miniaudio.h 3.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601
  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.19 - 2023-11-04
  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);
  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. You can enable the use of AudioWorkets by defining `MA_ENABLE_AUDIO_WORKLETS` and then compiling
  429. with the following options:
  430. -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY
  431. An example for compiling with AudioWorklet support might look like this:
  432. emcc program.c -o bin/program.html -DMA_ENABLE_AUDIO_WORKLETS -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY
  433. To run locally, you'll need to use emrun:
  434. emrun bin/program.html
  435. 2.7. Build Options
  436. ------------------
  437. `#define` these options before including miniaudio.h.
  438. +----------------------------------+--------------------------------------------------------------------+
  439. | Option | Description |
  440. +----------------------------------+--------------------------------------------------------------------+
  441. | MA_NO_WASAPI | Disables the WASAPI backend. |
  442. +----------------------------------+--------------------------------------------------------------------+
  443. | MA_NO_DSOUND | Disables the DirectSound backend. |
  444. +----------------------------------+--------------------------------------------------------------------+
  445. | MA_NO_WINMM | Disables the WinMM backend. |
  446. +----------------------------------+--------------------------------------------------------------------+
  447. | MA_NO_ALSA | Disables the ALSA backend. |
  448. +----------------------------------+--------------------------------------------------------------------+
  449. | MA_NO_PULSEAUDIO | Disables the PulseAudio backend. |
  450. +----------------------------------+--------------------------------------------------------------------+
  451. | MA_NO_JACK | Disables the JACK backend. |
  452. +----------------------------------+--------------------------------------------------------------------+
  453. | MA_NO_COREAUDIO | Disables the Core Audio backend. |
  454. +----------------------------------+--------------------------------------------------------------------+
  455. | MA_NO_SNDIO | Disables the sndio backend. |
  456. +----------------------------------+--------------------------------------------------------------------+
  457. | MA_NO_AUDIO4 | Disables the audio(4) backend. |
  458. +----------------------------------+--------------------------------------------------------------------+
  459. | MA_NO_OSS | Disables the OSS backend. |
  460. +----------------------------------+--------------------------------------------------------------------+
  461. | MA_NO_AAUDIO | Disables the AAudio backend. |
  462. +----------------------------------+--------------------------------------------------------------------+
  463. | MA_NO_OPENSL | Disables the OpenSL|ES backend. |
  464. +----------------------------------+--------------------------------------------------------------------+
  465. | MA_NO_WEBAUDIO | Disables the Web Audio backend. |
  466. +----------------------------------+--------------------------------------------------------------------+
  467. | MA_NO_NULL | Disables the null backend. |
  468. +----------------------------------+--------------------------------------------------------------------+
  469. | MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to |
  470. | | enable specific backends. |
  471. +----------------------------------+--------------------------------------------------------------------+
  472. | MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  473. | | enable the WASAPI backend. |
  474. +----------------------------------+--------------------------------------------------------------------+
  475. | MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  476. | | enable the DirectSound backend. |
  477. +----------------------------------+--------------------------------------------------------------------+
  478. | MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  479. | | enable the WinMM backend. |
  480. +----------------------------------+--------------------------------------------------------------------+
  481. | MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  482. | | enable the ALSA backend. |
  483. +----------------------------------+--------------------------------------------------------------------+
  484. | MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  485. | | enable the PulseAudio backend. |
  486. +----------------------------------+--------------------------------------------------------------------+
  487. | MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  488. | | enable the JACK backend. |
  489. +----------------------------------+--------------------------------------------------------------------+
  490. | MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  491. | | enable the Core Audio backend. |
  492. +----------------------------------+--------------------------------------------------------------------+
  493. | MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  494. | | enable the sndio backend. |
  495. +----------------------------------+--------------------------------------------------------------------+
  496. | MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  497. | | enable the audio(4) backend. |
  498. +----------------------------------+--------------------------------------------------------------------+
  499. | MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  500. | | enable the OSS backend. |
  501. +----------------------------------+--------------------------------------------------------------------+
  502. | MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  503. | | enable the AAudio backend. |
  504. +----------------------------------+--------------------------------------------------------------------+
  505. | MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  506. | | enable the OpenSL|ES backend. |
  507. +----------------------------------+--------------------------------------------------------------------+
  508. | MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  509. | | enable the Web Audio backend. |
  510. +----------------------------------+--------------------------------------------------------------------+
  511. | MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  512. | | enable the null backend. |
  513. +----------------------------------+--------------------------------------------------------------------+
  514. | MA_NO_DECODING | Disables decoding APIs. |
  515. +----------------------------------+--------------------------------------------------------------------+
  516. | MA_NO_ENCODING | Disables encoding APIs. |
  517. +----------------------------------+--------------------------------------------------------------------+
  518. | MA_NO_WAV | Disables the built-in WAV decoder and encoder. |
  519. +----------------------------------+--------------------------------------------------------------------+
  520. | MA_NO_FLAC | Disables the built-in FLAC decoder. |
  521. +----------------------------------+--------------------------------------------------------------------+
  522. | MA_NO_MP3 | Disables the built-in MP3 decoder. |
  523. +----------------------------------+--------------------------------------------------------------------+
  524. | MA_NO_DEVICE_IO | Disables playback and recording. This will disable `ma_context` |
  525. | | and `ma_device` APIs. This is useful if you only want to use |
  526. | | miniaudio's data conversion and/or decoding APIs. |
  527. +----------------------------------+--------------------------------------------------------------------+
  528. | MA_NO_RESOURCE_MANAGER | Disables the resource manager. When using the engine this will |
  529. | | also disable the following functions: |
  530. | | |
  531. | | ``` |
  532. | | ma_sound_init_from_file() |
  533. | | ma_sound_init_from_file_w() |
  534. | | ma_sound_init_copy() |
  535. | | ma_engine_play_sound_ex() |
  536. | | ma_engine_play_sound() |
  537. | | ``` |
  538. | | |
  539. | | The only way to initialize a `ma_sound` object is to initialize it |
  540. | | from a data source. |
  541. +----------------------------------+--------------------------------------------------------------------+
  542. | MA_NO_NODE_GRAPH | Disables the node graph API. This will also disable the engine API |
  543. | | because it depends on the node graph. |
  544. +----------------------------------+--------------------------------------------------------------------+
  545. | MA_NO_ENGINE | Disables the engine API. |
  546. +----------------------------------+--------------------------------------------------------------------+
  547. | MA_NO_THREADING | Disables the `ma_thread`, `ma_mutex`, `ma_semaphore` and |
  548. | | `ma_event` APIs. This option is useful if you only need to use |
  549. | | miniaudio for data conversion, decoding and/or encoding. Some |
  550. | | families of APIs require threading which means the following |
  551. | | options must also be set: |
  552. | | |
  553. | | ``` |
  554. | | MA_NO_DEVICE_IO |
  555. | | ``` |
  556. +----------------------------------+--------------------------------------------------------------------+
  557. | MA_NO_GENERATION | Disables generation APIs such a `ma_waveform` and `ma_noise`. |
  558. +----------------------------------+--------------------------------------------------------------------+
  559. | MA_NO_SSE2 | Disables SSE2 optimizations. |
  560. +----------------------------------+--------------------------------------------------------------------+
  561. | MA_NO_AVX2 | Disables AVX2 optimizations. |
  562. +----------------------------------+--------------------------------------------------------------------+
  563. | MA_NO_NEON | Disables NEON optimizations. |
  564. +----------------------------------+--------------------------------------------------------------------+
  565. | MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's |
  566. | | notarization process. When enabling this, you may need to avoid |
  567. | | using `-std=c89` or `-std=c99` on Linux builds or else you may end |
  568. | | up with compilation errors due to conflicts with `timespec` and |
  569. | | `timeval` data types. |
  570. | | |
  571. | | You may need to enable this if your target platform does not allow |
  572. | | runtime linking via `dlopen()`. |
  573. +----------------------------------+--------------------------------------------------------------------+
  574. | MA_DEBUG_OUTPUT | Enable `printf()` output of debug logs (`MA_LOG_LEVEL_DEBUG`). |
  575. +----------------------------------+--------------------------------------------------------------------+
  576. | MA_COINIT_VALUE | Windows only. The value to pass to internal calls to |
  577. | | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. |
  578. +----------------------------------+--------------------------------------------------------------------+
  579. | MA_API | Controls how public APIs should be decorated. Default is `extern`. |
  580. +----------------------------------+--------------------------------------------------------------------+
  581. 3. Definitions
  582. ==============
  583. This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity
  584. in the use of terms throughout the audio space, so this section is intended to clarify how miniaudio
  585. uses each term.
  586. 3.1. Sample
  587. -----------
  588. A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit
  589. floating point number.
  590. 3.2. Frame / PCM Frame
  591. ----------------------
  592. A frame is a group of samples equal to the number of channels. For a stereo stream a frame is 2
  593. samples, a mono frame is 1 sample, a 5.1 surround sound frame is 6 samples, etc. The terms "frame"
  594. and "PCM frame" are the same thing in miniaudio. Note that this is different to a compressed frame.
  595. If ever miniaudio needs to refer to a compressed frame, such as a FLAC frame, it will always
  596. clarify what it's referring to with something like "FLAC frame".
  597. 3.3. Channel
  598. ------------
  599. A stream of monaural audio that is emitted from an individual speaker in a speaker system, or
  600. received from an individual microphone in a microphone system. A stereo stream has two channels (a
  601. left channel, and a right channel), a 5.1 surround sound system has 6 channels, etc. Some audio
  602. systems refer to a channel as a complex audio stream that's mixed with other channels to produce
  603. the final mix - this is completely different to miniaudio's use of the term "channel" and should
  604. not be confused.
  605. 3.4. Sample Rate
  606. ----------------
  607. The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number
  608. of PCM frames that are processed per second.
  609. 3.5. Formats
  610. ------------
  611. Throughout miniaudio you will see references to different sample formats:
  612. +---------------+----------------------------------------+---------------------------+
  613. | Symbol | Description | Range |
  614. +---------------+----------------------------------------+---------------------------+
  615. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  616. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  617. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  618. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  619. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  620. +---------------+----------------------------------------+---------------------------+
  621. All formats are native-endian.
  622. 4. Data Sources
  623. ===============
  624. The data source abstraction in miniaudio is used for retrieving audio data from some source. A few
  625. examples include `ma_decoder`, `ma_noise` and `ma_waveform`. You will need to be familiar with data
  626. sources in order to make sense of some of the higher level concepts in miniaudio.
  627. The `ma_data_source` API is a generic interface for reading from a data source. Any object that
  628. implements the data source interface can be plugged into any `ma_data_source` function.
  629. To read data from a data source:
  630. ```c
  631. ma_result result;
  632. ma_uint64 framesRead;
  633. result = ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, &framesRead);
  634. if (result != MA_SUCCESS) {
  635. return result; // Failed to read data from the data source.
  636. }
  637. ```
  638. If you don't need the number of frames that were successfully read you can pass in `NULL` to the
  639. `pFramesRead` parameter. If this returns a value less than the number of frames requested it means
  640. the end of the file has been reached. `MA_AT_END` will be returned only when the number of frames
  641. read is 0.
  642. When calling any data source function, with the exception of `ma_data_source_init()` and
  643. `ma_data_source_uninit()`, you can pass in any object that implements a data source. For example,
  644. you could plug in a decoder like so:
  645. ```c
  646. ma_result result;
  647. ma_uint64 framesRead;
  648. ma_decoder decoder; // <-- This would be initialized with `ma_decoder_init_*()`.
  649. result = ma_data_source_read_pcm_frames(&decoder, pFramesOut, frameCount, &framesRead);
  650. if (result != MA_SUCCESS) {
  651. return result; // Failed to read data from the decoder.
  652. }
  653. ```
  654. If you want to seek forward you can pass in `NULL` to the `pFramesOut` parameter. Alternatively you
  655. can use `ma_data_source_seek_pcm_frames()`.
  656. To seek to a specific PCM frame:
  657. ```c
  658. result = ma_data_source_seek_to_pcm_frame(pDataSource, frameIndex);
  659. if (result != MA_SUCCESS) {
  660. return result; // Failed to seek to PCM frame.
  661. }
  662. ```
  663. You can retrieve the total length of a data source in PCM frames, but note that some data sources
  664. may not have the notion of a length, such as noise and waveforms, and others may just not have a
  665. way of determining the length such as some decoders. To retrieve the length:
  666. ```c
  667. ma_uint64 length;
  668. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &length);
  669. if (result != MA_SUCCESS) {
  670. return result; // Failed to retrieve the length.
  671. }
  672. ```
  673. Care should be taken when retrieving the length of a data source where the underlying decoder is
  674. pulling data from a data stream with an undefined length, such as internet radio or some kind of
  675. broadcast. If you do this, `ma_data_source_get_length_in_pcm_frames()` may never return.
  676. The current position of the cursor in PCM frames can also be retrieved:
  677. ```c
  678. ma_uint64 cursor;
  679. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor);
  680. if (result != MA_SUCCESS) {
  681. return result; // Failed to retrieve the cursor.
  682. }
  683. ```
  684. You will often need to know the data format that will be returned after reading. This can be
  685. retrieved like so:
  686. ```c
  687. ma_format format;
  688. ma_uint32 channels;
  689. ma_uint32 sampleRate;
  690. ma_channel channelMap[MA_MAX_CHANNELS];
  691. result = ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate, channelMap, MA_MAX_CHANNELS);
  692. if (result != MA_SUCCESS) {
  693. return result; // Failed to retrieve data format.
  694. }
  695. ```
  696. If you do not need a specific data format property, just pass in NULL to the respective parameter.
  697. There may be cases where you want to implement something like a sound bank where you only want to
  698. read data within a certain range of the underlying data. To do this you can use a range:
  699. ```c
  700. result = ma_data_source_set_range_in_pcm_frames(pDataSource, rangeBegInFrames, rangeEndInFrames);
  701. if (result != MA_SUCCESS) {
  702. return result; // Failed to set the range.
  703. }
  704. ```
  705. This is useful if you have a sound bank where many sounds are stored in the same file and you want
  706. the data source to only play one of those sub-sounds. Note that once the range is set, everything
  707. that takes a position, such as cursors and loop points, should always be relatvie to the start of
  708. the range. When the range is set, any previously defined loop point will be reset.
  709. Custom loop points can also be used with data sources. By default, data sources will loop after
  710. they reach the end of the data source, but if you need to loop at a specific location, you can do
  711. the following:
  712. ```c
  713. result = ma_data_set_loop_point_in_pcm_frames(pDataSource, loopBegInFrames, loopEndInFrames);
  714. if (result != MA_SUCCESS) {
  715. return result; // Failed to set the loop point.
  716. }
  717. ```
  718. The loop point is relative to the current range.
  719. It's sometimes useful to chain data sources together so that a seamless transition can be achieved.
  720. To do this, you can use chaining:
  721. ```c
  722. ma_decoder decoder1;
  723. ma_decoder decoder2;
  724. // ... initialize decoders with ma_decoder_init_*() ...
  725. result = ma_data_source_set_next(&decoder1, &decoder2);
  726. if (result != MA_SUCCESS) {
  727. return result; // Failed to set the next data source.
  728. }
  729. result = ma_data_source_read_pcm_frames(&decoder1, pFramesOut, frameCount, pFramesRead);
  730. if (result != MA_SUCCESS) {
  731. return result; // Failed to read from the decoder.
  732. }
  733. ```
  734. In the example above we're using decoders. When reading from a chain, you always want to read from
  735. the top level data source in the chain. In the example above, `decoder1` is the top level data
  736. source in the chain. When `decoder1` reaches the end, `decoder2` will start seamlessly without any
  737. gaps.
  738. Note that when looping is enabled, only the current data source will be looped. You can loop the
  739. entire chain by linking in a loop like so:
  740. ```c
  741. ma_data_source_set_next(&decoder1, &decoder2); // decoder1 -> decoder2
  742. ma_data_source_set_next(&decoder2, &decoder1); // decoder2 -> decoder1 (loop back to the start).
  743. ```
  744. Note that setting up chaining is not thread safe, so care needs to be taken if you're dynamically
  745. changing links while the audio thread is in the middle of reading.
  746. Do not use `ma_decoder_seek_to_pcm_frame()` as a means to reuse a data source to play multiple
  747. instances of the same sound simultaneously. This can be extremely inefficient depending on the type
  748. of data source and can result in glitching due to subtle changes to the state of internal filters.
  749. Instead, initialize multiple data sources for each instance.
  750. 4.1. Custom Data Sources
  751. ------------------------
  752. You can implement a custom data source by implementing the functions in `ma_data_source_vtable`.
  753. Your custom object must have `ma_data_source_base` as it's first member:
  754. ```c
  755. struct my_data_source
  756. {
  757. ma_data_source_base base;
  758. ...
  759. };
  760. ```
  761. In your initialization routine, you need to call `ma_data_source_init()` in order to set up the
  762. base object (`ma_data_source_base`):
  763. ```c
  764. static ma_result my_data_source_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  765. {
  766. // Read data here. Output in the same format returned by my_data_source_get_data_format().
  767. }
  768. static ma_result my_data_source_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  769. {
  770. // Seek to a specific PCM frame here. Return MA_NOT_IMPLEMENTED if seeking is not supported.
  771. }
  772. 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)
  773. {
  774. // Return the format of the data here.
  775. }
  776. static ma_result my_data_source_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  777. {
  778. // 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.
  779. }
  780. static ma_result my_data_source_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  781. {
  782. // 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.
  783. }
  784. static ma_data_source_vtable g_my_data_source_vtable =
  785. {
  786. my_data_source_read,
  787. my_data_source_seek,
  788. my_data_source_get_data_format,
  789. my_data_source_get_cursor,
  790. my_data_source_get_length
  791. };
  792. ma_result my_data_source_init(my_data_source* pMyDataSource)
  793. {
  794. ma_result result;
  795. ma_data_source_config baseConfig;
  796. baseConfig = ma_data_source_config_init();
  797. baseConfig.vtable = &g_my_data_source_vtable;
  798. result = ma_data_source_init(&baseConfig, &pMyDataSource->base);
  799. if (result != MA_SUCCESS) {
  800. return result;
  801. }
  802. // ... do the initialization of your custom data source here ...
  803. return MA_SUCCESS;
  804. }
  805. void my_data_source_uninit(my_data_source* pMyDataSource)
  806. {
  807. // ... do the uninitialization of your custom data source here ...
  808. // You must uninitialize the base data source.
  809. ma_data_source_uninit(&pMyDataSource->base);
  810. }
  811. ```
  812. Note that `ma_data_source_init()` and `ma_data_source_uninit()` are never called directly outside
  813. of the custom data source. It's up to the custom data source itself to call these within their own
  814. init/uninit functions.
  815. 5. Engine
  816. =========
  817. The `ma_engine` API is a high level API for managing and mixing sounds and effect processing. The
  818. `ma_engine` object encapsulates a resource manager and a node graph, both of which will be
  819. explained in more detail later.
  820. Sounds are called `ma_sound` and are created from an engine. Sounds can be associated with a mixing
  821. group called `ma_sound_group` which are also created from the engine. Both `ma_sound` and
  822. `ma_sound_group` objects are nodes within the engine's node graph.
  823. When the engine is initialized, it will normally create a device internally. If you would rather
  824. manage the device yourself, you can do so and just pass a pointer to it via the engine config when
  825. you initialize the engine. You can also just use the engine without a device, which again can be
  826. configured via the engine config.
  827. The most basic way to initialize the engine is with a default config, like so:
  828. ```c
  829. ma_result result;
  830. ma_engine engine;
  831. result = ma_engine_init(NULL, &engine);
  832. if (result != MA_SUCCESS) {
  833. return result; // Failed to initialize the engine.
  834. }
  835. ```
  836. This will result in the engine initializing a playback device using the operating system's default
  837. device. This will be sufficient for many use cases, but if you need more flexibility you'll want to
  838. configure the engine with an engine config:
  839. ```c
  840. ma_result result;
  841. ma_engine engine;
  842. ma_engine_config engineConfig;
  843. engineConfig = ma_engine_config_init();
  844. engineConfig.pDevice = &myDevice;
  845. result = ma_engine_init(&engineConfig, &engine);
  846. if (result != MA_SUCCESS) {
  847. return result; // Failed to initialize the engine.
  848. }
  849. ```
  850. In the example above we're passing in a pre-initialized device. Since the caller is the one in
  851. control of the device's data callback, it's their responsibility to manually call
  852. `ma_engine_read_pcm_frames()` from inside their data callback:
  853. ```c
  854. void playback_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  855. {
  856. ma_engine_read_pcm_frames(&g_Engine, pOutput, frameCount, NULL);
  857. }
  858. ```
  859. You can also use the engine independent of a device entirely:
  860. ```c
  861. ma_result result;
  862. ma_engine engine;
  863. ma_engine_config engineConfig;
  864. engineConfig = ma_engine_config_init();
  865. engineConfig.noDevice = MA_TRUE;
  866. engineConfig.channels = 2; // Must be set when not using a device.
  867. engineConfig.sampleRate = 48000; // Must be set when not using a device.
  868. result = ma_engine_init(&engineConfig, &engine);
  869. if (result != MA_SUCCESS) {
  870. return result; // Failed to initialize the engine.
  871. }
  872. ```
  873. Note that when you're not using a device, you must set the channel count and sample rate in the
  874. config or else miniaudio won't know what to use (miniaudio will use the device to determine this
  875. normally). When not using a device, you need to use `ma_engine_read_pcm_frames()` to process audio
  876. data from the engine. This kind of setup is useful if you want to do something like offline
  877. processing or want to use a different audio system for playback such as SDL.
  878. When a sound is loaded it goes through a resource manager. By default the engine will initialize a
  879. resource manager internally, but you can also specify a pre-initialized resource manager:
  880. ```c
  881. ma_result result;
  882. ma_engine engine1;
  883. ma_engine engine2;
  884. ma_engine_config engineConfig;
  885. engineConfig = ma_engine_config_init();
  886. engineConfig.pResourceManager = &myResourceManager;
  887. ma_engine_init(&engineConfig, &engine1);
  888. ma_engine_init(&engineConfig, &engine2);
  889. ```
  890. In this example we are initializing two engines, both of which are sharing the same resource
  891. manager. This is especially useful for saving memory when loading the same file across multiple
  892. engines. If you were not to use a shared resource manager, each engine instance would use their own
  893. which would result in any sounds that are used between both engine's being loaded twice. By using
  894. a shared resource manager, it would only be loaded once. Using multiple engine's is useful when you
  895. need to output to multiple playback devices, such as in a local multiplayer game where each player
  896. is using their own set of headphones.
  897. By default an engine will be in a started state. To make it so the engine is not automatically
  898. started you can configure it as such:
  899. ```c
  900. engineConfig.noAutoStart = MA_TRUE;
  901. // The engine will need to be started manually.
  902. ma_engine_start(&engine);
  903. // Later on the engine can be stopped with ma_engine_stop().
  904. ma_engine_stop(&engine);
  905. ```
  906. The concept of starting or stopping an engine is only relevant when using the engine with a
  907. device. Attempting to start or stop an engine that is not associated with a device will result in
  908. `MA_INVALID_OPERATION`.
  909. The master volume of the engine can be controlled with `ma_engine_set_volume()` which takes a
  910. linear scale, with 0 resulting in silence and anything above 1 resulting in amplification. If you
  911. prefer decibel based volume control, use `ma_volume_db_to_linear()` to convert from dB to linear.
  912. When a sound is spatialized, it is done so relative to a listener. An engine can be configured to
  913. have multiple listeners which can be configured via the config:
  914. ```c
  915. engineConfig.listenerCount = 2;
  916. ```
  917. The maximum number of listeners is restricted to `MA_ENGINE_MAX_LISTENERS`. By default, when a
  918. sound is spatialized, it will be done so relative to the closest listener. You can also pin a sound
  919. to a specific listener which will be explained later. Listener's have a position, direction, cone,
  920. and velocity (for doppler effect). A listener is referenced by an index, the meaning of which is up
  921. to the caller (the index is 0 based and cannot go beyond the listener count, minus 1). The
  922. position, direction and velocity are all specified in absolute terms:
  923. ```c
  924. ma_engine_listener_set_position(&engine, listenerIndex, worldPosX, worldPosY, worldPosZ);
  925. ```
  926. The direction of the listener represents it's forward vector. The listener's up vector can also be
  927. specified and defaults to +1 on the Y axis.
  928. ```c
  929. ma_engine_listener_set_direction(&engine, listenerIndex, forwardX, forwardY, forwardZ);
  930. ma_engine_listener_set_world_up(&engine, listenerIndex, 0, 1, 0);
  931. ```
  932. The engine supports directional attenuation. The listener can have a cone the controls how sound is
  933. attenuated based on the listener's direction. When a sound is between the inner and outer cones, it
  934. will be attenuated between 1 and the cone's outer gain:
  935. ```c
  936. ma_engine_listener_set_cone(&engine, listenerIndex, innerAngleInRadians, outerAngleInRadians, outerGain);
  937. ```
  938. When a sound is inside the inner code, no directional attenuation is applied. When the sound is
  939. outside of the outer cone, the attenuation will be set to `outerGain` in the example above. When
  940. the sound is in between the inner and outer cones, the attenuation will be interpolated between 1
  941. and the outer gain.
  942. The engine's coordinate system follows the OpenGL coordinate system where positive X points right,
  943. positive Y points up and negative Z points forward.
  944. The simplest and least flexible way to play a sound is like so:
  945. ```c
  946. ma_engine_play_sound(&engine, "my_sound.wav", pGroup);
  947. ```
  948. This is a "fire and forget" style of function. The engine will manage the `ma_sound` object
  949. internally. When the sound finishes playing, it'll be put up for recycling. For more flexibility
  950. you'll want to initialize a sound object:
  951. ```c
  952. ma_sound sound;
  953. result = ma_sound_init_from_file(&engine, "my_sound.wav", flags, pGroup, NULL, &sound);
  954. if (result != MA_SUCCESS) {
  955. return result; // Failed to load sound.
  956. }
  957. ```
  958. Sounds need to be uninitialized with `ma_sound_uninit()`.
  959. The example above loads a sound from a file. If the resource manager has been disabled you will not
  960. be able to use this function and instead you'll need to initialize a sound directly from a data
  961. source:
  962. ```c
  963. ma_sound sound;
  964. result = ma_sound_init_from_data_source(&engine, &dataSource, flags, pGroup, &sound);
  965. if (result != MA_SUCCESS) {
  966. return result;
  967. }
  968. ```
  969. Each `ma_sound` object represents a single instance of the sound. If you want to play the same
  970. sound multiple times at the same time, you need to initialize a separate `ma_sound` object.
  971. For the most flexibility when initializing sounds, use `ma_sound_init_ex()`. This uses miniaudio's
  972. standard config/init pattern:
  973. ```c
  974. ma_sound sound;
  975. ma_sound_config soundConfig;
  976. soundConfig = ma_sound_config_init();
  977. soundConfig.pFilePath = NULL; // Set this to load from a file path.
  978. soundConfig.pDataSource = NULL; // Set this to initialize from an existing data source.
  979. soundConfig.pInitialAttachment = &someNodeInTheNodeGraph;
  980. soundConfig.initialAttachmentInputBusIndex = 0;
  981. soundConfig.channelsIn = 1;
  982. soundConfig.channelsOut = 0; // Set to 0 to use the engine's native channel count.
  983. result = ma_sound_init_ex(&soundConfig, &sound);
  984. if (result != MA_SUCCESS) {
  985. return result;
  986. }
  987. ```
  988. In the example above, the sound is being initialized without a file nor a data source. This is
  989. valid, in which case the sound acts as a node in the middle of the node graph. This means you can
  990. connect other sounds to this sound and allow it to act like a sound group. Indeed, this is exactly
  991. what a `ma_sound_group` is.
  992. When loading a sound, you specify a set of flags that control how the sound is loaded and what
  993. features are enabled for that sound. When no flags are set, the sound will be fully loaded into
  994. memory in exactly the same format as how it's stored on the file system. The resource manager will
  995. allocate a block of memory and then load the file directly into it. When reading audio data, it
  996. will be decoded dynamically on the fly. In order to save processing time on the audio thread, it
  997. might be beneficial to pre-decode the sound. You can do this with the `MA_SOUND_FLAG_DECODE` flag:
  998. ```c
  999. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE, pGroup, NULL, &sound);
  1000. ```
  1001. By default, sounds will be loaded synchronously, meaning `ma_sound_init_*()` will not return until
  1002. the sound has been fully loaded. If this is prohibitive you can instead load sounds asynchronously
  1003. by specifying the `MA_SOUND_FLAG_ASYNC` flag:
  1004. ```c
  1005. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, NULL, &sound);
  1006. ```
  1007. This will result in `ma_sound_init_*()` returning quickly, but the sound won't yet have been fully
  1008. loaded. When you start the sound, it won't output anything until some sound is available. The sound
  1009. will start outputting audio before the sound has been fully decoded when the `MA_SOUND_FLAG_DECODE`
  1010. is specified.
  1011. If you need to wait for an asynchronously loaded sound to be fully loaded, you can use a fence. A
  1012. fence in miniaudio is a simple synchronization mechanism which simply blocks until it's internal
  1013. counter hit's zero. You can specify a fence like so:
  1014. ```c
  1015. ma_result result;
  1016. ma_fence fence;
  1017. ma_sound sounds[4];
  1018. result = ma_fence_init(&fence);
  1019. if (result != MA_SUCCESS) {
  1020. return result;
  1021. }
  1022. // Load some sounds asynchronously.
  1023. for (int iSound = 0; iSound < 4; iSound += 1) {
  1024. ma_sound_init_from_file(&engine, mySoundFilesPaths[iSound], MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, &fence, &sounds[iSound]);
  1025. }
  1026. // ... do some other stuff here in the mean time ...
  1027. // Wait for all sounds to finish loading.
  1028. ma_fence_wait(&fence);
  1029. ```
  1030. If loading the entire sound into memory is prohibitive, you can also configure the engine to stream
  1031. the audio data:
  1032. ```c
  1033. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_STREAM, pGroup, NULL, &sound);
  1034. ```
  1035. When streaming sounds, 2 seconds worth of audio data is stored in memory. Although it should work
  1036. fine, it's inefficient to use streaming for short sounds. Streaming is useful for things like music
  1037. tracks in games.
  1038. When loading a sound from a file path, the engine will reference count the file to prevent it from
  1039. being loaded if it's already in memory. When you uninitialize a sound, the reference count will be
  1040. decremented, and if it hits zero, the sound will be unloaded from memory. This reference counting
  1041. system is not used for streams. The engine will use a 64-bit hash of the file name when comparing
  1042. file paths which means there's a small chance you might encounter a name collision. If this is an
  1043. issue, you'll need to use a different name for one of the colliding file paths, or just not load
  1044. from files and instead load from a data source.
  1045. You can use `ma_sound_init_copy()` to initialize a copy of another sound. Note, however, that this
  1046. only works for sounds that were initialized with `ma_sound_init_from_file()` and without the
  1047. `MA_SOUND_FLAG_STREAM` flag.
  1048. When you initialize a sound, if you specify a sound group the sound will be attached to that group
  1049. automatically. If you set it to NULL, it will be automatically attached to the engine's endpoint.
  1050. If you would instead rather leave the sound unattached by default, you can can specify the
  1051. `MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT` flag. This is useful if you want to set up a complex node
  1052. graph.
  1053. Sounds are not started by default. To start a sound, use `ma_sound_start()`. Stop a sound with
  1054. `ma_sound_stop()`.
  1055. Sounds can have their volume controlled with `ma_sound_set_volume()` in the same way as the
  1056. engine's master volume.
  1057. Sounds support stereo panning and pitching. Set the pan with `ma_sound_set_pan()`. Setting the pan
  1058. to 0 will result in an unpanned sound. Setting it to -1 will shift everything to the left, whereas
  1059. +1 will shift it to the right. The pitch can be controlled with `ma_sound_set_pitch()`. A larger
  1060. value will result in a higher pitch. The pitch must be greater than 0.
  1061. The engine supports 3D spatialization of sounds. By default sounds will have spatialization
  1062. enabled, but if a sound does not need to be spatialized it's best to disable it. There are two ways
  1063. to disable spatialization of a sound:
  1064. ```c
  1065. // Disable spatialization at initialization time via a flag:
  1066. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_NO_SPATIALIZATION, NULL, NULL, &sound);
  1067. // Dynamically disable or enable spatialization post-initialization:
  1068. ma_sound_set_spatialization_enabled(&sound, isSpatializationEnabled);
  1069. ```
  1070. By default sounds will be spatialized based on the closest listener. If a sound should always be
  1071. spatialized relative to a specific listener it can be pinned to one:
  1072. ```c
  1073. ma_sound_set_pinned_listener_index(&sound, listenerIndex);
  1074. ```
  1075. Like listeners, sounds have a position. By default, the position of a sound is in absolute space,
  1076. but it can be changed to be relative to a listener:
  1077. ```c
  1078. ma_sound_set_positioning(&sound, ma_positioning_relative);
  1079. ```
  1080. Note that relative positioning of a sound only makes sense if there is either only one listener, or
  1081. the sound is pinned to a specific listener. To set the position of a sound:
  1082. ```c
  1083. ma_sound_set_position(&sound, posX, posY, posZ);
  1084. ```
  1085. The direction works the same way as a listener and represents the sound's forward direction:
  1086. ```c
  1087. ma_sound_set_direction(&sound, forwardX, forwardY, forwardZ);
  1088. ```
  1089. Sound's also have a cone for controlling directional attenuation. This works exactly the same as
  1090. listeners:
  1091. ```c
  1092. ma_sound_set_cone(&sound, innerAngleInRadians, outerAngleInRadians, outerGain);
  1093. ```
  1094. The velocity of a sound is used for doppler effect and can be set as such:
  1095. ```c
  1096. ma_sound_set_velocity(&sound, velocityX, velocityY, velocityZ);
  1097. ```
  1098. The engine supports different attenuation models which can be configured on a per-sound basis. By
  1099. default the attenuation model is set to `ma_attenuation_model_inverse` which is the equivalent to
  1100. OpenAL's `AL_INVERSE_DISTANCE_CLAMPED`. Configure the attenuation model like so:
  1101. ```c
  1102. ma_sound_set_attenuation_model(&sound, ma_attenuation_model_inverse);
  1103. ```
  1104. The supported attenuation models include the following:
  1105. +----------------------------------+----------------------------------------------+
  1106. | ma_attenuation_model_none | No distance attenuation. |
  1107. +----------------------------------+----------------------------------------------+
  1108. | ma_attenuation_model_inverse | Equivalent to `AL_INVERSE_DISTANCE_CLAMPED`. |
  1109. +----------------------------------+----------------------------------------------+
  1110. | ma_attenuation_model_linear | Linear attenuation. |
  1111. +----------------------------------+----------------------------------------------+
  1112. | ma_attenuation_model_exponential | Exponential attenuation. |
  1113. +----------------------------------+----------------------------------------------+
  1114. To control how quickly a sound rolls off as it moves away from the listener, you need to configure
  1115. the rolloff:
  1116. ```c
  1117. ma_sound_set_rolloff(&sound, rolloff);
  1118. ```
  1119. You can control the minimum and maximum gain to apply from spatialization:
  1120. ```c
  1121. ma_sound_set_min_gain(&sound, minGain);
  1122. ma_sound_set_max_gain(&sound, maxGain);
  1123. ```
  1124. Likewise, in the calculation of attenuation, you can control the minimum and maximum distances for
  1125. the attenuation calculation. This is useful if you want to ensure sounds don't drop below a certain
  1126. volume after the listener moves further away and to have sounds play a maximum volume when the
  1127. listener is within a certain distance:
  1128. ```c
  1129. ma_sound_set_min_distance(&sound, minDistance);
  1130. ma_sound_set_max_distance(&sound, maxDistance);
  1131. ```
  1132. The engine's spatialization system supports doppler effect. The doppler factor can be configure on
  1133. a per-sound basis like so:
  1134. ```c
  1135. ma_sound_set_doppler_factor(&sound, dopplerFactor);
  1136. ```
  1137. You can fade sounds in and out with `ma_sound_set_fade_in_pcm_frames()` and
  1138. `ma_sound_set_fade_in_milliseconds()`. Set the volume to -1 to use the current volume as the
  1139. starting volume:
  1140. ```c
  1141. // Fade in over 1 second.
  1142. ma_sound_set_fade_in_milliseconds(&sound, 0, 1, 1000);
  1143. // ... sometime later ...
  1144. // Fade out over 1 second, starting from the current volume.
  1145. ma_sound_set_fade_in_milliseconds(&sound, -1, 0, 1000);
  1146. ```
  1147. By default sounds will start immediately, but sometimes for timing and synchronization purposes it
  1148. can be useful to schedule a sound to start or stop:
  1149. ```c
  1150. // Start the sound in 1 second from now.
  1151. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 1));
  1152. // Stop the sound in 2 seconds from now.
  1153. ma_sound_set_stop_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2));
  1154. ```
  1155. Note that scheduling a start time still requires an explicit call to `ma_sound_start()` before
  1156. anything will play.
  1157. The time is specified in global time which is controlled by the engine. You can get the engine's
  1158. current time with `ma_engine_get_time_in_pcm_frames()`. The engine's global time is incremented
  1159. automatically as audio data is read, but it can be reset with `ma_engine_set_time_in_pcm_frames()`
  1160. in case it needs to be resynchronized for some reason.
  1161. To determine whether or not a sound is currently playing, use `ma_sound_is_playing()`. This will
  1162. take the scheduled start and stop times into account.
  1163. Whether or not a sound should loop can be controlled with `ma_sound_set_looping()`. Sounds will not
  1164. be looping by default. Use `ma_sound_is_looping()` to determine whether or not a sound is looping.
  1165. Use `ma_sound_at_end()` to determine whether or not a sound is currently at the end. For a looping
  1166. sound this should never return true. Alternatively, you can configure a callback that will be fired
  1167. when the sound reaches the end. Note that the callback is fired from the audio thread which means
  1168. you cannot be uninitializing sound from the callback. To set the callback you can use
  1169. `ma_sound_set_end_callback()`. Alternatively, if you're using `ma_sound_init_ex()`, you can pass it
  1170. into the config like so:
  1171. ```c
  1172. soundConfig.endCallback = my_end_callback;
  1173. soundConfig.pEndCallbackUserData = pMyEndCallbackUserData;
  1174. ```
  1175. The end callback is declared like so:
  1176. ```c
  1177. void my_end_callback(void* pUserData, ma_sound* pSound)
  1178. {
  1179. ...
  1180. }
  1181. ```
  1182. Internally a sound wraps around a data source. Some APIs exist to control the underlying data
  1183. source, mainly for convenience:
  1184. ```c
  1185. ma_sound_seek_to_pcm_frame(&sound, frameIndex);
  1186. ma_sound_get_data_format(&sound, &format, &channels, &sampleRate, pChannelMap, channelMapCapacity);
  1187. ma_sound_get_cursor_in_pcm_frames(&sound, &cursor);
  1188. ma_sound_get_length_in_pcm_frames(&sound, &length);
  1189. ```
  1190. Sound groups have the same API as sounds, only they are called `ma_sound_group`, and since they do
  1191. not have any notion of a data source, anything relating to a data source is unavailable.
  1192. Internally, sound data is loaded via the `ma_decoder` API which means by default it only supports
  1193. file formats that have built-in support in miniaudio. You can extend this to support any kind of
  1194. file format through the use of custom decoders. To do this you'll need to use a self-managed
  1195. resource manager and configure it appropriately. See the "Resource Management" section below for
  1196. details on how to set this up.
  1197. 6. Resource Management
  1198. ======================
  1199. Many programs will want to manage sound resources for things such as reference counting and
  1200. streaming. This is supported by miniaudio via the `ma_resource_manager` API.
  1201. The resource manager is mainly responsible for the following:
  1202. * Loading of sound files into memory with reference counting.
  1203. * Streaming of sound data.
  1204. When loading a sound file, the resource manager will give you back a `ma_data_source` compatible
  1205. object called `ma_resource_manager_data_source`. This object can be passed into any
  1206. `ma_data_source` API which is how you can read and seek audio data. When loading a sound file, you
  1207. specify whether or not you want the sound to be fully loaded into memory (and optionally
  1208. pre-decoded) or streamed. When loading into memory, you can also specify whether or not you want
  1209. the data to be loaded asynchronously.
  1210. The example below is how you can initialize a resource manager using it's default configuration:
  1211. ```c
  1212. ma_resource_manager_config config;
  1213. ma_resource_manager resourceManager;
  1214. config = ma_resource_manager_config_init();
  1215. result = ma_resource_manager_init(&config, &resourceManager);
  1216. if (result != MA_SUCCESS) {
  1217. ma_device_uninit(&device);
  1218. printf("Failed to initialize the resource manager.");
  1219. return -1;
  1220. }
  1221. ```
  1222. You can configure the format, channels and sample rate of the decoded audio data. By default it
  1223. will use the file's native data format, but you can configure it to use a consistent format. This
  1224. is useful for offloading the cost of data conversion to load time rather than dynamically
  1225. converting at mixing time. To do this, you configure the decoded format, channels and sample rate
  1226. like the code below:
  1227. ```c
  1228. config = ma_resource_manager_config_init();
  1229. config.decodedFormat = device.playback.format;
  1230. config.decodedChannels = device.playback.channels;
  1231. config.decodedSampleRate = device.sampleRate;
  1232. ```
  1233. In the code above, the resource manager will be configured so that any decoded audio data will be
  1234. pre-converted at load time to the device's native data format. If instead you used defaults and
  1235. the data format of the file did not match the device's data format, you would need to convert the
  1236. data at mixing time which may be prohibitive in high-performance and large scale scenarios like
  1237. games.
  1238. Internally the resource manager uses the `ma_decoder` API to load sounds. This means by default it
  1239. only supports decoders that are built into miniaudio. It's possible to support additional encoding
  1240. formats through the use of custom decoders. To do so, pass in your `ma_decoding_backend_vtable`
  1241. vtables into the resource manager config:
  1242. ```c
  1243. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  1244. {
  1245. &g_ma_decoding_backend_vtable_libvorbis,
  1246. &g_ma_decoding_backend_vtable_libopus
  1247. };
  1248. ...
  1249. resourceManagerConfig.ppCustomDecodingBackendVTables = pCustomBackendVTables;
  1250. resourceManagerConfig.customDecodingBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  1251. resourceManagerConfig.pCustomDecodingBackendUserData = NULL;
  1252. ```
  1253. This system can allow you to support any kind of file format. See the "Decoding" section for
  1254. details on how to implement custom decoders. The miniaudio repository includes examples for Opus
  1255. via libopus and libopusfile and Vorbis via libvorbis and libvorbisfile.
  1256. Asynchronicity is achieved via a job system. When an operation needs to be performed, such as the
  1257. decoding of a page, a job will be posted to a queue which will then be processed by a job thread.
  1258. By default there will be only one job thread running, but this can be configured, like so:
  1259. ```c
  1260. config = ma_resource_manager_config_init();
  1261. config.jobThreadCount = MY_JOB_THREAD_COUNT;
  1262. ```
  1263. By default job threads are managed internally by the resource manager, however you can also self
  1264. manage your job threads if, for example, you want to integrate the job processing into your
  1265. existing job infrastructure, or if you simply don't like the way the resource manager does it. To
  1266. do this, just set the job thread count to 0 and process jobs manually. To process jobs, you first
  1267. need to retrieve a job using `ma_resource_manager_next_job()` and then process it using
  1268. `ma_job_process()`:
  1269. ```c
  1270. config = ma_resource_manager_config_init();
  1271. config.jobThreadCount = 0; // Don't manage any job threads internally.
  1272. config.flags = MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; // Optional. Makes `ma_resource_manager_next_job()` non-blocking.
  1273. // ... Initialize your custom job threads ...
  1274. void my_custom_job_thread(...)
  1275. {
  1276. for (;;) {
  1277. ma_job job;
  1278. ma_result result = ma_resource_manager_next_job(pMyResourceManager, &job);
  1279. if (result != MA_SUCCESS) {
  1280. if (result == MA_NO_DATA_AVAILABLE) {
  1281. // No jobs are available. Keep going. Will only get this if the resource manager was initialized
  1282. // with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING.
  1283. continue;
  1284. } else if (result == MA_CANCELLED) {
  1285. // MA_JOB_TYPE_QUIT was posted. Exit.
  1286. break;
  1287. } else {
  1288. // Some other error occurred.
  1289. break;
  1290. }
  1291. }
  1292. ma_job_process(&job);
  1293. }
  1294. }
  1295. ```
  1296. In the example above, the `MA_JOB_TYPE_QUIT` event is the used as the termination
  1297. indicator, but you can use whatever you would like to terminate the thread. The call to
  1298. `ma_resource_manager_next_job()` is blocking by default, but can be configured to be non-blocking
  1299. by initializing the resource manager with the `MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING` configuration
  1300. flag. Note that the `MA_JOB_TYPE_QUIT` will never be removed from the job queue. This
  1301. is to give every thread the opportunity to catch the event and terminate naturally.
  1302. When loading a file, it's sometimes convenient to be able to customize how files are opened and
  1303. read instead of using standard `fopen()`, `fclose()`, etc. which is what miniaudio will use by
  1304. default. This can be done by setting `pVFS` member of the resource manager's config:
  1305. ```c
  1306. // Initialize your custom VFS object. See documentation for VFS for information on how to do this.
  1307. my_custom_vfs vfs = my_custom_vfs_init();
  1308. config = ma_resource_manager_config_init();
  1309. config.pVFS = &vfs;
  1310. ```
  1311. This is particularly useful in programs like games where you want to read straight from an archive
  1312. rather than the normal file system. If you do not specify a custom VFS, the resource manager will
  1313. use the operating system's normal file operations.
  1314. To load a sound file and create a data source, call `ma_resource_manager_data_source_init()`. When
  1315. loading a sound you need to specify the file path and options for how the sounds should be loaded.
  1316. By default a sound will be loaded synchronously. The returned data source is owned by the caller
  1317. which means the caller is responsible for the allocation and freeing of the data source. Below is
  1318. an example for initializing a data source:
  1319. ```c
  1320. ma_resource_manager_data_source dataSource;
  1321. ma_result result = ma_resource_manager_data_source_init(pResourceManager, pFilePath, flags, &dataSource);
  1322. if (result != MA_SUCCESS) {
  1323. // Error.
  1324. }
  1325. // ...
  1326. // A ma_resource_manager_data_source object is compatible with the `ma_data_source` API. To read data, just call
  1327. // the `ma_data_source_read_pcm_frames()` like you would with any normal data source.
  1328. result = ma_data_source_read_pcm_frames(&dataSource, pDecodedData, frameCount, &framesRead);
  1329. if (result != MA_SUCCESS) {
  1330. // Failed to read PCM frames.
  1331. }
  1332. // ...
  1333. ma_resource_manager_data_source_uninit(&dataSource);
  1334. ```
  1335. The `flags` parameter specifies how you want to perform loading of the sound file. It can be a
  1336. combination of the following flags:
  1337. ```
  1338. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM
  1339. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE
  1340. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC
  1341. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT
  1342. ```
  1343. When no flags are specified (set to 0), the sound will be fully loaded into memory, but not
  1344. decoded, meaning the raw file data will be stored in memory, and then dynamically decoded when
  1345. `ma_data_source_read_pcm_frames()` is called. To instead decode the audio data before storing it in
  1346. memory, use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` flag. By default, the sound file will
  1347. be loaded synchronously, meaning `ma_resource_manager_data_source_init()` will only return after
  1348. the entire file has been loaded. This is good for simplicity, but can be prohibitively slow. You
  1349. can instead load the sound asynchronously using the `MA_RESOURCE_MANAGER_DATA_SOURCE_ASYNC` flag.
  1350. This will result in `ma_resource_manager_data_source_init()` returning quickly, but no data will be
  1351. returned by `ma_data_source_read_pcm_frames()` until some data is available. When no data is
  1352. available because the asynchronous decoding hasn't caught up, `MA_BUSY` will be returned by
  1353. `ma_data_source_read_pcm_frames()`.
  1354. For large sounds, it's often prohibitive to store the entire file in memory. To mitigate this, you
  1355. can instead stream audio data which you can do by specifying the
  1356. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. When streaming, data will be decoded in 1
  1357. second pages. When a new page needs to be decoded, a job will be posted to the job queue and then
  1358. subsequently processed in a job thread.
  1359. For in-memory sounds, reference counting is used to ensure the data is loaded only once. This means
  1360. multiple calls to `ma_resource_manager_data_source_init()` with the same file path will result in
  1361. the file data only being loaded once. Each call to `ma_resource_manager_data_source_init()` must be
  1362. matched up with a call to `ma_resource_manager_data_source_uninit()`. Sometimes it can be useful
  1363. for a program to register self-managed raw audio data and associate it with a file path. Use the
  1364. `ma_resource_manager_register_*()` and `ma_resource_manager_unregister_*()` APIs to do this.
  1365. `ma_resource_manager_register_decoded_data()` is used to associate a pointer to raw, self-managed
  1366. decoded audio data in the specified data format with the specified name. Likewise,
  1367. `ma_resource_manager_register_encoded_data()` is used to associate a pointer to raw self-managed
  1368. encoded audio data (the raw file data) with the specified name. Note that these names need not be
  1369. actual file paths. When `ma_resource_manager_data_source_init()` is called (without the
  1370. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag), the resource manager will look for these
  1371. explicitly registered data buffers and, if found, will use it as the backing data for the data
  1372. source. Note that the resource manager does *not* make a copy of this data so it is up to the
  1373. caller to ensure the pointer stays valid for it's lifetime. Use
  1374. `ma_resource_manager_unregister_data()` to unregister the self-managed data. You can also use
  1375. `ma_resource_manager_register_file()` and `ma_resource_manager_unregister_file()` to register and
  1376. unregister a file. It does not make sense to use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM`
  1377. flag with a self-managed data pointer.
  1378. 6.1. Asynchronous Loading and Synchronization
  1379. ---------------------------------------------
  1380. When loading asynchronously, it can be useful to poll whether or not loading has finished. Use
  1381. `ma_resource_manager_data_source_result()` to determine this. For in-memory sounds, this will
  1382. return `MA_SUCCESS` when the file has been *entirely* decoded. If the sound is still being decoded,
  1383. `MA_BUSY` will be returned. Otherwise, some other error code will be returned if the sound failed
  1384. to load. For streaming data sources, `MA_SUCCESS` will be returned when the first page has been
  1385. decoded and the sound is ready to be played. If the first page is still being decoded, `MA_BUSY`
  1386. will be returned. Otherwise, some other error code will be returned if the sound failed to load.
  1387. In addition to polling, you can also use a simple synchronization object called a "fence" to wait
  1388. for asynchronously loaded sounds to finish. This is called `ma_fence`. The advantage to using a
  1389. fence is that it can be used to wait for a group of sounds to finish loading rather than waiting
  1390. for sounds on an individual basis. There are two stages to loading a sound:
  1391. * Initialization of the internal decoder; and
  1392. * Completion of decoding of the file (the file is fully decoded)
  1393. You can specify separate fences for each of the different stages. Waiting for the initialization
  1394. of the internal decoder is important for when you need to know the sample format, channels and
  1395. sample rate of the file.
  1396. The example below shows how you could use a fence when loading a number of sounds:
  1397. ```c
  1398. // This fence will be released when all sounds are finished loading entirely.
  1399. ma_fence fence;
  1400. ma_fence_init(&fence);
  1401. // This will be passed into the initialization routine for each sound.
  1402. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1403. notifications.done.pFence = &fence;
  1404. // Now load a bunch of sounds:
  1405. for (iSound = 0; iSound < soundCount; iSound += 1) {
  1406. ma_resource_manager_data_source_init(pResourceManager, pSoundFilePaths[iSound], flags, &notifications, &pSoundSources[iSound]);
  1407. }
  1408. // ... DO SOMETHING ELSE WHILE SOUNDS ARE LOADING ...
  1409. // Wait for loading of sounds to finish.
  1410. ma_fence_wait(&fence);
  1411. ```
  1412. In the example above we used a fence for waiting until the entire file has been fully decoded. If
  1413. you only need to wait for the initialization of the internal decoder to complete, you can use the
  1414. `init` member of the `ma_resource_manager_pipeline_notifications` object:
  1415. ```c
  1416. notifications.init.pFence = &fence;
  1417. ```
  1418. If a fence is not appropriate for your situation, you can instead use a callback that is fired on
  1419. an individual sound basis. This is done in a very similar way to fences:
  1420. ```c
  1421. typedef struct
  1422. {
  1423. ma_async_notification_callbacks cb;
  1424. void* pMyData;
  1425. } my_notification;
  1426. void my_notification_callback(ma_async_notification* pNotification)
  1427. {
  1428. my_notification* pMyNotification = (my_notification*)pNotification;
  1429. // Do something in response to the sound finishing loading.
  1430. }
  1431. ...
  1432. my_notification myCallback;
  1433. myCallback.cb.onSignal = my_notification_callback;
  1434. myCallback.pMyData = pMyData;
  1435. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1436. notifications.done.pNotification = &myCallback;
  1437. ma_resource_manager_data_source_init(pResourceManager, "my_sound.wav", flags, &notifications, &mySound);
  1438. ```
  1439. In the example above we just extend the `ma_async_notification_callbacks` object and pass an
  1440. instantiation into the `ma_resource_manager_pipeline_notifications` in the same way as we did with
  1441. the fence, only we set `pNotification` instead of `pFence`. You can set both of these at the same
  1442. time and they should both work as expected. If using the `pNotification` system, you need to ensure
  1443. your `ma_async_notification_callbacks` object stays valid.
  1444. 6.2. Resource Manager Implementation Details
  1445. --------------------------------------------
  1446. Resources are managed in two main ways:
  1447. * By storing the entire sound inside an in-memory buffer (referred to as a data buffer)
  1448. * By streaming audio data on the fly (referred to as a data stream)
  1449. A resource managed data source (`ma_resource_manager_data_source`) encapsulates a data buffer or
  1450. data stream, depending on whether or not the data source was initialized with the
  1451. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. If so, it will make use of a
  1452. `ma_resource_manager_data_stream` object. Otherwise it will use a `ma_resource_manager_data_buffer`
  1453. object. Both of these objects are data sources which means they can be used with any
  1454. `ma_data_source_*()` API.
  1455. Another major feature of the resource manager is the ability to asynchronously decode audio files.
  1456. This relieves the audio thread of time-consuming decoding which can negatively affect scalability
  1457. due to the audio thread needing to complete it's work extremely quickly to avoid glitching.
  1458. Asynchronous decoding is achieved through a job system. There is a central multi-producer,
  1459. multi-consumer, fixed-capacity job queue. When some asynchronous work needs to be done, a job is
  1460. posted to the queue which is then read by a job thread. The number of job threads can be
  1461. configured for improved scalability, and job threads can all run in parallel without needing to
  1462. worry about the order of execution (how this is achieved is explained below).
  1463. When a sound is being loaded asynchronously, playback can begin before the sound has been fully
  1464. decoded. This enables the application to start playback of the sound quickly, while at the same
  1465. time allowing to resource manager to keep loading in the background. Since there may be less
  1466. threads than the number of sounds being loaded at a given time, a simple scheduling system is used
  1467. to keep decoding time balanced and fair. The resource manager solves this by splitting decoding
  1468. into chunks called pages. By default, each page is 1 second long. When a page has been decoded, a
  1469. new job will be posted to start decoding the next page. By dividing up decoding into pages, an
  1470. individual sound shouldn't ever delay every other sound from having their first page decoded. Of
  1471. course, when loading many sounds at the same time, there will always be an amount of time required
  1472. to process jobs in the queue so in heavy load situations there will still be some delay. To
  1473. determine if a data source is ready to have some frames read, use
  1474. `ma_resource_manager_data_source_get_available_frames()`. This will return the number of frames
  1475. available starting from the current position.
  1476. 6.2.1. Job Queue
  1477. ----------------
  1478. The resource manager uses a job queue which is multi-producer, multi-consumer, and fixed-capacity.
  1479. This job queue is not currently lock-free, and instead uses a spinlock to achieve thread-safety.
  1480. Only a fixed number of jobs can be allocated and inserted into the queue which is done through a
  1481. lock-free data structure for allocating an index into a fixed sized array, with reference counting
  1482. for mitigation of the ABA problem. The reference count is 32-bit.
  1483. For many types of jobs it's important that they execute in a specific order. In these cases, jobs
  1484. are executed serially. For the resource manager, serial execution of jobs is only required on a
  1485. per-object basis (per data buffer or per data stream). Each of these objects stores an execution
  1486. counter. When a job is posted it is associated with an execution counter. When the job is
  1487. processed, it checks if the execution counter of the job equals the execution counter of the
  1488. owning object and if so, processes the job. If the counters are not equal, the job will be posted
  1489. back onto the job queue for later processing. When the job finishes processing the execution order
  1490. of the main object is incremented. This system means the no matter how many job threads are
  1491. executing, decoding of an individual sound will always get processed serially. The advantage to
  1492. having multiple threads comes into play when loading multiple sounds at the same time.
  1493. The resource manager's job queue is not 100% lock-free and will use a spinlock to achieve
  1494. thread-safety for a very small section of code. This is only relevant when the resource manager
  1495. uses more than one job thread. If only using a single job thread, which is the default, the
  1496. lock should never actually wait in practice. The amount of time spent locking should be quite
  1497. short, but it's something to be aware of for those who have pedantic lock-free requirements and
  1498. need to use more than one job thread. There are plans to remove this lock in a future version.
  1499. In addition, posting a job will release a semaphore, which on Win32 is implemented with
  1500. `ReleaseSemaphore` and on POSIX platforms via a condition variable:
  1501. ```c
  1502. pthread_mutex_lock(&pSemaphore->lock);
  1503. {
  1504. pSemaphore->value += 1;
  1505. pthread_cond_signal(&pSemaphore->cond);
  1506. }
  1507. pthread_mutex_unlock(&pSemaphore->lock);
  1508. ```
  1509. Again, this is relevant for those with strict lock-free requirements in the audio thread. To avoid
  1510. this, you can use non-blocking mode (via the `MA_JOB_QUEUE_FLAG_NON_BLOCKING`
  1511. flag) and implement your own job processing routine (see the "Resource Manager" section above for
  1512. details on how to do this).
  1513. 6.2.2. Data Buffers
  1514. -------------------
  1515. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag is excluded at initialization time, the
  1516. resource manager will try to load the data into an in-memory data buffer. Before doing so, however,
  1517. it will first check if the specified file is already loaded. If so, it will increment a reference
  1518. counter and just use the already loaded data. This saves both time and memory. When the data buffer
  1519. is uninitialized, the reference counter will be decremented. If the counter hits zero, the file
  1520. will be unloaded. This is a detail to keep in mind because it could result in excessive loading and
  1521. unloading of a sound. For example, the following sequence will result in a file be loaded twice,
  1522. once after the other:
  1523. ```c
  1524. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer0); // Refcount = 1. Initial load.
  1525. ma_resource_manager_data_source_uninit(&myDataBuffer0); // Refcount = 0. Unloaded.
  1526. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer1); // Refcount = 1. Reloaded because previous uninit() unloaded it.
  1527. ma_resource_manager_data_source_uninit(&myDataBuffer1); // Refcount = 0. Unloaded.
  1528. ```
  1529. A binary search tree (BST) is used for storing data buffers as it has good balance between
  1530. efficiency and simplicity. The key of the BST is a 64-bit hash of the file path that was passed
  1531. into `ma_resource_manager_data_source_init()`. The advantage of using a hash is that it saves
  1532. memory over storing the entire path, has faster comparisons, and results in a mostly balanced BST
  1533. due to the random nature of the hash. The disadvantages are that file names are case-sensitive and
  1534. there's a small chance of name collisions. If case-sensitivity is an issue, you should normalize
  1535. your file names to upper- or lower-case before initializing your data sources. If name collisions
  1536. become an issue, you'll need to change the name of one of the colliding names or just not use the
  1537. resource manager.
  1538. When a sound file has not already been loaded and the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC`
  1539. flag is excluded, the file will be decoded synchronously by the calling thread. There are two
  1540. options for controlling how the audio is stored in the data buffer - encoded or decoded. When the
  1541. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` option is excluded, the raw file data will be stored
  1542. in memory. Otherwise the sound will be decoded before storing it in memory. Synchronous loading is
  1543. a very simple and standard process of simply adding an item to the BST, allocating a block of
  1544. memory and then decoding (if `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` is specified).
  1545. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag is specified, loading of the data buffer
  1546. is done asynchronously. In this case, a job is posted to the queue to start loading and then the
  1547. function immediately returns, setting an internal result code to `MA_BUSY`. This result code is
  1548. returned when the program calls `ma_resource_manager_data_source_result()`. When decoding has fully
  1549. completed `MA_SUCCESS` will be returned. This can be used to know if loading has fully completed.
  1550. When loading asynchronously, a single job is posted to the queue of the type
  1551. `MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE`. This involves making a copy of the file path and
  1552. associating it with job. When the job is processed by the job thread, it will first load the file
  1553. using the VFS associated with the resource manager. When using a custom VFS, it's important that it
  1554. be completely thread-safe because it will be used from one or more job threads at the same time.
  1555. Individual files should only ever be accessed by one thread at a time, however. After opening the
  1556. file via the VFS, the job will determine whether or not the file is being decoded. If not, it
  1557. simply allocates a block of memory and loads the raw file contents into it and returns. On the
  1558. other hand, when the file is being decoded, it will first allocate a decoder on the heap and
  1559. initialize it. Then it will check if the length of the file is known. If so it will allocate a
  1560. block of memory to store the decoded output and initialize it to silence. If the size is unknown,
  1561. it will allocate room for one page. After memory has been allocated, the first page will be
  1562. decoded. If the sound is shorter than a page, the result code will be set to `MA_SUCCESS` and the
  1563. completion event will be signalled and loading is now complete. If, however, there is more to
  1564. decode, a job with the code `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` is posted. This job
  1565. will decode the next page and perform the same process if it reaches the end. If there is more to
  1566. decode, the job will post another `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` job which will
  1567. keep on happening until the sound has been fully decoded. For sounds of an unknown length, each
  1568. page will be linked together as a linked list. Internally this is implemented via the
  1569. `ma_paged_audio_buffer` object.
  1570. 6.2.3. Data Streams
  1571. -------------------
  1572. Data streams only ever store two pages worth of data for each instance. They are most useful for
  1573. large sounds like music tracks in games that would consume too much memory if fully decoded in
  1574. memory. After every frame from a page has been read, a job will be posted to load the next page
  1575. which is done from the VFS.
  1576. For data streams, the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag will determine whether or
  1577. not initialization of the data source waits until the two pages have been decoded. When unset,
  1578. `ma_resource_manager_data_source_init()` will wait until the two pages have been loaded, otherwise
  1579. it will return immediately.
  1580. When frames are read from a data stream using `ma_resource_manager_data_source_read_pcm_frames()`,
  1581. `MA_BUSY` will be returned if there are no frames available. If there are some frames available,
  1582. but less than the number requested, `MA_SUCCESS` will be returned, but the actual number of frames
  1583. read will be less than the number requested. Due to the asynchronous nature of data streams,
  1584. seeking is also asynchronous. If the data stream is in the middle of a seek, `MA_BUSY` will be
  1585. returned when trying to read frames.
  1586. When `ma_resource_manager_data_source_read_pcm_frames()` results in a page getting fully consumed
  1587. a job is posted to load the next page. This will be posted from the same thread that called
  1588. `ma_resource_manager_data_source_read_pcm_frames()`.
  1589. Data streams are uninitialized by posting a job to the queue, but the function won't return until
  1590. that job has been processed. The reason for this is that the caller owns the data stream object and
  1591. therefore miniaudio needs to ensure everything completes before handing back control to the caller.
  1592. Also, if the data stream is uninitialized while pages are in the middle of decoding, they must
  1593. complete before destroying any underlying object and the job system handles this cleanly.
  1594. Note that when a new page needs to be loaded, a job will be posted to the resource manager's job
  1595. thread from the audio thread. You must keep in mind the details mentioned in the "Job Queue"
  1596. section above regarding locking when posting an event if you require a strictly lock-free audio
  1597. thread.
  1598. 7. Node Graph
  1599. =============
  1600. miniaudio's routing infrastructure follows a node graph paradigm. The idea is that you create a
  1601. node whose outputs are attached to inputs of another node, thereby creating a graph. There are
  1602. different types of nodes, with each node in the graph processing input data to produce output,
  1603. which is then fed through the chain. Each node in the graph can apply their own custom effects. At
  1604. the start of the graph will usually be one or more data source nodes which have no inputs and
  1605. instead pull their data from a data source. At the end of the graph is an endpoint which represents
  1606. the end of the chain and is where the final output is ultimately extracted from.
  1607. Each node has a number of input buses and a number of output buses. An output bus from a node is
  1608. attached to an input bus of another. Multiple nodes can connect their output buses to another
  1609. node's input bus, in which case their outputs will be mixed before processing by the node. Below is
  1610. a diagram that illustrates a hypothetical node graph setup:
  1611. ```
  1612. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Data flows left to right >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  1613. +---------------+ +-----------------+
  1614. | Data Source 1 =----+ +----------+ +----= Low Pass Filter =----+
  1615. +---------------+ | | =----+ +-----------------+ | +----------+
  1616. +----= Splitter | +----= ENDPOINT |
  1617. +---------------+ | | =----+ +-----------------+ | +----------+
  1618. | Data Source 2 =----+ +----------+ +----= Echo / Delay =----+
  1619. +---------------+ +-----------------+
  1620. ```
  1621. In the above graph, it starts with two data sources whose outputs are attached to the input of a
  1622. splitter node. It's at this point that the two data sources are mixed. After mixing, the splitter
  1623. performs it's processing routine and produces two outputs which is simply a duplication of the
  1624. input stream. One output is attached to a low pass filter, whereas the other output is attached to
  1625. a echo/delay. The outputs of the the low pass filter and the echo are attached to the endpoint, and
  1626. since they're both connected to the same input bus, they'll be mixed.
  1627. Each input bus must be configured to accept the same number of channels, but the number of channels
  1628. used by input buses can be different to the number of channels for output buses in which case
  1629. miniaudio will automatically convert the input data to the output channel count before processing.
  1630. The number of channels of an output bus of one node must match the channel count of the input bus
  1631. it's attached to. The channel counts cannot be changed after the node has been initialized. If you
  1632. attempt to attach an output bus to an input bus with a different channel count, attachment will
  1633. fail.
  1634. To use a node graph, you first need to initialize a `ma_node_graph` object. This is essentially a
  1635. container around the entire graph. The `ma_node_graph` object is required for some thread-safety
  1636. issues which will be explained later. A `ma_node_graph` object is initialized using miniaudio's
  1637. standard config/init system:
  1638. ```c
  1639. ma_node_graph_config nodeGraphConfig = ma_node_graph_config_init(myChannelCount);
  1640. result = ma_node_graph_init(&nodeGraphConfig, NULL, &nodeGraph); // Second parameter is a pointer to allocation callbacks.
  1641. if (result != MA_SUCCESS) {
  1642. // Failed to initialize node graph.
  1643. }
  1644. ```
  1645. When you initialize the node graph, you're specifying the channel count of the endpoint. The
  1646. endpoint is a special node which has one input bus and one output bus, both of which have the
  1647. same channel count, which is specified in the config. Any nodes that connect directly to the
  1648. endpoint must be configured such that their output buses have the same channel count. When you read
  1649. audio data from the node graph, it'll have the channel count you specified in the config. To read
  1650. data from the graph:
  1651. ```c
  1652. ma_uint32 framesRead;
  1653. result = ma_node_graph_read_pcm_frames(&nodeGraph, pFramesOut, frameCount, &framesRead);
  1654. if (result != MA_SUCCESS) {
  1655. // Failed to read data from the node graph.
  1656. }
  1657. ```
  1658. When you read audio data, miniaudio starts at the node graph's endpoint node which then pulls in
  1659. data from it's input attachments, which in turn recursively pull in data from their inputs, and so
  1660. on. At the start of the graph there will be some kind of data source node which will have zero
  1661. inputs and will instead read directly from a data source. The base nodes don't literally need to
  1662. read from a `ma_data_source` object, but they will always have some kind of underlying object that
  1663. sources some kind of audio. The `ma_data_source_node` node can be used to read from a
  1664. `ma_data_source`. Data is always in floating-point format and in the number of channels you
  1665. specified when the graph was initialized. The sample rate is defined by the underlying data sources.
  1666. It's up to you to ensure they use a consistent and appropriate sample rate.
  1667. The `ma_node` API is designed to allow custom nodes to be implemented with relative ease, but
  1668. miniaudio includes a few stock nodes for common functionality. This is how you would initialize a
  1669. node which reads directly from a data source (`ma_data_source_node`) which is an example of one
  1670. of the stock nodes that comes with miniaudio:
  1671. ```c
  1672. ma_data_source_node_config config = ma_data_source_node_config_init(pMyDataSource);
  1673. ma_data_source_node dataSourceNode;
  1674. result = ma_data_source_node_init(&nodeGraph, &config, NULL, &dataSourceNode);
  1675. if (result != MA_SUCCESS) {
  1676. // Failed to create data source node.
  1677. }
  1678. ```
  1679. The data source node will use the output channel count to determine the channel count of the output
  1680. bus. There will be 1 output bus and 0 input buses (data will be drawn directly from the data
  1681. source). The data source must output to floating-point (`ma_format_f32`) or else an error will be
  1682. returned from `ma_data_source_node_init()`.
  1683. By default the node will not be attached to the graph. To do so, use `ma_node_attach_output_bus()`:
  1684. ```c
  1685. result = ma_node_attach_output_bus(&dataSourceNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0);
  1686. if (result != MA_SUCCESS) {
  1687. // Failed to attach node.
  1688. }
  1689. ```
  1690. The code above connects the data source node directly to the endpoint. Since the data source node
  1691. has only a single output bus, the index will always be 0. Likewise, the endpoint only has a single
  1692. input bus which means the input bus index will also always be 0.
  1693. To detach a specific output bus, use `ma_node_detach_output_bus()`. To detach all output buses, use
  1694. `ma_node_detach_all_output_buses()`. If you want to just move the output bus from one attachment to
  1695. another, you do not need to detach first. You can just call `ma_node_attach_output_bus()` and it'll
  1696. deal with it for you.
  1697. Less frequently you may want to create a specialized node. This will be a node where you implement
  1698. your own processing callback to apply a custom effect of some kind. This is similar to initializing
  1699. one of the stock node types, only this time you need to specify a pointer to a vtable containing a
  1700. pointer to the processing function and the number of input and output buses. Example:
  1701. ```c
  1702. static void my_custom_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  1703. {
  1704. // Do some processing of ppFramesIn (one stream of audio data per input bus)
  1705. const float* pFramesIn_0 = ppFramesIn[0]; // Input bus @ index 0.
  1706. const float* pFramesIn_1 = ppFramesIn[1]; // Input bus @ index 1.
  1707. float* pFramesOut_0 = ppFramesOut[0]; // Output bus @ index 0.
  1708. // Do some processing. On input, `pFrameCountIn` will be the number of input frames in each
  1709. // buffer in `ppFramesIn` and `pFrameCountOut` will be the capacity of each of the buffers
  1710. // in `ppFramesOut`. On output, `pFrameCountIn` should be set to the number of input frames
  1711. // your node consumed and `pFrameCountOut` should be set the number of output frames that
  1712. // were produced.
  1713. //
  1714. // You should process as many frames as you can. If your effect consumes input frames at the
  1715. // same rate as output frames (always the case, unless you're doing resampling), you need
  1716. // only look at `ppFramesOut` and process that exact number of frames. If you're doing
  1717. // resampling, you'll need to be sure to set both `pFrameCountIn` and `pFrameCountOut`
  1718. // properly.
  1719. }
  1720. static ma_node_vtable my_custom_node_vtable =
  1721. {
  1722. 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.
  1723. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1724. 2, // 2 input buses.
  1725. 1, // 1 output bus.
  1726. 0 // Default flags.
  1727. };
  1728. ...
  1729. // Each bus needs to have a channel count specified. To do this you need to specify the channel
  1730. // counts in an array and then pass that into the node config.
  1731. ma_uint32 inputChannels[2]; // Equal in size to the number of input channels specified in the vtable.
  1732. ma_uint32 outputChannels[1]; // Equal in size to the number of output channels specified in the vtable.
  1733. inputChannels[0] = channelsIn;
  1734. inputChannels[1] = channelsIn;
  1735. outputChannels[0] = channelsOut;
  1736. ma_node_config nodeConfig = ma_node_config_init();
  1737. nodeConfig.vtable = &my_custom_node_vtable;
  1738. nodeConfig.pInputChannels = inputChannels;
  1739. nodeConfig.pOutputChannels = outputChannels;
  1740. ma_node_base node;
  1741. result = ma_node_init(&nodeGraph, &nodeConfig, NULL, &node);
  1742. if (result != MA_SUCCESS) {
  1743. // Failed to initialize node.
  1744. }
  1745. ```
  1746. When initializing a custom node, as in the code above, you'll normally just place your vtable in
  1747. static space. The number of input and output buses are specified as part of the vtable. If you need
  1748. a variable number of buses on a per-node bases, the vtable should have the relevant bus count set
  1749. to `MA_NODE_BUS_COUNT_UNKNOWN`. In this case, the bus count should be set in the node config:
  1750. ```c
  1751. static ma_node_vtable my_custom_node_vtable =
  1752. {
  1753. 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.
  1754. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1755. MA_NODE_BUS_COUNT_UNKNOWN, // The number of input buses is determined on a per-node basis.
  1756. 1, // 1 output bus.
  1757. 0 // Default flags.
  1758. };
  1759. ...
  1760. ma_node_config nodeConfig = ma_node_config_init();
  1761. nodeConfig.vtable = &my_custom_node_vtable;
  1762. nodeConfig.inputBusCount = myBusCount; // <-- Since the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN, the input bus count should be set here.
  1763. nodeConfig.pInputChannels = inputChannels; // <-- Make sure there are nodeConfig.inputBusCount elements in this array.
  1764. nodeConfig.pOutputChannels = outputChannels; // <-- The vtable specifies 1 output bus, so there must be 1 element in this array.
  1765. ```
  1766. In the above example it's important to never set the `inputBusCount` and `outputBusCount` members
  1767. to anything other than their defaults if the vtable specifies an explicit count. They can only be
  1768. set if the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN in the relevant bus count.
  1769. Most often you'll want to create a structure to encapsulate your node with some extra data. You
  1770. need to make sure the `ma_node_base` object is your first member of the structure:
  1771. ```c
  1772. typedef struct
  1773. {
  1774. ma_node_base base; // <-- Make sure this is always the first member.
  1775. float someCustomData;
  1776. } my_custom_node;
  1777. ```
  1778. By doing this, your object will be compatible with all `ma_node` APIs and you can attach it to the
  1779. graph just like any other node.
  1780. In the custom processing callback (`my_custom_node_process_pcm_frames()` in the example above), the
  1781. number of channels for each bus is what was specified by the config when the node was initialized
  1782. with `ma_node_init()`. In addition, all attachments to each of the input buses will have been
  1783. pre-mixed by miniaudio. The config allows you to specify different channel counts for each
  1784. individual input and output bus. It's up to the effect to handle it appropriate, and if it can't,
  1785. return an error in it's initialization routine.
  1786. Custom nodes can be assigned some flags to describe their behaviour. These are set via the vtable
  1787. and include the following:
  1788. +-----------------------------------------+---------------------------------------------------+
  1789. | Flag Name | Description |
  1790. +-----------------------------------------+---------------------------------------------------+
  1791. | MA_NODE_FLAG_PASSTHROUGH | Useful for nodes that do not do any kind of audio |
  1792. | | processing, but are instead used for tracking |
  1793. | | time, handling events, etc. Also used by the |
  1794. | | internal endpoint node. It reads directly from |
  1795. | | the input bus to the output bus. Nodes with this |
  1796. | | flag must have exactly 1 input bus and 1 output |
  1797. | | bus, and both buses must have the same channel |
  1798. | | counts. |
  1799. +-----------------------------------------+---------------------------------------------------+
  1800. | MA_NODE_FLAG_CONTINUOUS_PROCESSING | Causes the processing callback to be called even |
  1801. | | when no data is available to be read from input |
  1802. | | attachments. When a node has at least one input |
  1803. | | bus, but there are no inputs attached or the |
  1804. | | inputs do not deliver any data, the node's |
  1805. | | processing callback will not get fired. This flag |
  1806. | | will make it so the callback is always fired |
  1807. | | regardless of whether or not any input data is |
  1808. | | received. This is useful for effects like |
  1809. | | echos where there will be a tail of audio data |
  1810. | | that still needs to be processed even when the |
  1811. | | original data sources have reached their ends. It |
  1812. | | may also be useful for nodes that must always |
  1813. | | have their processing callback fired when there |
  1814. | | are no inputs attached. |
  1815. +-----------------------------------------+---------------------------------------------------+
  1816. | MA_NODE_FLAG_ALLOW_NULL_INPUT | Used in conjunction with |
  1817. | | `MA_NODE_FLAG_CONTINUOUS_PROCESSING`. When this |
  1818. | | is set, the `ppFramesIn` parameter of the |
  1819. | | processing callback will be set to NULL when |
  1820. | | there are no input frames are available. When |
  1821. | | this is unset, silence will be posted to the |
  1822. | | processing callback. |
  1823. +-----------------------------------------+---------------------------------------------------+
  1824. | MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES | Used to tell miniaudio that input and output |
  1825. | | frames are processed at different rates. You |
  1826. | | should set this for any nodes that perform |
  1827. | | resampling. |
  1828. +-----------------------------------------+---------------------------------------------------+
  1829. | MA_NODE_FLAG_SILENT_OUTPUT | Used to tell miniaudio that a node produces only |
  1830. | | silent output. This is useful for nodes where you |
  1831. | | don't want the output to contribute to the final |
  1832. | | mix. An example might be if you want split your |
  1833. | | stream and have one branch be output to a file. |
  1834. | | When using this flag, you should avoid writing to |
  1835. | | the output buffer of the node's processing |
  1836. | | callback because miniaudio will ignore it anyway. |
  1837. +-----------------------------------------+---------------------------------------------------+
  1838. If you need to make a copy of an audio stream for effect processing you can use a splitter node
  1839. called `ma_splitter_node`. This takes has 1 input bus and splits the stream into 2 output buses.
  1840. You can use it like this:
  1841. ```c
  1842. ma_splitter_node_config splitterNodeConfig = ma_splitter_node_config_init(channels);
  1843. ma_splitter_node splitterNode;
  1844. result = ma_splitter_node_init(&nodeGraph, &splitterNodeConfig, NULL, &splitterNode);
  1845. if (result != MA_SUCCESS) {
  1846. // Failed to create node.
  1847. }
  1848. // Attach your output buses to two different input buses (can be on two different nodes).
  1849. ma_node_attach_output_bus(&splitterNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); // Attach directly to the endpoint.
  1850. ma_node_attach_output_bus(&splitterNode, 1, &myEffectNode, 0); // Attach to input bus 0 of some effect node.
  1851. ```
  1852. The volume of an output bus can be configured on a per-bus basis:
  1853. ```c
  1854. ma_node_set_output_bus_volume(&splitterNode, 0, 0.5f);
  1855. ma_node_set_output_bus_volume(&splitterNode, 1, 0.5f);
  1856. ```
  1857. In the code above we're using the splitter node from before and changing the volume of each of the
  1858. copied streams.
  1859. You can start and stop a node with the following:
  1860. ```c
  1861. ma_node_set_state(&splitterNode, ma_node_state_started); // The default state.
  1862. ma_node_set_state(&splitterNode, ma_node_state_stopped);
  1863. ```
  1864. By default the node is in a started state, but since it won't be connected to anything won't
  1865. actually be invoked by the node graph until it's connected. When you stop a node, data will not be
  1866. read from any of it's input connections. You can use this property to stop a group of sounds
  1867. atomically.
  1868. You can configure the initial state of a node in it's config:
  1869. ```c
  1870. nodeConfig.initialState = ma_node_state_stopped;
  1871. ```
  1872. Note that for the stock specialized nodes, all of their configs will have a `nodeConfig` member
  1873. which is the config to use with the base node. This is where the initial state can be configured
  1874. for specialized nodes:
  1875. ```c
  1876. dataSourceNodeConfig.nodeConfig.initialState = ma_node_state_stopped;
  1877. ```
  1878. When using a specialized node like `ma_data_source_node` or `ma_splitter_node`, be sure to not
  1879. modify the `vtable` member of the `nodeConfig` object.
  1880. 7.1. Timing
  1881. -----------
  1882. The node graph supports starting and stopping nodes at scheduled times. This is especially useful
  1883. for data source nodes where you want to get the node set up, but only start playback at a specific
  1884. time. There are two clocks: local and global.
  1885. A local clock is per-node, whereas the global clock is per graph. Scheduling starts and stops can
  1886. only be done based on the global clock because the local clock will not be running while the node
  1887. is stopped. The global clocks advances whenever `ma_node_graph_read_pcm_frames()` is called. On the
  1888. other hand, the local clock only advances when the node's processing callback is fired, and is
  1889. advanced based on the output frame count.
  1890. To retrieve the global time, use `ma_node_graph_get_time()`. The global time can be set with
  1891. `ma_node_graph_set_time()` which might be useful if you want to do seeking on a global timeline.
  1892. Getting and setting the local time is similar. Use `ma_node_get_time()` to retrieve the local time,
  1893. and `ma_node_set_time()` to set the local time. The global and local times will be advanced by the
  1894. audio thread, so care should be taken to avoid data races. Ideally you should avoid calling these
  1895. outside of the node processing callbacks which are always run on the audio thread.
  1896. There is basic support for scheduling the starting and stopping of nodes. You can only schedule one
  1897. start and one stop at a time. This is mainly intended for putting nodes into a started or stopped
  1898. state in a frame-exact manner. Without this mechanism, starting and stopping of a node is limited
  1899. to the resolution of a call to `ma_node_graph_read_pcm_frames()` which would typically be in blocks
  1900. of several milliseconds. The following APIs can be used for scheduling node states:
  1901. ```c
  1902. ma_node_set_state_time()
  1903. ma_node_get_state_time()
  1904. ```
  1905. The time is absolute and must be based on the global clock. An example is below:
  1906. ```c
  1907. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1); // Delay starting to 1 second.
  1908. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5); // Delay stopping to 5 seconds.
  1909. ```
  1910. An example for changing the state using a relative time.
  1911. ```c
  1912. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1 + ma_node_graph_get_time(&myNodeGraph));
  1913. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5 + ma_node_graph_get_time(&myNodeGraph));
  1914. ```
  1915. Note that due to the nature of multi-threading the times may not be 100% exact. If this is an
  1916. issue, consider scheduling state changes from within a processing callback. An idea might be to
  1917. have some kind of passthrough trigger node that is used specifically for tracking time and handling
  1918. events.
  1919. 7.2. Thread Safety and Locking
  1920. ------------------------------
  1921. When processing audio, it's ideal not to have any kind of locking in the audio thread. Since it's
  1922. expected that `ma_node_graph_read_pcm_frames()` would be run on the audio thread, it does so
  1923. without the use of any locks. This section discusses the implementation used by miniaudio and goes
  1924. over some of the compromises employed by miniaudio to achieve this goal. Note that the current
  1925. implementation may not be ideal - feedback and critiques are most welcome.
  1926. The node graph API is not *entirely* lock-free. Only `ma_node_graph_read_pcm_frames()` is expected
  1927. to be lock-free. Attachment, detachment and uninitialization of nodes use locks to simplify the
  1928. implementation, but are crafted in a way such that such locking is not required when reading audio
  1929. data from the graph. Locking in these areas are achieved by means of spinlocks.
  1930. The main complication with keeping `ma_node_graph_read_pcm_frames()` lock-free stems from the fact
  1931. that a node can be uninitialized, and it's memory potentially freed, while in the middle of being
  1932. processed on the audio thread. There are times when the audio thread will be referencing a node,
  1933. which means the uninitialization process of a node needs to make sure it delays returning until the
  1934. audio thread is finished so that control is not handed back to the caller thereby giving them a
  1935. chance to free the node's memory.
  1936. When the audio thread is processing a node, it does so by reading from each of the output buses of
  1937. the node. In order for a node to process data for one of it's output buses, it needs to read from
  1938. each of it's input buses, and so on an so forth. It follows that once all output buses of a node
  1939. are detached, the node as a whole will be disconnected and no further processing will occur unless
  1940. it's output buses are reattached, which won't be happening when the node is being uninitialized.
  1941. By having `ma_node_detach_output_bus()` wait until the audio thread is finished with it, we can
  1942. simplify a few things, at the expense of making `ma_node_detach_output_bus()` a bit slower. By
  1943. doing this, the implementation of `ma_node_uninit()` becomes trivial - just detach all output
  1944. nodes, followed by each of the attachments to each of it's input nodes, and then do any final clean
  1945. up.
  1946. With the above design, the worst-case scenario is `ma_node_detach_output_bus()` taking as long as
  1947. it takes to process the output bus being detached. This will happen if it's called at just the
  1948. wrong moment where the audio thread has just iterated it and has just started processing. The
  1949. caller of `ma_node_detach_output_bus()` will stall until the audio thread is finished, which
  1950. includes the cost of recursively processing it's inputs. This is the biggest compromise made with
  1951. the approach taken by miniaudio for it's lock-free processing system. The cost of detaching nodes
  1952. earlier in the pipeline (data sources, for example) will be cheaper than the cost of detaching
  1953. higher level nodes, such as some kind of final post-processing endpoint. If you need to do mass
  1954. detachments, detach starting from the lowest level nodes and work your way towards the final
  1955. endpoint node (but don't try detaching the node graph's endpoint). If the audio thread is not
  1956. running, detachment will be fast and detachment in any order will be the same. The reason nodes
  1957. need to wait for their input attachments to complete is due to the potential for desyncs between
  1958. data sources. If the node was to terminate processing mid way through processing it's inputs,
  1959. there's a chance that some of the underlying data sources will have been read, but then others not.
  1960. That will then result in a potential desynchronization when detaching and reattaching higher-level
  1961. nodes. A possible solution to this is to have an option when detaching to terminate processing
  1962. before processing all input attachments which should be fairly simple.
  1963. Another compromise, albeit less significant, is locking when attaching and detaching nodes. This
  1964. locking is achieved by means of a spinlock in order to reduce memory overhead. A lock is present
  1965. for each input bus and output bus. When an output bus is connected to an input bus, both the output
  1966. bus and input bus is locked. This locking is specifically for attaching and detaching across
  1967. different threads and does not affect `ma_node_graph_read_pcm_frames()` in any way. The locking and
  1968. unlocking is mostly self-explanatory, but a slightly less intuitive aspect comes into it when
  1969. considering that iterating over attachments must not break as a result of attaching or detaching a
  1970. node while iteration is occurring.
  1971. Attaching and detaching are both quite simple. When an output bus of a node is attached to an input
  1972. bus of another node, it's added to a linked list. Basically, an input bus is a linked list, where
  1973. each item in the list is and output bus. We have some intentional (and convenient) restrictions on
  1974. what can done with the linked list in order to simplify the implementation. First of all, whenever
  1975. something needs to iterate over the list, it must do so in a forward direction. Backwards iteration
  1976. is not supported. Also, items can only be added to the start of the list.
  1977. The linked list is a doubly-linked list where each item in the list (an output bus) holds a pointer
  1978. to the next item in the list, and another to the previous item. A pointer to the previous item is
  1979. only required for fast detachment of the node - it is never used in iteration. This is an
  1980. important property because it means from the perspective of iteration, attaching and detaching of
  1981. an item can be done with a single atomic assignment. This is exploited by both the attachment and
  1982. detachment process. When attaching the node, the first thing that is done is the setting of the
  1983. local "next" and "previous" pointers of the node. After that, the item is "attached" to the list
  1984. by simply performing an atomic exchange with the head pointer. After that, the node is "attached"
  1985. to the list from the perspective of iteration. Even though the "previous" pointer of the next item
  1986. hasn't yet been set, from the perspective of iteration it's been attached because iteration will
  1987. only be happening in a forward direction which means the "previous" pointer won't actually ever get
  1988. used. The same general process applies to detachment. See `ma_node_attach_output_bus()` and
  1989. `ma_node_detach_output_bus()` for the implementation of this mechanism.
  1990. 8. Decoding
  1991. ===========
  1992. The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from
  1993. devices and can be used independently. Built-in support is included for the following formats:
  1994. +---------+
  1995. | Format |
  1996. +---------+
  1997. | WAV |
  1998. | MP3 |
  1999. | FLAC |
  2000. +---------+
  2001. You can disable the built-in decoders by specifying one or more of the following options before the
  2002. miniaudio implementation:
  2003. ```c
  2004. #define MA_NO_WAV
  2005. #define MA_NO_MP3
  2006. #define MA_NO_FLAC
  2007. ```
  2008. miniaudio supports the ability to plug in custom decoders. See the section below for details on how
  2009. to use custom decoders.
  2010. A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with
  2011. `ma_decoder_init_memory()`, or from data delivered via callbacks with `ma_decoder_init()`. Here is
  2012. an example for loading a decoder from a file:
  2013. ```c
  2014. ma_decoder decoder;
  2015. ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder);
  2016. if (result != MA_SUCCESS) {
  2017. return false; // An error occurred.
  2018. }
  2019. ...
  2020. ma_decoder_uninit(&decoder);
  2021. ```
  2022. When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object
  2023. (the `NULL` argument in the example above) which allows you to configure the output format, channel
  2024. count, sample rate and channel map:
  2025. ```c
  2026. ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000);
  2027. ```
  2028. When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the
  2029. same as that defined by the decoding backend.
  2030. Data is read from the decoder as PCM frames. This will output the number of PCM frames actually
  2031. read. If this is less than the requested number of PCM frames it means you've reached the end. The
  2032. return value will be `MA_AT_END` if no samples have been read and the end has been reached.
  2033. ```c
  2034. ma_result result = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead, &framesRead);
  2035. if (framesRead < framesToRead) {
  2036. // Reached the end.
  2037. }
  2038. ```
  2039. You can also seek to a specific frame like so:
  2040. ```c
  2041. ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame);
  2042. if (result != MA_SUCCESS) {
  2043. return false; // An error occurred.
  2044. }
  2045. ```
  2046. If you want to loop back to the start, you can simply seek back to the first PCM frame:
  2047. ```c
  2048. ma_decoder_seek_to_pcm_frame(pDecoder, 0);
  2049. ```
  2050. When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding
  2051. backend. This can be unnecessarily inefficient if the type is already known. In this case you can
  2052. use `encodingFormat` variable in the device config to specify a specific encoding format you want
  2053. to decode:
  2054. ```c
  2055. decoderConfig.encodingFormat = ma_encoding_format_wav;
  2056. ```
  2057. See the `ma_encoding_format` enum for possible encoding formats.
  2058. The `ma_decoder_init_file()` API will try using the file extension to determine which decoding
  2059. backend to prefer.
  2060. 8.1. Custom Decoders
  2061. --------------------
  2062. It's possible to implement a custom decoder and plug it into miniaudio. This is extremely useful
  2063. when you want to use the `ma_decoder` API, but need to support an encoding format that's not one of
  2064. the stock formats supported by miniaudio. This can be put to particularly good use when using the
  2065. `ma_engine` and/or `ma_resource_manager` APIs because they use `ma_decoder` internally. If, for
  2066. example, you wanted to support Opus, you can do so with a custom decoder (there if a reference
  2067. Opus decoder in the "extras" folder of the miniaudio repository which uses libopus + libopusfile).
  2068. A custom decoder must implement a data source. A vtable called `ma_decoding_backend_vtable` needs
  2069. to be implemented which is then passed into the decoder config:
  2070. ```c
  2071. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  2072. {
  2073. &g_ma_decoding_backend_vtable_libvorbis,
  2074. &g_ma_decoding_backend_vtable_libopus
  2075. };
  2076. ...
  2077. decoderConfig = ma_decoder_config_init_default();
  2078. decoderConfig.pCustomBackendUserData = NULL;
  2079. decoderConfig.ppCustomBackendVTables = pCustomBackendVTables;
  2080. decoderConfig.customBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  2081. ```
  2082. The `ma_decoding_backend_vtable` vtable has the following functions:
  2083. ```
  2084. onInit
  2085. onInitFile
  2086. onInitFileW
  2087. onInitMemory
  2088. onUninit
  2089. ```
  2090. There are only two functions that must be implemented - `onInit` and `onUninit`. The other
  2091. functions can be implemented for a small optimization for loading from a file path or memory. If
  2092. these are not specified, miniaudio will deal with it for you via a generic implementation.
  2093. When you initialize a custom data source (by implementing the `onInit` function in the vtable) you
  2094. will need to output a pointer to a `ma_data_source` which implements your custom decoder. See the
  2095. section about data sources for details on how to implement this. Alternatively, see the
  2096. "custom_decoders" example in the miniaudio repository.
  2097. The `onInit` function takes a pointer to some callbacks for the purpose of reading raw audio data
  2098. from some arbitrary source. You'll use these functions to read from the raw data and perform the
  2099. decoding. When you call them, you will pass in the `pReadSeekTellUserData` pointer to the relevant
  2100. parameter.
  2101. The `pConfig` parameter in `onInit` can be used to configure the backend if appropriate. It's only
  2102. used as a hint and can be ignored. However, if any of the properties are relevant to your decoder,
  2103. an optimal implementation will handle the relevant properties appropriately.
  2104. If memory allocation is required, it should be done so via the specified allocation callbacks if
  2105. possible (the `pAllocationCallbacks` parameter).
  2106. If an error occurs when initializing the decoder, you should leave `ppBackend` unset, or set to
  2107. NULL, and make sure everything is cleaned up appropriately and an appropriate result code returned.
  2108. When multiple custom backends are specified, miniaudio will cycle through the vtables in the order
  2109. they're listed in the array that's passed into the decoder config so it's important that your
  2110. initialization routine is clean.
  2111. When a decoder is uninitialized, the `onUninit` callback will be fired which will give you an
  2112. opportunity to clean up and internal data.
  2113. 9. Encoding
  2114. ===========
  2115. The `ma_encoding` API is used for writing audio files. The only supported output format is WAV.
  2116. This can be disabled by specifying the following option before the implementation of miniaudio:
  2117. ```c
  2118. #define MA_NO_WAV
  2119. ```
  2120. An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data
  2121. delivered via callbacks with `ma_encoder_init()`. Below is an example for initializing an encoder
  2122. to output to a file.
  2123. ```c
  2124. ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, FORMAT, CHANNELS, SAMPLE_RATE);
  2125. ma_encoder encoder;
  2126. ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder);
  2127. if (result != MA_SUCCESS) {
  2128. // Error
  2129. }
  2130. ...
  2131. ma_encoder_uninit(&encoder);
  2132. ```
  2133. When initializing an encoder you must specify a config which is initialized with
  2134. `ma_encoder_config_init()`. Here you must specify the file type, the output sample format, output
  2135. channel count and output sample rate. The following file types are supported:
  2136. +------------------------+-------------+
  2137. | Enum | Description |
  2138. +------------------------+-------------+
  2139. | ma_encoding_format_wav | WAV |
  2140. +------------------------+-------------+
  2141. If the format, channel count or sample rate is not supported by the output file type an error will
  2142. be returned. The encoder will not perform data conversion so you will need to convert it before
  2143. outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the
  2144. example below:
  2145. ```c
  2146. ma_uint64 framesWritten;
  2147. result = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite, &framesWritten);
  2148. if (result != MA_SUCCESS) {
  2149. ... handle error ...
  2150. }
  2151. ```
  2152. The `framesWritten` variable will contain the number of PCM frames that were actually written. This
  2153. is optionally and you can pass in `NULL` if you need this.
  2154. Encoders must be uninitialized with `ma_encoder_uninit()`.
  2155. 10. Data Conversion
  2156. ===================
  2157. A data conversion API is included with miniaudio which supports the majority of data conversion
  2158. requirements. This supports conversion between sample formats, channel counts (with channel
  2159. mapping) and sample rates.
  2160. 10.1. Sample Format Conversion
  2161. ------------------------------
  2162. Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and
  2163. `ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()` to convert between two specific
  2164. formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use
  2165. `ma_convert_pcm_frames_format()` to convert PCM frames where you want to specify the frame count
  2166. and channel count as a variable instead of the total sample count.
  2167. 10.1.1. Dithering
  2168. -----------------
  2169. Dithering can be set using the ditherMode parameter.
  2170. The different dithering modes include the following, in order of efficiency:
  2171. +-----------+--------------------------+
  2172. | Type | Enum Token |
  2173. +-----------+--------------------------+
  2174. | None | ma_dither_mode_none |
  2175. | Rectangle | ma_dither_mode_rectangle |
  2176. | Triangle | ma_dither_mode_triangle |
  2177. +-----------+--------------------------+
  2178. Note that even if the dither mode is set to something other than `ma_dither_mode_none`, it will be
  2179. ignored for conversions where dithering is not needed. Dithering is available for the following
  2180. conversions:
  2181. ```
  2182. s16 -> u8
  2183. s24 -> u8
  2184. s32 -> u8
  2185. f32 -> u8
  2186. s24 -> s16
  2187. s32 -> s16
  2188. f32 -> s16
  2189. ```
  2190. Note that it is not an error to pass something other than ma_dither_mode_none for conversions where
  2191. dither is not used. It will just be ignored.
  2192. 10.2. Channel Conversion
  2193. ------------------------
  2194. Channel conversion is used for channel rearrangement and conversion from one channel count to
  2195. another. The `ma_channel_converter` API is used for channel conversion. Below is an example of
  2196. initializing a simple channel converter which converts from mono to stereo.
  2197. ```c
  2198. ma_channel_converter_config config = ma_channel_converter_config_init(
  2199. ma_format, // Sample format
  2200. 1, // Input channels
  2201. NULL, // Input channel map
  2202. 2, // Output channels
  2203. NULL, // Output channel map
  2204. ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels.
  2205. result = ma_channel_converter_init(&config, NULL, &converter);
  2206. if (result != MA_SUCCESS) {
  2207. // Error.
  2208. }
  2209. ```
  2210. To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so:
  2211. ```c
  2212. ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount);
  2213. if (result != MA_SUCCESS) {
  2214. // Error.
  2215. }
  2216. ```
  2217. It is up to the caller to ensure the output buffer is large enough to accommodate the new PCM
  2218. frames.
  2219. Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported.
  2220. 10.2.1. Channel Mapping
  2221. -----------------------
  2222. In addition to converting from one channel count to another, like the example above, the channel
  2223. converter can also be used to rearrange channels. When initializing the channel converter, you can
  2224. optionally pass in channel maps for both the input and output frames. If the channel counts are the
  2225. same, and each channel map contains the same channel positions with the exception that they're in
  2226. a different order, a simple shuffling of the channels will be performed. If, however, there is not
  2227. a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed
  2228. based on a mixing mode which is specified when initializing the `ma_channel_converter_config`
  2229. object.
  2230. When converting from mono to multi-channel, the mono channel is simply copied to each output
  2231. channel. When going the other way around, the audio of each output channel is simply averaged and
  2232. copied to the mono channel.
  2233. In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess
  2234. channels and silence extra channels. For example, converting from 4 to 2 channels, the 3rd and 4th
  2235. channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and
  2236. 4th channels.
  2237. The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a
  2238. simple distribution between input and output. Imagine sitting in the middle of a room, with
  2239. speakers on the walls representing channel positions. The `MA_CHANNEL_FRONT_LEFT` position can be
  2240. thought of as being in the corner of the front and left walls.
  2241. Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined
  2242. weights. Custom weights can be passed in as the last parameter of
  2243. `ma_channel_converter_config_init()`.
  2244. Predefined channel maps can be retrieved with `ma_channel_map_init_standard()`. This takes a
  2245. `ma_standard_channel_map` enum as it's first parameter, which can be one of the following:
  2246. +-----------------------------------+-----------------------------------------------------------+
  2247. | Name | Description |
  2248. +-----------------------------------+-----------------------------------------------------------+
  2249. | ma_standard_channel_map_default | Default channel map used by miniaudio. See below. |
  2250. | ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. |
  2251. | ma_standard_channel_map_alsa | Default ALSA channel map. |
  2252. | ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. |
  2253. | ma_standard_channel_map_flac | FLAC channel map. |
  2254. | ma_standard_channel_map_vorbis | Vorbis channel map. |
  2255. | ma_standard_channel_map_sound4 | FreeBSD's sound(4). |
  2256. | ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. |
  2257. | ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering |
  2258. +-----------------------------------+-----------------------------------------------------------+
  2259. Below are the channel maps used by default in miniaudio (`ma_standard_channel_map_default`):
  2260. +---------------+---------------------------------+
  2261. | Channel Count | Mapping |
  2262. +---------------+---------------------------------+
  2263. | 1 (Mono) | 0: MA_CHANNEL_MONO |
  2264. +---------------+---------------------------------+
  2265. | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2266. | | 1: MA_CHANNEL_FRONT_RIGHT |
  2267. +---------------+---------------------------------+
  2268. | 3 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2269. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2270. | | 2: MA_CHANNEL_FRONT_CENTER |
  2271. +---------------+---------------------------------+
  2272. | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2273. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2274. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2275. | | 3: MA_CHANNEL_BACK_CENTER |
  2276. +---------------+---------------------------------+
  2277. | 5 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2278. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2279. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2280. | | 3: MA_CHANNEL_BACK_LEFT <br> |
  2281. | | 4: MA_CHANNEL_BACK_RIGHT |
  2282. +---------------+---------------------------------+
  2283. | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2284. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2285. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2286. | | 3: MA_CHANNEL_LFE <br> |
  2287. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2288. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2289. +---------------+---------------------------------+
  2290. | 7 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2291. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2292. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2293. | | 3: MA_CHANNEL_LFE <br> |
  2294. | | 4: MA_CHANNEL_BACK_CENTER <br> |
  2295. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2296. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2297. +---------------+---------------------------------+
  2298. | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2299. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2300. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2301. | | 3: MA_CHANNEL_LFE <br> |
  2302. | | 4: MA_CHANNEL_BACK_LEFT <br> |
  2303. | | 5: MA_CHANNEL_BACK_RIGHT <br> |
  2304. | | 6: MA_CHANNEL_SIDE_LEFT <br> |
  2305. | | 7: MA_CHANNEL_SIDE_RIGHT |
  2306. +---------------+---------------------------------+
  2307. | Other | All channels set to 0. This |
  2308. | | is equivalent to the same |
  2309. | | mapping as the device. |
  2310. +---------------+---------------------------------+
  2311. 10.3. Resampling
  2312. ----------------
  2313. Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something
  2314. like the following:
  2315. ```c
  2316. ma_resampler_config config = ma_resampler_config_init(
  2317. ma_format_s16,
  2318. channels,
  2319. sampleRateIn,
  2320. sampleRateOut,
  2321. ma_resample_algorithm_linear);
  2322. ma_resampler resampler;
  2323. ma_result result = ma_resampler_init(&config, &resampler);
  2324. if (result != MA_SUCCESS) {
  2325. // An error occurred...
  2326. }
  2327. ```
  2328. Do the following to uninitialize the resampler:
  2329. ```c
  2330. ma_resampler_uninit(&resampler);
  2331. ```
  2332. The following example shows how data can be processed
  2333. ```c
  2334. ma_uint64 frameCountIn = 1000;
  2335. ma_uint64 frameCountOut = 2000;
  2336. ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2337. if (result != MA_SUCCESS) {
  2338. // An error occurred...
  2339. }
  2340. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the
  2341. // number of output frames written.
  2342. ```
  2343. To initialize the resampler you first need to set up a config (`ma_resampler_config`) with
  2344. `ma_resampler_config_init()`. You need to specify the sample format you want to use, the number of
  2345. channels, the input and output sample rate, and the algorithm.
  2346. The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format
  2347. you will need to perform pre- and post-conversions yourself where necessary. Note that the format
  2348. is the same for both input and output. The format cannot be changed after initialization.
  2349. The resampler supports multiple channels and is always interleaved (both input and output). The
  2350. channel count cannot be changed after initialization.
  2351. The sample rates can be anything other than zero, and are always specified in hertz. They should be
  2352. set to something like 44100, etc. The sample rate is the only configuration property that can be
  2353. changed after initialization.
  2354. The miniaudio resampler has built-in support for the following algorithms:
  2355. +-----------+------------------------------+
  2356. | Algorithm | Enum Token |
  2357. +-----------+------------------------------+
  2358. | Linear | ma_resample_algorithm_linear |
  2359. | Custom | ma_resample_algorithm_custom |
  2360. +-----------+------------------------------+
  2361. The algorithm cannot be changed after initialization.
  2362. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2363. De-interleaved processing is not supported. To process frames, use
  2364. `ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you
  2365. can fit in the output buffer and the number of input frames contained in the input buffer. On
  2366. output these variables contain the number of output frames that were written to the output buffer
  2367. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2368. input buffer in which case it will be treated as an infinitely large buffer of zeros. The output
  2369. buffer can also be NULL, in which case the processing will be treated as seek.
  2370. The sample rate can be changed dynamically on the fly. You can change this with explicit sample
  2371. rates with `ma_resampler_set_rate()` and also with a decimal ratio with
  2372. `ma_resampler_set_rate_ratio()`. The ratio is in/out.
  2373. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2374. number of frames. You can calculate this with `ma_resampler_get_required_input_frame_count()`.
  2375. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2376. number of input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`.
  2377. Due to the nature of how resampling works, the resampler introduces some latency. This can be
  2378. retrieved in terms of both the input rate and the output rate with
  2379. `ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`.
  2380. 10.3.1. Resampling Algorithms
  2381. -----------------------------
  2382. The choice of resampling algorithm depends on your situation and requirements.
  2383. 10.3.1.1. Linear Resampling
  2384. ---------------------------
  2385. The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however,
  2386. some control over the quality of the linear resampler which may make it a suitable option depending
  2387. on your requirements.
  2388. The linear resampler performs low-pass filtering before or after downsampling or upsampling,
  2389. depending on the sample rates you're converting between. When decreasing the sample rate, the
  2390. low-pass filter will be applied before downsampling. When increasing the rate it will be performed
  2391. after upsampling. By default a fourth order low-pass filter will be applied. This can be configured
  2392. via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering.
  2393. The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of
  2394. the input and output sample rates (Nyquist Frequency).
  2395. The API for the linear resampler is the same as the main resampler API, only it's called
  2396. `ma_linear_resampler`.
  2397. 10.3.2. Custom Resamplers
  2398. -------------------------
  2399. You can implement a custom resampler by using the `ma_resample_algorithm_custom` resampling
  2400. algorithm and setting a vtable in the resampler config:
  2401. ```c
  2402. ma_resampler_config config = ma_resampler_config_init(..., ma_resample_algorithm_custom);
  2403. config.pBackendVTable = &g_customResamplerVTable;
  2404. ```
  2405. Custom resamplers are useful if the stock algorithms are not appropriate for your use case. You
  2406. need to implement the required functions in `ma_resampling_backend_vtable`. Note that not all
  2407. functions in the vtable need to be implemented, but if it's possible to implement, they should be.
  2408. You can use the `ma_linear_resampler` object for an example on how to implement the vtable. The
  2409. `onGetHeapSize` callback is used to calculate the size of any internal heap allocation the custom
  2410. resampler will need to make given the supplied config. When you initialize the resampler via the
  2411. `onInit` callback, you'll be given a pointer to a heap allocation which is where you should store
  2412. the heap allocated data. You should not free this data in `onUninit` because miniaudio will manage
  2413. it for you.
  2414. The `onProcess` callback is where the actual resampling takes place. On input, `pFrameCountIn`
  2415. points to a variable containing the number of frames in the `pFramesIn` buffer and
  2416. `pFrameCountOut` points to a variable containing the capacity in frames of the `pFramesOut` buffer.
  2417. On output, `pFrameCountIn` should be set to the number of input frames that were fully consumed,
  2418. whereas `pFrameCountOut` should be set to the number of frames that were written to `pFramesOut`.
  2419. The `onSetRate` callback is optional and is used for dynamically changing the sample rate. If
  2420. dynamic rate changes are not supported, you can set this callback to NULL.
  2421. The `onGetInputLatency` and `onGetOutputLatency` functions are used for retrieving the latency in
  2422. input and output rates respectively. These can be NULL in which case latency calculations will be
  2423. assumed to be NULL.
  2424. The `onGetRequiredInputFrameCount` callback is used to give miniaudio a hint as to how many input
  2425. frames are required to be available to produce the given number of output frames. Likewise, the
  2426. `onGetExpectedOutputFrameCount` callback is used to determine how many output frames will be
  2427. produced given the specified number of input frames. miniaudio will use these as a hint, but they
  2428. are optional and can be set to NULL if you're unable to implement them.
  2429. 10.4. General Data Conversion
  2430. -----------------------------
  2431. The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and
  2432. resampling into one operation. This is what miniaudio uses internally to convert between the format
  2433. requested when the device was initialized and the format of the backend's native device. The API
  2434. for general data conversion is very similar to the resampling API. Create a `ma_data_converter`
  2435. object like this:
  2436. ```c
  2437. ma_data_converter_config config = ma_data_converter_config_init(
  2438. inputFormat,
  2439. outputFormat,
  2440. inputChannels,
  2441. outputChannels,
  2442. inputSampleRate,
  2443. outputSampleRate
  2444. );
  2445. ma_data_converter converter;
  2446. ma_result result = ma_data_converter_init(&config, NULL, &converter);
  2447. if (result != MA_SUCCESS) {
  2448. // An error occurred...
  2449. }
  2450. ```
  2451. In the example above we use `ma_data_converter_config_init()` to initialize the config, however
  2452. there's many more properties that can be configured, such as channel maps and resampling quality.
  2453. Something like the following may be more suitable depending on your requirements:
  2454. ```c
  2455. ma_data_converter_config config = ma_data_converter_config_init_default();
  2456. config.formatIn = inputFormat;
  2457. config.formatOut = outputFormat;
  2458. config.channelsIn = inputChannels;
  2459. config.channelsOut = outputChannels;
  2460. config.sampleRateIn = inputSampleRate;
  2461. config.sampleRateOut = outputSampleRate;
  2462. ma_channel_map_init_standard(ma_standard_channel_map_flac, config.channelMapIn, sizeof(config.channelMapIn)/sizeof(config.channelMapIn[0]), config.channelCountIn);
  2463. config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER;
  2464. ```
  2465. Do the following to uninitialize the data converter:
  2466. ```c
  2467. ma_data_converter_uninit(&converter, NULL);
  2468. ```
  2469. The following example shows how data can be processed
  2470. ```c
  2471. ma_uint64 frameCountIn = 1000;
  2472. ma_uint64 frameCountOut = 2000;
  2473. ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2474. if (result != MA_SUCCESS) {
  2475. // An error occurred...
  2476. }
  2477. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number
  2478. // of output frames written.
  2479. ```
  2480. The data converter supports multiple channels and is always interleaved (both input and output).
  2481. The channel count cannot be changed after initialization.
  2482. Sample rates can be anything other than zero, and are always specified in hertz. They should be set
  2483. to something like 44100, etc. The sample rate is the only configuration property that can be
  2484. changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of
  2485. `ma_data_converter_config` is set to `MA_TRUE`. To change the sample rate, use
  2486. `ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out.
  2487. The resampling algorithm cannot be changed after initialization.
  2488. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2489. De-interleaved processing is not supported. To process frames, use
  2490. `ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames
  2491. you can fit in the output buffer and the number of input frames contained in the input buffer. On
  2492. output these variables contain the number of output frames that were written to the output buffer
  2493. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2494. input buffer in which case it will be treated as an infinitely large
  2495. buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated
  2496. as seek.
  2497. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2498. number of frames. You can calculate this with `ma_data_converter_get_required_input_frame_count()`.
  2499. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2500. number of input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`.
  2501. Due to the nature of how resampling works, the data converter introduces some latency if resampling
  2502. is required. This can be retrieved in terms of both the input rate and the output rate with
  2503. `ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`.
  2504. 11. Filtering
  2505. =============
  2506. 11.1. Biquad Filtering
  2507. ----------------------
  2508. Biquad filtering is achieved with the `ma_biquad` API. Example:
  2509. ```c
  2510. ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  2511. ma_result result = ma_biquad_init(&config, &biquad);
  2512. if (result != MA_SUCCESS) {
  2513. // Error.
  2514. }
  2515. ...
  2516. ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount);
  2517. ```
  2518. Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0,
  2519. b1 and b2, and the denominator coefficients are a0, a1 and a2. The a0 coefficient is required and
  2520. coefficients must not be pre-normalized.
  2521. Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format
  2522. you need to convert it yourself beforehand. When using `ma_format_s16` the biquad filter will use
  2523. fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used.
  2524. Input and output frames are always interleaved.
  2525. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2526. buffers, like so:
  2527. ```c
  2528. ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount);
  2529. ```
  2530. If you need to change the values of the coefficients, but maintain the values in the registers you
  2531. can do so with `ma_biquad_reinit()`. This is useful if you need to change the properties of the
  2532. filter while keeping the values of registers valid to avoid glitching. Do not use
  2533. `ma_biquad_init()` for this as it will do a full initialization which involves clearing the
  2534. registers to 0. Note that changing the format or channel count after initialization is invalid and
  2535. will result in an error.
  2536. 11.2. Low-Pass Filtering
  2537. ------------------------
  2538. Low-pass filtering is achieved with the following APIs:
  2539. +---------+------------------------------------------+
  2540. | API | Description |
  2541. +---------+------------------------------------------+
  2542. | ma_lpf1 | First order low-pass filter |
  2543. | ma_lpf2 | Second order low-pass filter |
  2544. | ma_lpf | High order low-pass filter (Butterworth) |
  2545. +---------+------------------------------------------+
  2546. Low-pass filter example:
  2547. ```c
  2548. ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  2549. ma_result result = ma_lpf_init(&config, &lpf);
  2550. if (result != MA_SUCCESS) {
  2551. // Error.
  2552. }
  2553. ...
  2554. ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount);
  2555. ```
  2556. Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format
  2557. you need to convert it yourself beforehand. Input and output frames are always interleaved.
  2558. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2559. buffers, like so:
  2560. ```c
  2561. ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount);
  2562. ```
  2563. The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more,
  2564. you can chain first and second order filters together.
  2565. ```c
  2566. for (iFilter = 0; iFilter < filterCount; iFilter += 1) {
  2567. ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount);
  2568. }
  2569. ```
  2570. If you need to change the configuration of the filter, but need to maintain the state of internal
  2571. registers you can do so with `ma_lpf_reinit()`. This may be useful if you need to change the sample
  2572. rate and/or cutoff frequency dynamically while maintaining smooth transitions. Note that changing the
  2573. format or channel count after initialization is invalid and will result in an error.
  2574. The `ma_lpf` object supports a configurable order, but if you only need a first order filter you
  2575. may want to consider using `ma_lpf1`. Likewise, if you only need a second order filter you can use
  2576. `ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient.
  2577. If an even filter order is specified, a series of second order filters will be processed in a
  2578. chain. If an odd filter order is specified, a first order filter will be applied, followed by a
  2579. series of second order filters in a chain.
  2580. 11.3. High-Pass Filtering
  2581. -------------------------
  2582. High-pass filtering is achieved with the following APIs:
  2583. +---------+-------------------------------------------+
  2584. | API | Description |
  2585. +---------+-------------------------------------------+
  2586. | ma_hpf1 | First order high-pass filter |
  2587. | ma_hpf2 | Second order high-pass filter |
  2588. | ma_hpf | High order high-pass filter (Butterworth) |
  2589. +---------+-------------------------------------------+
  2590. High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`,
  2591. `ma_hpf2` and `ma_hpf`. See example code for low-pass filters for example usage.
  2592. 11.4. Band-Pass Filtering
  2593. -------------------------
  2594. Band-pass filtering is achieved with the following APIs:
  2595. +---------+-------------------------------+
  2596. | API | Description |
  2597. +---------+-------------------------------+
  2598. | ma_bpf2 | Second order band-pass filter |
  2599. | ma_bpf | High order band-pass filter |
  2600. +---------+-------------------------------+
  2601. Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and
  2602. `ma_hpf`. See example code for low-pass filters for example usage. Note that the order for
  2603. band-pass filters must be an even number which means there is no first order band-pass filter,
  2604. unlike low-pass and high-pass filters.
  2605. 11.5. Notch Filtering
  2606. ---------------------
  2607. Notch filtering is achieved with the following APIs:
  2608. +-----------+------------------------------------------+
  2609. | API | Description |
  2610. +-----------+------------------------------------------+
  2611. | ma_notch2 | Second order notching filter |
  2612. +-----------+------------------------------------------+
  2613. 11.6. Peaking EQ Filtering
  2614. -------------------------
  2615. Peaking filtering is achieved with the following APIs:
  2616. +----------+------------------------------------------+
  2617. | API | Description |
  2618. +----------+------------------------------------------+
  2619. | ma_peak2 | Second order peaking filter |
  2620. +----------+------------------------------------------+
  2621. 11.7. Low Shelf Filtering
  2622. -------------------------
  2623. Low shelf filtering is achieved with the following APIs:
  2624. +-------------+------------------------------------------+
  2625. | API | Description |
  2626. +-------------+------------------------------------------+
  2627. | ma_loshelf2 | Second order low shelf filter |
  2628. +-------------+------------------------------------------+
  2629. Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to
  2630. just turn them down rather than eliminate them entirely.
  2631. 11.8. High Shelf Filtering
  2632. --------------------------
  2633. High shelf filtering is achieved with the following APIs:
  2634. +-------------+------------------------------------------+
  2635. | API | Description |
  2636. +-------------+------------------------------------------+
  2637. | ma_hishelf2 | Second order high shelf filter |
  2638. +-------------+------------------------------------------+
  2639. The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf`
  2640. instead of `ma_loshelf`. Where a low shelf filter is used to adjust the volume of low frequencies,
  2641. the high shelf filter does the same thing for high frequencies.
  2642. 12. Waveform and Noise Generation
  2643. =================================
  2644. 12.1. Waveforms
  2645. ---------------
  2646. miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved
  2647. with the `ma_waveform` API. Example:
  2648. ```c
  2649. ma_waveform_config config = ma_waveform_config_init(
  2650. FORMAT,
  2651. CHANNELS,
  2652. SAMPLE_RATE,
  2653. ma_waveform_type_sine,
  2654. amplitude,
  2655. frequency);
  2656. ma_waveform waveform;
  2657. ma_result result = ma_waveform_init(&config, &waveform);
  2658. if (result != MA_SUCCESS) {
  2659. // Error.
  2660. }
  2661. ...
  2662. ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount);
  2663. ```
  2664. The amplitude, frequency, type, and sample rate can be changed dynamically with
  2665. `ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`, `ma_waveform_set_type()`, and
  2666. `ma_waveform_set_sample_rate()` respectively.
  2667. You can invert the waveform by setting the amplitude to a negative value. You can use this to
  2668. control whether or not a sawtooth has a positive or negative ramp, for example.
  2669. Below are the supported waveform types:
  2670. +---------------------------+
  2671. | Enum Name |
  2672. +---------------------------+
  2673. | ma_waveform_type_sine |
  2674. | ma_waveform_type_square |
  2675. | ma_waveform_type_triangle |
  2676. | ma_waveform_type_sawtooth |
  2677. +---------------------------+
  2678. 12.2. Noise
  2679. -----------
  2680. miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example:
  2681. ```c
  2682. ma_noise_config config = ma_noise_config_init(
  2683. FORMAT,
  2684. CHANNELS,
  2685. ma_noise_type_white,
  2686. SEED,
  2687. amplitude);
  2688. ma_noise noise;
  2689. ma_result result = ma_noise_init(&config, &noise);
  2690. if (result != MA_SUCCESS) {
  2691. // Error.
  2692. }
  2693. ...
  2694. ma_noise_read_pcm_frames(&noise, pOutput, frameCount);
  2695. ```
  2696. The noise API uses simple LCG random number generation. It supports a custom seed which is useful
  2697. for things like automated testing requiring reproducibility. Setting the seed to zero will default
  2698. to `MA_DEFAULT_LCG_SEED`.
  2699. The amplitude and seed can be changed dynamically with `ma_noise_set_amplitude()` and
  2700. `ma_noise_set_seed()` respectively.
  2701. By default, the noise API will use different values for different channels. So, for example, the
  2702. left side in a stereo stream will be different to the right side. To instead have each channel use
  2703. the same random value, set the `duplicateChannels` member of the noise config to true, like so:
  2704. ```c
  2705. config.duplicateChannels = MA_TRUE;
  2706. ```
  2707. Below are the supported noise types.
  2708. +------------------------+
  2709. | Enum Name |
  2710. +------------------------+
  2711. | ma_noise_type_white |
  2712. | ma_noise_type_pink |
  2713. | ma_noise_type_brownian |
  2714. +------------------------+
  2715. 13. Audio Buffers
  2716. =================
  2717. miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can
  2718. read from memory that's managed by the application, but can also handle the memory management for
  2719. you internally. Memory management is flexible and should support most use cases.
  2720. Audio buffers are initialized using the standard configuration system used everywhere in miniaudio:
  2721. ```c
  2722. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2723. format,
  2724. channels,
  2725. sizeInFrames,
  2726. pExistingData,
  2727. &allocationCallbacks);
  2728. ma_audio_buffer buffer;
  2729. result = ma_audio_buffer_init(&config, &buffer);
  2730. if (result != MA_SUCCESS) {
  2731. // Error.
  2732. }
  2733. ...
  2734. ma_audio_buffer_uninit(&buffer);
  2735. ```
  2736. In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an
  2737. application can do self-managed memory allocation. If you would rather make a copy of the data, use
  2738. `ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`.
  2739. Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the
  2740. raw audio data in a contiguous block of memory. That is, the raw audio data will be located
  2741. immediately after the `ma_audio_buffer` structure. To do this, use
  2742. `ma_audio_buffer_alloc_and_init()`:
  2743. ```c
  2744. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2745. format,
  2746. channels,
  2747. sizeInFrames,
  2748. pExistingData,
  2749. &allocationCallbacks);
  2750. ma_audio_buffer* pBuffer
  2751. result = ma_audio_buffer_alloc_and_init(&config, &pBuffer);
  2752. if (result != MA_SUCCESS) {
  2753. // Error
  2754. }
  2755. ...
  2756. ma_audio_buffer_uninit_and_free(&buffer);
  2757. ```
  2758. If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it
  2759. with `ma_audio_buffer_uninit_and_free()`. In the example above, the memory pointed to by
  2760. `pExistingData` will be copied into the buffer, which is contrary to the behavior of
  2761. `ma_audio_buffer_init()`.
  2762. An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the
  2763. cursor moves forward. The last parameter (`loop`) can be used to determine if the buffer should
  2764. loop. The return value is the number of frames actually read. If this is less than the number of
  2765. frames requested it means the end has been reached. This should never happen if the `loop`
  2766. parameter is set to true. If you want to manually loop back to the start, you can do so with with
  2767. `ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an
  2768. audio buffer.
  2769. ```c
  2770. ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping);
  2771. if (framesRead < desiredFrameCount) {
  2772. // If not looping, this means the end has been reached. This should never happen in looping mode with valid input.
  2773. }
  2774. ```
  2775. Sometimes you may want to avoid the cost of data movement between the internal buffer and the
  2776. output buffer. Instead you can use memory mapping to retrieve a pointer to a segment of data:
  2777. ```c
  2778. void* pMappedFrames;
  2779. ma_uint64 frameCount = frameCountToTryMapping;
  2780. ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount);
  2781. if (result == MA_SUCCESS) {
  2782. // Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be
  2783. // less due to the end of the buffer being reached.
  2784. ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels);
  2785. // You must unmap the buffer.
  2786. ma_audio_buffer_unmap(pAudioBuffer, frameCount);
  2787. }
  2788. ```
  2789. When you use memory mapping, the read cursor is increment by the frame count passed in to
  2790. `ma_audio_buffer_unmap()`. If you decide not to process every frame you can pass in a value smaller
  2791. than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is
  2792. that it does not handle looping for you. You can determine if the buffer is at the end for the
  2793. purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of
  2794. `ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END`
  2795. as an error when returned by `ma_audio_buffer_unmap()`.
  2796. 14. Ring Buffers
  2797. ================
  2798. miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via
  2799. the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates on bytes, whereas the `ma_pcm_rb`
  2800. operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around
  2801. `ma_rb`.
  2802. Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved
  2803. streams. The caller can also allocate their own backing memory for the ring buffer to use
  2804. internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for
  2805. you.
  2806. The examples below use the PCM frame variant of the ring buffer since that's most likely the one
  2807. you will want to use. To initialize a ring buffer, do something like the following:
  2808. ```c
  2809. ma_pcm_rb rb;
  2810. ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb);
  2811. if (result != MA_SUCCESS) {
  2812. // Error
  2813. }
  2814. ```
  2815. The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because
  2816. it's the PCM variant of the ring buffer API. For the regular ring buffer that operates on bytes you
  2817. would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes
  2818. instead of frames. The fourth parameter is an optional pre-allocated buffer and the fifth parameter
  2819. is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation routines.
  2820. Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used.
  2821. Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is
  2822. offset from each other based on the stride. To manage your sub-buffers you can use
  2823. `ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and
  2824. `ma_pcm_rb_get_subbuffer_ptr()`.
  2825. Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section
  2826. of the ring buffer. You specify the number of frames you need, and on output it will set to what
  2827. was actually acquired. If the read or write pointer is positioned such that the number of frames
  2828. requested will require a loop, it will be clamped to the end of the buffer. Therefore, the number
  2829. of frames you're given may be less than the number you requested.
  2830. After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the
  2831. buffer and then "commit" it with `ma_pcm_rb_commit_read()` or `ma_pcm_rb_commit_write()`. This is
  2832. where the read/write pointers are updated. When you commit you need to pass in the buffer that was
  2833. returned by the earlier call to `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is
  2834. only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and
  2835. `ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was
  2836. originally requested.
  2837. If you want to correct for drift between the write pointer and the read pointer you can use a
  2838. combination of `ma_pcm_rb_pointer_distance()`, `ma_pcm_rb_seek_read()` and
  2839. `ma_pcm_rb_seek_write()`. Note that you can only move the pointers forward, and you should only
  2840. move the read pointer forward via the consumer thread, and the write pointer forward by the
  2841. producer thread. If there is too much space between the pointers, move the read pointer forward. If
  2842. there is too little space between the pointers, move the write pointer forward.
  2843. You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb`
  2844. API. This is exactly the same, only you will use the `ma_rb` functions instead of `ma_pcm_rb` and
  2845. instead of frame counts you will pass around byte counts.
  2846. The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most
  2847. significant bit being used to encode a loop flag and the internally managed buffers always being
  2848. aligned to `MA_SIMD_ALIGNMENT`.
  2849. Note that the ring buffer is only thread safe when used by a single consumer thread and single
  2850. producer thread.
  2851. 15. Backends
  2852. ============
  2853. The following backends are supported by miniaudio. These are listed in order of default priority.
  2854. When no backend is specified when initializing a context or device, miniaudio will attempt to use
  2855. each of these backends in the order listed in the table below.
  2856. Note that backends that are not usable by the build target will not be included in the build. For
  2857. example, ALSA, which is specific to Linux, will not be included in the Windows build.
  2858. +-------------+-----------------------+--------------------------------------------------------+
  2859. | Name | Enum Name | Supported Operating Systems |
  2860. +-------------+-----------------------+--------------------------------------------------------+
  2861. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  2862. | DirectSound | ma_backend_dsound | Windows XP+ |
  2863. | WinMM | ma_backend_winmm | Windows 95+ |
  2864. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  2865. | sndio | ma_backend_sndio | OpenBSD |
  2866. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  2867. | OSS | ma_backend_oss | FreeBSD |
  2868. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  2869. | ALSA | ma_backend_alsa | Linux |
  2870. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  2871. | AAudio | ma_backend_aaudio | Android 8+ |
  2872. | OpenSL ES | ma_backend_opensl | Android (API level 16+) |
  2873. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  2874. | Custom | ma_backend_custom | Cross Platform |
  2875. | Null | ma_backend_null | Cross Platform (not used on Web) |
  2876. +-------------+-----------------------+--------------------------------------------------------+
  2877. Some backends have some nuance details you may want to be aware of.
  2878. 15.1. WASAPI
  2879. ------------
  2880. - Low-latency shared mode will be disabled when using an application-defined sample rate which is
  2881. different to the device's native sample rate. To work around this, set `wasapi.noAutoConvertSRC`
  2882. to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing
  2883. when the `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC
  2884. will result in miniaudio's internal resampler being used instead which will in turn enable the
  2885. use of low-latency shared mode.
  2886. 15.2. PulseAudio
  2887. ----------------
  2888. - If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki:
  2889. https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling.
  2890. Alternatively, consider using a different backend such as ALSA.
  2891. 15.3. Android
  2892. -------------
  2893. - To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest:
  2894. `<uses-permission android:name="android.permission.RECORD_AUDIO" />`
  2895. - With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a
  2896. limitation with OpenSL|ES.
  2897. - With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration
  2898. API (devices are enumerated through Java). You can however perform your own device enumeration
  2899. through Java and then set the ID in the ma_device_id structure (ma_device_id.aaudio) and pass it
  2900. to ma_device_init().
  2901. - The backend API will perform resampling where possible. The reason for this as opposed to using
  2902. miniaudio's built-in resampler is to take advantage of any potential device-specific
  2903. optimizations the driver may implement.
  2904. BSD
  2905. ---
  2906. - The sndio backend is currently only enabled on OpenBSD builds.
  2907. - The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can
  2908. use it.
  2909. 15.4. UWP
  2910. ---------
  2911. - UWP only supports default playback and capture devices.
  2912. - UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest):
  2913. ```
  2914. <Package ...>
  2915. ...
  2916. <Capabilities>
  2917. <DeviceCapability Name="microphone" />
  2918. </Capabilities>
  2919. </Package>
  2920. ```
  2921. 15.5. Web Audio / Emscripten
  2922. ----------------------------
  2923. - You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build.
  2924. - The first time a context is initialized it will create a global object called "miniaudio" whose
  2925. primary purpose is to act as a factory for device objects.
  2926. - Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as
  2927. they've been deprecated.
  2928. - Google has implemented a policy in their browsers that prevent automatic media output without
  2929. first receiving some kind of user input. The following web page has additional details:
  2930. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting the device
  2931. may fail if you try to start playback without first handling some kind of user input.
  2932. 16. Optimization Tips
  2933. =====================
  2934. See below for some tips on improving performance.
  2935. 16.1. Low Level API
  2936. -------------------
  2937. - In the data callback, if your data is already clipped prior to copying it into the output buffer,
  2938. set the `noClip` config option in the device config to true. This will disable miniaudio's built
  2939. in clipping function.
  2940. - By default, miniaudio will pre-silence the data callback's output buffer. If you know that you
  2941. will always write valid data to the output buffer you can disable pre-silencing by setting the
  2942. `noPreSilence` config option in the device config to true.
  2943. 16.2. High Level API
  2944. --------------------
  2945. - If a sound does not require doppler or pitch shifting, consider disabling pitching by
  2946. initializing the sound with the `MA_SOUND_FLAG_NO_PITCH` flag.
  2947. - If a sound does not require spatialization, disable it by initializing the sound with the
  2948. `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. It can be re-enabled again post-initialization with
  2949. `ma_sound_set_spatialization_enabled()`.
  2950. - If you know all of your sounds will always be the same sample rate, set the engine's sample
  2951. rate to match that of the sounds. Likewise, if you're using a self-managed resource manager,
  2952. consider setting the decoded sample rate to match your sounds. By configuring everything to
  2953. use a consistent sample rate, sample rate conversion can be avoided.
  2954. 17. Miscellaneous Notes
  2955. =======================
  2956. - Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for
  2957. WASAPI and Core Audio, however other backends such as PulseAudio may naturally support it, though
  2958. not all have been tested.
  2959. - When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This
  2960. is due to 64-bit file APIs not being available.
  2961. */
  2962. #ifndef miniaudio_h
  2963. #define miniaudio_h
  2964. #ifdef __cplusplus
  2965. extern "C" {
  2966. #endif
  2967. #define MA_STRINGIFY(x) #x
  2968. #define MA_XSTRINGIFY(x) MA_STRINGIFY(x)
  2969. #define MA_VERSION_MAJOR 0
  2970. #define MA_VERSION_MINOR 11
  2971. #define MA_VERSION_REVISION 19
  2972. #define MA_VERSION_STRING MA_XSTRINGIFY(MA_VERSION_MAJOR) "." MA_XSTRINGIFY(MA_VERSION_MINOR) "." MA_XSTRINGIFY(MA_VERSION_REVISION)
  2973. #if defined(_MSC_VER) && !defined(__clang__)
  2974. #pragma warning(push)
  2975. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  2976. #pragma warning(disable:4214) /* nonstandard extension used: bit field types other than int */
  2977. #pragma warning(disable:4324) /* structure was padded due to alignment specifier */
  2978. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  2979. #pragma GCC diagnostic push
  2980. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  2981. #if defined(__clang__)
  2982. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  2983. #endif
  2984. #endif
  2985. #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__)
  2986. #define MA_SIZEOF_PTR 8
  2987. #else
  2988. #define MA_SIZEOF_PTR 4
  2989. #endif
  2990. #include <stddef.h> /* For size_t. */
  2991. /* Sized types. */
  2992. #if defined(MA_USE_STDINT)
  2993. #include <stdint.h>
  2994. typedef int8_t ma_int8;
  2995. typedef uint8_t ma_uint8;
  2996. typedef int16_t ma_int16;
  2997. typedef uint16_t ma_uint16;
  2998. typedef int32_t ma_int32;
  2999. typedef uint32_t ma_uint32;
  3000. typedef int64_t ma_int64;
  3001. typedef uint64_t ma_uint64;
  3002. #else
  3003. typedef signed char ma_int8;
  3004. typedef unsigned char ma_uint8;
  3005. typedef signed short ma_int16;
  3006. typedef unsigned short ma_uint16;
  3007. typedef signed int ma_int32;
  3008. typedef unsigned int ma_uint32;
  3009. #if defined(_MSC_VER) && !defined(__clang__)
  3010. typedef signed __int64 ma_int64;
  3011. typedef unsigned __int64 ma_uint64;
  3012. #else
  3013. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  3014. #pragma GCC diagnostic push
  3015. #pragma GCC diagnostic ignored "-Wlong-long"
  3016. #if defined(__clang__)
  3017. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  3018. #endif
  3019. #endif
  3020. typedef signed long long ma_int64;
  3021. typedef unsigned long long ma_uint64;
  3022. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  3023. #pragma GCC diagnostic pop
  3024. #endif
  3025. #endif
  3026. #endif /* MA_USE_STDINT */
  3027. #if MA_SIZEOF_PTR == 8
  3028. typedef ma_uint64 ma_uintptr;
  3029. #else
  3030. typedef ma_uint32 ma_uintptr;
  3031. #endif
  3032. typedef ma_uint8 ma_bool8;
  3033. typedef ma_uint32 ma_bool32;
  3034. #define MA_TRUE 1
  3035. #define MA_FALSE 0
  3036. /* These float types are not used universally by miniaudio. It's to simplify some macro expansion for atomic types. */
  3037. typedef float ma_float;
  3038. typedef double ma_double;
  3039. typedef void* ma_handle;
  3040. typedef void* ma_ptr;
  3041. /*
  3042. ma_proc is annoying because when compiling with GCC we get pendantic warnings about converting
  3043. between `void*` and `void (*)()`. We can't use `void (*)()` with MSVC however, because we'll get
  3044. warning C4191 about "type cast between incompatible function types". To work around this I'm going
  3045. to use a different data type depending on the compiler.
  3046. */
  3047. #if defined(__GNUC__)
  3048. typedef void (*ma_proc)(void);
  3049. #else
  3050. typedef void* ma_proc;
  3051. #endif
  3052. #if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED)
  3053. typedef ma_uint16 wchar_t;
  3054. #endif
  3055. /* Define NULL for some compilers. */
  3056. #ifndef NULL
  3057. #define NULL 0
  3058. #endif
  3059. #if defined(SIZE_MAX)
  3060. #define MA_SIZE_MAX SIZE_MAX
  3061. #else
  3062. #define MA_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */
  3063. #endif
  3064. /* Platform/backend detection. */
  3065. #if defined(_WIN32) || defined(__COSMOPOLITAN__)
  3066. #define MA_WIN32
  3067. #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)))
  3068. #define MA_WIN32_UWP
  3069. #elif defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
  3070. #define MA_WIN32_GDK
  3071. #else
  3072. #define MA_WIN32_DESKTOP
  3073. #endif
  3074. #endif
  3075. #if !defined(_WIN32) /* If it's not Win32, assume POSIX. */
  3076. #define MA_POSIX
  3077. /*
  3078. Use the MA_NO_PTHREAD_IN_HEADER option at your own risk. This is intentionally undocumented.
  3079. You can use this to avoid including pthread.h in the header section. The downside is that it
  3080. results in some fixed sized structures being declared for the various types that are used in
  3081. miniaudio. The risk here is that these types might be too small for a given platform. This
  3082. risk is yours to take and no support will be offered if you enable this option.
  3083. */
  3084. #ifndef MA_NO_PTHREAD_IN_HEADER
  3085. #include <pthread.h> /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */
  3086. typedef pthread_t ma_pthread_t;
  3087. typedef pthread_mutex_t ma_pthread_mutex_t;
  3088. typedef pthread_cond_t ma_pthread_cond_t;
  3089. #else
  3090. typedef ma_uintptr ma_pthread_t;
  3091. typedef union ma_pthread_mutex_t { char __data[40]; ma_uint64 __alignment; } ma_pthread_mutex_t;
  3092. typedef union ma_pthread_cond_t { char __data[48]; ma_uint64 __alignment; } ma_pthread_cond_t;
  3093. #endif
  3094. #if defined(__unix__)
  3095. #define MA_UNIX
  3096. #endif
  3097. #if defined(__linux__)
  3098. #define MA_LINUX
  3099. #endif
  3100. #if defined(__APPLE__)
  3101. #define MA_APPLE
  3102. #endif
  3103. #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
  3104. #define MA_BSD
  3105. #endif
  3106. #if defined(__ANDROID__)
  3107. #define MA_ANDROID
  3108. #endif
  3109. #if defined(__EMSCRIPTEN__)
  3110. #define MA_EMSCRIPTEN
  3111. #endif
  3112. #if defined(__ORBIS__)
  3113. #define MA_ORBIS
  3114. #endif
  3115. #if defined(__PROSPERO__)
  3116. #define MA_PROSPERO
  3117. #endif
  3118. #if defined(__NX__)
  3119. #define MA_NX
  3120. #endif
  3121. #if defined(__BEOS__) || defined(__HAIKU__)
  3122. #define MA_BEOS
  3123. #endif
  3124. #if defined(__HAIKU__)
  3125. #define MA_HAIKU
  3126. #endif
  3127. #endif
  3128. #if defined(__has_c_attribute)
  3129. #if __has_c_attribute(fallthrough)
  3130. #define MA_FALLTHROUGH [[fallthrough]]
  3131. #endif
  3132. #endif
  3133. #if !defined(MA_FALLTHROUGH) && defined(__has_attribute) && (defined(__clang__) || defined(__GNUC__))
  3134. #if __has_attribute(fallthrough)
  3135. #define MA_FALLTHROUGH __attribute__((fallthrough))
  3136. #endif
  3137. #endif
  3138. #if !defined(MA_FALLTHROUGH)
  3139. #define MA_FALLTHROUGH ((void)0)
  3140. #endif
  3141. #ifdef _MSC_VER
  3142. #define MA_INLINE __forceinline
  3143. /* noinline was introduced in Visual Studio 2005. */
  3144. #if _MSC_VER >= 1400
  3145. #define MA_NO_INLINE __declspec(noinline)
  3146. #else
  3147. #define MA_NO_INLINE
  3148. #endif
  3149. #elif defined(__GNUC__)
  3150. /*
  3151. I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
  3152. the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
  3153. case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
  3154. command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
  3155. I am using "__inline__" only when we're compiling in strict ANSI mode.
  3156. */
  3157. #if defined(__STRICT_ANSI__)
  3158. #define MA_GNUC_INLINE_HINT __inline__
  3159. #else
  3160. #define MA_GNUC_INLINE_HINT inline
  3161. #endif
  3162. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  3163. #define MA_INLINE MA_GNUC_INLINE_HINT __attribute__((always_inline))
  3164. #define MA_NO_INLINE __attribute__((noinline))
  3165. #else
  3166. #define MA_INLINE MA_GNUC_INLINE_HINT
  3167. #define MA_NO_INLINE __attribute__((noinline))
  3168. #endif
  3169. #elif defined(__WATCOMC__)
  3170. #define MA_INLINE __inline
  3171. #define MA_NO_INLINE
  3172. #else
  3173. #define MA_INLINE
  3174. #define MA_NO_INLINE
  3175. #endif
  3176. /* MA_DLL is not officially supported. You're on your own if you want to use this. */
  3177. #if defined(MA_DLL)
  3178. #if defined(_WIN32)
  3179. #define MA_DLL_IMPORT __declspec(dllimport)
  3180. #define MA_DLL_EXPORT __declspec(dllexport)
  3181. #define MA_DLL_PRIVATE static
  3182. #else
  3183. #if defined(__GNUC__) && __GNUC__ >= 4
  3184. #define MA_DLL_IMPORT __attribute__((visibility("default")))
  3185. #define MA_DLL_EXPORT __attribute__((visibility("default")))
  3186. #define MA_DLL_PRIVATE __attribute__((visibility("hidden")))
  3187. #else
  3188. #define MA_DLL_IMPORT
  3189. #define MA_DLL_EXPORT
  3190. #define MA_DLL_PRIVATE static
  3191. #endif
  3192. #endif
  3193. #endif
  3194. #if !defined(MA_API)
  3195. #if defined(MA_DLL)
  3196. #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
  3197. #define MA_API MA_DLL_EXPORT
  3198. #else
  3199. #define MA_API MA_DLL_IMPORT
  3200. #endif
  3201. #else
  3202. #define MA_API extern
  3203. #endif
  3204. #endif
  3205. #if !defined(MA_STATIC)
  3206. #if defined(MA_DLL)
  3207. #define MA_PRIVATE MA_DLL_PRIVATE
  3208. #else
  3209. #define MA_PRIVATE static
  3210. #endif
  3211. #endif
  3212. /* SIMD alignment in bytes. Currently set to 32 bytes in preparation for future AVX optimizations. */
  3213. #define MA_SIMD_ALIGNMENT 32
  3214. /*
  3215. Special wchar_t type to ensure any structures in the public sections that reference it have a
  3216. consistent size across all platforms.
  3217. On Windows, wchar_t is 2 bytes, whereas everywhere else it's 4 bytes. Since Windows likes to use
  3218. wchar_t for it's IDs, we need a special explicitly sized wchar type that is always 2 bytes on all
  3219. platforms.
  3220. */
  3221. #if !defined(MA_POSIX) && defined(MA_WIN32)
  3222. typedef wchar_t ma_wchar_win32;
  3223. #else
  3224. typedef ma_uint16 ma_wchar_win32;
  3225. #endif
  3226. /*
  3227. Logging Levels
  3228. ==============
  3229. Log levels are only used to give logging callbacks some context as to the severity of a log message
  3230. so they can do filtering. All log levels will be posted to registered logging callbacks. If you
  3231. don't want to output a certain log level you can discriminate against the log level in the callback.
  3232. MA_LOG_LEVEL_DEBUG
  3233. Used for debugging. Useful for debug and test builds, but should be disabled in release builds.
  3234. MA_LOG_LEVEL_INFO
  3235. Informational logging. Useful for debugging. This will never be called from within the data
  3236. callback.
  3237. MA_LOG_LEVEL_WARNING
  3238. Warnings. You should enable this in you development builds and action them when encounted. These
  3239. logs usually indicate a potential problem or misconfiguration, but still allow you to keep
  3240. running. This will never be called from within the data callback.
  3241. MA_LOG_LEVEL_ERROR
  3242. Error logging. This will be fired when an operation fails and is subsequently aborted. This can
  3243. be fired from within the data callback, in which case the device will be stopped. You should
  3244. always have this log level enabled.
  3245. */
  3246. typedef enum
  3247. {
  3248. MA_LOG_LEVEL_DEBUG = 4,
  3249. MA_LOG_LEVEL_INFO = 3,
  3250. MA_LOG_LEVEL_WARNING = 2,
  3251. MA_LOG_LEVEL_ERROR = 1
  3252. } ma_log_level;
  3253. /*
  3254. Variables needing to be accessed atomically should be declared with this macro for two reasons:
  3255. 1) It allows people who read the code to identify a variable as such; and
  3256. 2) It forces alignment on platforms where it's required or optimal.
  3257. Note that for x86/64, alignment is not strictly necessary, but does have some performance
  3258. implications. Where supported by the compiler, alignment will be used, but otherwise if the CPU
  3259. architecture does not require it, it will simply leave it unaligned. This is the case with old
  3260. versions of Visual Studio, which I've confirmed with at least VC6.
  3261. */
  3262. #if !defined(_MSC_VER) && defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  3263. #include <stdalign.h>
  3264. #define MA_ATOMIC(alignment, type) _Alignas(alignment) type
  3265. #else
  3266. #if defined(__GNUC__)
  3267. /* GCC-style compilers. */
  3268. #define MA_ATOMIC(alignment, type) type __attribute__((aligned(alignment)))
  3269. #elif defined(_MSC_VER) && _MSC_VER > 1200 /* 1200 = VC6. Alignment not supported, but not necessary because x86 is the only supported target. */
  3270. /* MSVC. */
  3271. #define MA_ATOMIC(alignment, type) __declspec(align(alignment)) type
  3272. #else
  3273. /* Other compilers. */
  3274. #define MA_ATOMIC(alignment, type) type
  3275. #endif
  3276. #endif
  3277. typedef struct ma_context ma_context;
  3278. typedef struct ma_device ma_device;
  3279. typedef ma_uint8 ma_channel;
  3280. typedef enum
  3281. {
  3282. MA_CHANNEL_NONE = 0,
  3283. MA_CHANNEL_MONO = 1,
  3284. MA_CHANNEL_FRONT_LEFT = 2,
  3285. MA_CHANNEL_FRONT_RIGHT = 3,
  3286. MA_CHANNEL_FRONT_CENTER = 4,
  3287. MA_CHANNEL_LFE = 5,
  3288. MA_CHANNEL_BACK_LEFT = 6,
  3289. MA_CHANNEL_BACK_RIGHT = 7,
  3290. MA_CHANNEL_FRONT_LEFT_CENTER = 8,
  3291. MA_CHANNEL_FRONT_RIGHT_CENTER = 9,
  3292. MA_CHANNEL_BACK_CENTER = 10,
  3293. MA_CHANNEL_SIDE_LEFT = 11,
  3294. MA_CHANNEL_SIDE_RIGHT = 12,
  3295. MA_CHANNEL_TOP_CENTER = 13,
  3296. MA_CHANNEL_TOP_FRONT_LEFT = 14,
  3297. MA_CHANNEL_TOP_FRONT_CENTER = 15,
  3298. MA_CHANNEL_TOP_FRONT_RIGHT = 16,
  3299. MA_CHANNEL_TOP_BACK_LEFT = 17,
  3300. MA_CHANNEL_TOP_BACK_CENTER = 18,
  3301. MA_CHANNEL_TOP_BACK_RIGHT = 19,
  3302. MA_CHANNEL_AUX_0 = 20,
  3303. MA_CHANNEL_AUX_1 = 21,
  3304. MA_CHANNEL_AUX_2 = 22,
  3305. MA_CHANNEL_AUX_3 = 23,
  3306. MA_CHANNEL_AUX_4 = 24,
  3307. MA_CHANNEL_AUX_5 = 25,
  3308. MA_CHANNEL_AUX_6 = 26,
  3309. MA_CHANNEL_AUX_7 = 27,
  3310. MA_CHANNEL_AUX_8 = 28,
  3311. MA_CHANNEL_AUX_9 = 29,
  3312. MA_CHANNEL_AUX_10 = 30,
  3313. MA_CHANNEL_AUX_11 = 31,
  3314. MA_CHANNEL_AUX_12 = 32,
  3315. MA_CHANNEL_AUX_13 = 33,
  3316. MA_CHANNEL_AUX_14 = 34,
  3317. MA_CHANNEL_AUX_15 = 35,
  3318. MA_CHANNEL_AUX_16 = 36,
  3319. MA_CHANNEL_AUX_17 = 37,
  3320. MA_CHANNEL_AUX_18 = 38,
  3321. MA_CHANNEL_AUX_19 = 39,
  3322. MA_CHANNEL_AUX_20 = 40,
  3323. MA_CHANNEL_AUX_21 = 41,
  3324. MA_CHANNEL_AUX_22 = 42,
  3325. MA_CHANNEL_AUX_23 = 43,
  3326. MA_CHANNEL_AUX_24 = 44,
  3327. MA_CHANNEL_AUX_25 = 45,
  3328. MA_CHANNEL_AUX_26 = 46,
  3329. MA_CHANNEL_AUX_27 = 47,
  3330. MA_CHANNEL_AUX_28 = 48,
  3331. MA_CHANNEL_AUX_29 = 49,
  3332. MA_CHANNEL_AUX_30 = 50,
  3333. MA_CHANNEL_AUX_31 = 51,
  3334. MA_CHANNEL_LEFT = MA_CHANNEL_FRONT_LEFT,
  3335. MA_CHANNEL_RIGHT = MA_CHANNEL_FRONT_RIGHT,
  3336. MA_CHANNEL_POSITION_COUNT = (MA_CHANNEL_AUX_31 + 1)
  3337. } _ma_channel_position; /* Do not use `_ma_channel_position` directly. Use `ma_channel` instead. */
  3338. typedef enum
  3339. {
  3340. MA_SUCCESS = 0,
  3341. MA_ERROR = -1, /* A generic error. */
  3342. MA_INVALID_ARGS = -2,
  3343. MA_INVALID_OPERATION = -3,
  3344. MA_OUT_OF_MEMORY = -4,
  3345. MA_OUT_OF_RANGE = -5,
  3346. MA_ACCESS_DENIED = -6,
  3347. MA_DOES_NOT_EXIST = -7,
  3348. MA_ALREADY_EXISTS = -8,
  3349. MA_TOO_MANY_OPEN_FILES = -9,
  3350. MA_INVALID_FILE = -10,
  3351. MA_TOO_BIG = -11,
  3352. MA_PATH_TOO_LONG = -12,
  3353. MA_NAME_TOO_LONG = -13,
  3354. MA_NOT_DIRECTORY = -14,
  3355. MA_IS_DIRECTORY = -15,
  3356. MA_DIRECTORY_NOT_EMPTY = -16,
  3357. MA_AT_END = -17,
  3358. MA_NO_SPACE = -18,
  3359. MA_BUSY = -19,
  3360. MA_IO_ERROR = -20,
  3361. MA_INTERRUPT = -21,
  3362. MA_UNAVAILABLE = -22,
  3363. MA_ALREADY_IN_USE = -23,
  3364. MA_BAD_ADDRESS = -24,
  3365. MA_BAD_SEEK = -25,
  3366. MA_BAD_PIPE = -26,
  3367. MA_DEADLOCK = -27,
  3368. MA_TOO_MANY_LINKS = -28,
  3369. MA_NOT_IMPLEMENTED = -29,
  3370. MA_NO_MESSAGE = -30,
  3371. MA_BAD_MESSAGE = -31,
  3372. MA_NO_DATA_AVAILABLE = -32,
  3373. MA_INVALID_DATA = -33,
  3374. MA_TIMEOUT = -34,
  3375. MA_NO_NETWORK = -35,
  3376. MA_NOT_UNIQUE = -36,
  3377. MA_NOT_SOCKET = -37,
  3378. MA_NO_ADDRESS = -38,
  3379. MA_BAD_PROTOCOL = -39,
  3380. MA_PROTOCOL_UNAVAILABLE = -40,
  3381. MA_PROTOCOL_NOT_SUPPORTED = -41,
  3382. MA_PROTOCOL_FAMILY_NOT_SUPPORTED = -42,
  3383. MA_ADDRESS_FAMILY_NOT_SUPPORTED = -43,
  3384. MA_SOCKET_NOT_SUPPORTED = -44,
  3385. MA_CONNECTION_RESET = -45,
  3386. MA_ALREADY_CONNECTED = -46,
  3387. MA_NOT_CONNECTED = -47,
  3388. MA_CONNECTION_REFUSED = -48,
  3389. MA_NO_HOST = -49,
  3390. MA_IN_PROGRESS = -50,
  3391. MA_CANCELLED = -51,
  3392. MA_MEMORY_ALREADY_MAPPED = -52,
  3393. /* General non-standard errors. */
  3394. MA_CRC_MISMATCH = -100,
  3395. /* General miniaudio-specific errors. */
  3396. MA_FORMAT_NOT_SUPPORTED = -200,
  3397. MA_DEVICE_TYPE_NOT_SUPPORTED = -201,
  3398. MA_SHARE_MODE_NOT_SUPPORTED = -202,
  3399. MA_NO_BACKEND = -203,
  3400. MA_NO_DEVICE = -204,
  3401. MA_API_NOT_FOUND = -205,
  3402. MA_INVALID_DEVICE_CONFIG = -206,
  3403. MA_LOOP = -207,
  3404. MA_BACKEND_NOT_ENABLED = -208,
  3405. /* State errors. */
  3406. MA_DEVICE_NOT_INITIALIZED = -300,
  3407. MA_DEVICE_ALREADY_INITIALIZED = -301,
  3408. MA_DEVICE_NOT_STARTED = -302,
  3409. MA_DEVICE_NOT_STOPPED = -303,
  3410. /* Operation errors. */
  3411. MA_FAILED_TO_INIT_BACKEND = -400,
  3412. MA_FAILED_TO_OPEN_BACKEND_DEVICE = -401,
  3413. MA_FAILED_TO_START_BACKEND_DEVICE = -402,
  3414. MA_FAILED_TO_STOP_BACKEND_DEVICE = -403
  3415. } ma_result;
  3416. #define MA_MIN_CHANNELS 1
  3417. #ifndef MA_MAX_CHANNELS
  3418. #define MA_MAX_CHANNELS 254
  3419. #endif
  3420. #ifndef MA_MAX_FILTER_ORDER
  3421. #define MA_MAX_FILTER_ORDER 8
  3422. #endif
  3423. typedef enum
  3424. {
  3425. ma_stream_format_pcm = 0
  3426. } ma_stream_format;
  3427. typedef enum
  3428. {
  3429. ma_stream_layout_interleaved = 0,
  3430. ma_stream_layout_deinterleaved
  3431. } ma_stream_layout;
  3432. typedef enum
  3433. {
  3434. ma_dither_mode_none = 0,
  3435. ma_dither_mode_rectangle,
  3436. ma_dither_mode_triangle
  3437. } ma_dither_mode;
  3438. typedef enum
  3439. {
  3440. /*
  3441. I like to keep these explicitly defined because they're used as a key into a lookup table. When items are
  3442. added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample().
  3443. */
  3444. ma_format_unknown = 0, /* Mainly used for indicating an error, but also used as the default for the output format for decoders. */
  3445. ma_format_u8 = 1,
  3446. ma_format_s16 = 2, /* Seems to be the most widely supported format. */
  3447. ma_format_s24 = 3, /* Tightly packed. 3 bytes per sample. */
  3448. ma_format_s32 = 4,
  3449. ma_format_f32 = 5,
  3450. ma_format_count
  3451. } ma_format;
  3452. typedef enum
  3453. {
  3454. /* Standard rates need to be in priority order. */
  3455. ma_standard_sample_rate_48000 = 48000, /* Most common */
  3456. ma_standard_sample_rate_44100 = 44100,
  3457. ma_standard_sample_rate_32000 = 32000, /* Lows */
  3458. ma_standard_sample_rate_24000 = 24000,
  3459. ma_standard_sample_rate_22050 = 22050,
  3460. ma_standard_sample_rate_88200 = 88200, /* Highs */
  3461. ma_standard_sample_rate_96000 = 96000,
  3462. ma_standard_sample_rate_176400 = 176400,
  3463. ma_standard_sample_rate_192000 = 192000,
  3464. ma_standard_sample_rate_16000 = 16000, /* Extreme lows */
  3465. ma_standard_sample_rate_11025 = 11025,
  3466. ma_standard_sample_rate_8000 = 8000,
  3467. ma_standard_sample_rate_352800 = 352800, /* Extreme highs */
  3468. ma_standard_sample_rate_384000 = 384000,
  3469. ma_standard_sample_rate_min = ma_standard_sample_rate_8000,
  3470. ma_standard_sample_rate_max = ma_standard_sample_rate_384000,
  3471. ma_standard_sample_rate_count = 14 /* Need to maintain the count manually. Make sure this is updated if items are added to enum. */
  3472. } ma_standard_sample_rate;
  3473. typedef enum
  3474. {
  3475. ma_channel_mix_mode_rectangular = 0, /* Simple averaging based on the plane(s) the channel is sitting on. */
  3476. ma_channel_mix_mode_simple, /* Drop excess channels; zeroed out extra channels. */
  3477. ma_channel_mix_mode_custom_weights, /* Use custom weights specified in ma_channel_converter_config. */
  3478. ma_channel_mix_mode_default = ma_channel_mix_mode_rectangular
  3479. } ma_channel_mix_mode;
  3480. typedef enum
  3481. {
  3482. ma_standard_channel_map_microsoft,
  3483. ma_standard_channel_map_alsa,
  3484. ma_standard_channel_map_rfc3551, /* Based off AIFF. */
  3485. ma_standard_channel_map_flac,
  3486. ma_standard_channel_map_vorbis,
  3487. ma_standard_channel_map_sound4, /* FreeBSD's sound(4). */
  3488. ma_standard_channel_map_sndio, /* www.sndio.org/tips.html */
  3489. 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. */
  3490. ma_standard_channel_map_default = ma_standard_channel_map_microsoft
  3491. } ma_standard_channel_map;
  3492. typedef enum
  3493. {
  3494. ma_performance_profile_low_latency = 0,
  3495. ma_performance_profile_conservative
  3496. } ma_performance_profile;
  3497. typedef struct
  3498. {
  3499. void* pUserData;
  3500. void* (* onMalloc)(size_t sz, void* pUserData);
  3501. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  3502. void (* onFree)(void* p, void* pUserData);
  3503. } ma_allocation_callbacks;
  3504. typedef struct
  3505. {
  3506. ma_int32 state;
  3507. } ma_lcg;
  3508. /*
  3509. Atomics.
  3510. These are typesafe structures to prevent errors as a result of forgetting to reference variables atomically. It's too
  3511. easy to introduce subtle bugs where you accidentally do a regular assignment instead of an atomic load/store, etc. By
  3512. using a struct we can enforce the use of atomics at compile time.
  3513. These types are declared in the header section because we need to reference them in structs below, but functions for
  3514. using them are only exposed in the implementation section. I do not want these to be part of the public API.
  3515. There's a few downsides to this system. The first is that you need to declare a new struct for each type. Below are
  3516. some macros to help with the declarations. They will be named like so:
  3517. ma_atomic_uint32 - atomic ma_uint32
  3518. ma_atomic_int32 - atomic ma_int32
  3519. ma_atomic_uint64 - atomic ma_uint64
  3520. ma_atomic_float - atomic float
  3521. ma_atomic_bool32 - atomic ma_bool32
  3522. The other downside is that atomic pointers are extremely messy. You need to declare a new struct for each specific
  3523. type of pointer you need to make atomic. For example, an atomic ma_node* will look like this:
  3524. MA_ATOMIC_SAFE_TYPE_IMPL_PTR(node)
  3525. Which will declare a type struct that's named like so:
  3526. ma_atomic_ptr_node
  3527. Functions to use the atomic types are declared in the implementation section. All atomic functions are prefixed with
  3528. the name of the struct. For example:
  3529. ma_atomic_uint32_set() - Atomic store of ma_uint32
  3530. ma_atomic_uint32_get() - Atomic load of ma_uint32
  3531. etc.
  3532. 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
  3533. return you get type safety and enforcement of atomic operations.
  3534. */
  3535. #define MA_ATOMIC_SAFE_TYPE_DECL(c89TypeExtension, typeSize, type) \
  3536. typedef struct \
  3537. { \
  3538. MA_ATOMIC(typeSize, ma_##type) value; \
  3539. } ma_atomic_##type; \
  3540. #define MA_ATOMIC_SAFE_TYPE_DECL_PTR(type) \
  3541. typedef struct \
  3542. { \
  3543. MA_ATOMIC(MA_SIZEOF_PTR, ma_##type*) value; \
  3544. } ma_atomic_ptr_##type; \
  3545. MA_ATOMIC_SAFE_TYPE_DECL(32, 4, uint32)
  3546. MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, int32)
  3547. MA_ATOMIC_SAFE_TYPE_DECL(64, 8, uint64)
  3548. MA_ATOMIC_SAFE_TYPE_DECL(f32, 4, float)
  3549. MA_ATOMIC_SAFE_TYPE_DECL(32, 4, bool32)
  3550. /* Spinlocks are 32-bit for compatibility reasons. */
  3551. typedef ma_uint32 ma_spinlock;
  3552. #ifndef MA_NO_THREADING
  3553. /* Thread priorities should be ordered such that the default priority of the worker thread is 0. */
  3554. typedef enum
  3555. {
  3556. ma_thread_priority_idle = -5,
  3557. ma_thread_priority_lowest = -4,
  3558. ma_thread_priority_low = -3,
  3559. ma_thread_priority_normal = -2,
  3560. ma_thread_priority_high = -1,
  3561. ma_thread_priority_highest = 0,
  3562. ma_thread_priority_realtime = 1,
  3563. ma_thread_priority_default = 0
  3564. } ma_thread_priority;
  3565. #if defined(MA_POSIX)
  3566. typedef ma_pthread_t ma_thread;
  3567. #elif defined(MA_WIN32)
  3568. typedef ma_handle ma_thread;
  3569. #endif
  3570. #if defined(MA_POSIX)
  3571. typedef ma_pthread_mutex_t ma_mutex;
  3572. #elif defined(MA_WIN32)
  3573. typedef ma_handle ma_mutex;
  3574. #endif
  3575. #if defined(MA_POSIX)
  3576. typedef struct
  3577. {
  3578. ma_uint32 value;
  3579. ma_pthread_mutex_t lock;
  3580. ma_pthread_cond_t cond;
  3581. } ma_event;
  3582. #elif defined(MA_WIN32)
  3583. typedef ma_handle ma_event;
  3584. #endif
  3585. #if defined(MA_POSIX)
  3586. typedef struct
  3587. {
  3588. int value;
  3589. ma_pthread_mutex_t lock;
  3590. ma_pthread_cond_t cond;
  3591. } ma_semaphore;
  3592. #elif defined(MA_WIN32)
  3593. typedef ma_handle ma_semaphore;
  3594. #endif
  3595. #else
  3596. /* 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. */
  3597. #ifndef MA_NO_DEVICE_IO
  3598. #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
  3599. #endif
  3600. #endif /* MA_NO_THREADING */
  3601. /*
  3602. Retrieves the version of miniaudio as separated integers. Each component can be NULL if it's not required.
  3603. */
  3604. MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
  3605. /*
  3606. Retrieves the version of miniaudio as a string which can be useful for logging purposes.
  3607. */
  3608. MA_API const char* ma_version_string(void);
  3609. /**************************************************************************************************************************************************************
  3610. Logging
  3611. **************************************************************************************************************************************************************/
  3612. #include <stdarg.h> /* For va_list. */
  3613. #if defined(__has_attribute)
  3614. #if __has_attribute(format)
  3615. #define MA_ATTRIBUTE_FORMAT(fmt, va) __attribute__((format(printf, fmt, va)))
  3616. #endif
  3617. #endif
  3618. #ifndef MA_ATTRIBUTE_FORMAT
  3619. #define MA_ATTRIBUTE_FORMAT(fmt, va)
  3620. #endif
  3621. #ifndef MA_MAX_LOG_CALLBACKS
  3622. #define MA_MAX_LOG_CALLBACKS 4
  3623. #endif
  3624. /*
  3625. The callback for handling log messages.
  3626. Parameters
  3627. ----------
  3628. pUserData (in)
  3629. The user data pointer that was passed into ma_log_register_callback().
  3630. logLevel (in)
  3631. The log level. This can be one of the following:
  3632. +----------------------+
  3633. | Log Level |
  3634. +----------------------+
  3635. | MA_LOG_LEVEL_DEBUG |
  3636. | MA_LOG_LEVEL_INFO |
  3637. | MA_LOG_LEVEL_WARNING |
  3638. | MA_LOG_LEVEL_ERROR |
  3639. +----------------------+
  3640. pMessage (in)
  3641. The log message.
  3642. */
  3643. typedef void (* ma_log_callback_proc)(void* pUserData, ma_uint32 level, const char* pMessage);
  3644. typedef struct
  3645. {
  3646. ma_log_callback_proc onLog;
  3647. void* pUserData;
  3648. } ma_log_callback;
  3649. MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData);
  3650. typedef struct
  3651. {
  3652. ma_log_callback callbacks[MA_MAX_LOG_CALLBACKS];
  3653. ma_uint32 callbackCount;
  3654. ma_allocation_callbacks allocationCallbacks; /* Need to store these persistently because ma_log_postv() might need to allocate a buffer on the heap. */
  3655. #ifndef MA_NO_THREADING
  3656. ma_mutex lock; /* For thread safety just to make it easier and safer for the logging implementation. */
  3657. #endif
  3658. } ma_log;
  3659. MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog);
  3660. MA_API void ma_log_uninit(ma_log* pLog);
  3661. MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback);
  3662. MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback);
  3663. MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage);
  3664. MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args);
  3665. MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...) MA_ATTRIBUTE_FORMAT(3, 4);
  3666. /**************************************************************************************************************************************************************
  3667. Biquad Filtering
  3668. **************************************************************************************************************************************************************/
  3669. typedef union
  3670. {
  3671. float f32;
  3672. ma_int32 s32;
  3673. } ma_biquad_coefficient;
  3674. typedef struct
  3675. {
  3676. ma_format format;
  3677. ma_uint32 channels;
  3678. double b0;
  3679. double b1;
  3680. double b2;
  3681. double a0;
  3682. double a1;
  3683. double a2;
  3684. } ma_biquad_config;
  3685. 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);
  3686. typedef struct
  3687. {
  3688. ma_format format;
  3689. ma_uint32 channels;
  3690. ma_biquad_coefficient b0;
  3691. ma_biquad_coefficient b1;
  3692. ma_biquad_coefficient b2;
  3693. ma_biquad_coefficient a1;
  3694. ma_biquad_coefficient a2;
  3695. ma_biquad_coefficient* pR1;
  3696. ma_biquad_coefficient* pR2;
  3697. /* Memory management. */
  3698. void* _pHeap;
  3699. ma_bool32 _ownsHeap;
  3700. } ma_biquad;
  3701. MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes);
  3702. MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ);
  3703. MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ);
  3704. MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks);
  3705. MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ);
  3706. MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ);
  3707. MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3708. MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ);
  3709. /**************************************************************************************************************************************************************
  3710. Low-Pass Filtering
  3711. **************************************************************************************************************************************************************/
  3712. typedef struct
  3713. {
  3714. ma_format format;
  3715. ma_uint32 channels;
  3716. ma_uint32 sampleRate;
  3717. double cutoffFrequency;
  3718. double q;
  3719. } ma_lpf1_config, ma_lpf2_config;
  3720. MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
  3721. MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3722. typedef struct
  3723. {
  3724. ma_format format;
  3725. ma_uint32 channels;
  3726. ma_biquad_coefficient a;
  3727. ma_biquad_coefficient* pR1;
  3728. /* Memory management. */
  3729. void* _pHeap;
  3730. ma_bool32 _ownsHeap;
  3731. } ma_lpf1;
  3732. MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes);
  3733. MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF);
  3734. MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF);
  3735. MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3736. MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF);
  3737. MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF);
  3738. MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3739. MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF);
  3740. typedef struct
  3741. {
  3742. ma_biquad bq; /* The second order low-pass filter is implemented as a biquad filter. */
  3743. } ma_lpf2;
  3744. MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3745. MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pHPF);
  3746. MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF);
  3747. MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3748. MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF);
  3749. MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF);
  3750. MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3751. MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF);
  3752. typedef struct
  3753. {
  3754. ma_format format;
  3755. ma_uint32 channels;
  3756. ma_uint32 sampleRate;
  3757. double cutoffFrequency;
  3758. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3759. } ma_lpf_config;
  3760. MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3761. typedef struct
  3762. {
  3763. ma_format format;
  3764. ma_uint32 channels;
  3765. ma_uint32 sampleRate;
  3766. ma_uint32 lpf1Count;
  3767. ma_uint32 lpf2Count;
  3768. ma_lpf1* pLPF1;
  3769. ma_lpf2* pLPF2;
  3770. /* Memory management. */
  3771. void* _pHeap;
  3772. ma_bool32 _ownsHeap;
  3773. } ma_lpf;
  3774. MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes);
  3775. MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF);
  3776. MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF);
  3777. MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3778. MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF);
  3779. MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF);
  3780. MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3781. MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF);
  3782. /**************************************************************************************************************************************************************
  3783. High-Pass Filtering
  3784. **************************************************************************************************************************************************************/
  3785. typedef struct
  3786. {
  3787. ma_format format;
  3788. ma_uint32 channels;
  3789. ma_uint32 sampleRate;
  3790. double cutoffFrequency;
  3791. double q;
  3792. } ma_hpf1_config, ma_hpf2_config;
  3793. MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
  3794. MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3795. typedef struct
  3796. {
  3797. ma_format format;
  3798. ma_uint32 channels;
  3799. ma_biquad_coefficient a;
  3800. ma_biquad_coefficient* pR1;
  3801. /* Memory management. */
  3802. void* _pHeap;
  3803. ma_bool32 _ownsHeap;
  3804. } ma_hpf1;
  3805. MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes);
  3806. MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF);
  3807. MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pHPF);
  3808. MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3809. MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF);
  3810. MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3811. MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF);
  3812. typedef struct
  3813. {
  3814. ma_biquad bq; /* The second order high-pass filter is implemented as a biquad filter. */
  3815. } ma_hpf2;
  3816. MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3817. MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF);
  3818. MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF);
  3819. MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3820. MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF);
  3821. MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3822. MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF);
  3823. typedef struct
  3824. {
  3825. ma_format format;
  3826. ma_uint32 channels;
  3827. ma_uint32 sampleRate;
  3828. double cutoffFrequency;
  3829. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3830. } ma_hpf_config;
  3831. MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3832. typedef struct
  3833. {
  3834. ma_format format;
  3835. ma_uint32 channels;
  3836. ma_uint32 sampleRate;
  3837. ma_uint32 hpf1Count;
  3838. ma_uint32 hpf2Count;
  3839. ma_hpf1* pHPF1;
  3840. ma_hpf2* pHPF2;
  3841. /* Memory management. */
  3842. void* _pHeap;
  3843. ma_bool32 _ownsHeap;
  3844. } ma_hpf;
  3845. MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes);
  3846. MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF);
  3847. MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF);
  3848. MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3849. MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF);
  3850. MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3851. MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF);
  3852. /**************************************************************************************************************************************************************
  3853. Band-Pass Filtering
  3854. **************************************************************************************************************************************************************/
  3855. typedef struct
  3856. {
  3857. ma_format format;
  3858. ma_uint32 channels;
  3859. ma_uint32 sampleRate;
  3860. double cutoffFrequency;
  3861. double q;
  3862. } ma_bpf2_config;
  3863. MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3864. typedef struct
  3865. {
  3866. ma_biquad bq; /* The second order band-pass filter is implemented as a biquad filter. */
  3867. } ma_bpf2;
  3868. MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3869. MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF);
  3870. MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF);
  3871. MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3872. MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF);
  3873. MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3874. MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF);
  3875. typedef struct
  3876. {
  3877. ma_format format;
  3878. ma_uint32 channels;
  3879. ma_uint32 sampleRate;
  3880. double cutoffFrequency;
  3881. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3882. } ma_bpf_config;
  3883. MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3884. typedef struct
  3885. {
  3886. ma_format format;
  3887. ma_uint32 channels;
  3888. ma_uint32 bpf2Count;
  3889. ma_bpf2* pBPF2;
  3890. /* Memory management. */
  3891. void* _pHeap;
  3892. ma_bool32 _ownsHeap;
  3893. } ma_bpf;
  3894. MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes);
  3895. MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF);
  3896. MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF);
  3897. MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3898. MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF);
  3899. MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3900. MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF);
  3901. /**************************************************************************************************************************************************************
  3902. Notching Filter
  3903. **************************************************************************************************************************************************************/
  3904. typedef struct
  3905. {
  3906. ma_format format;
  3907. ma_uint32 channels;
  3908. ma_uint32 sampleRate;
  3909. double q;
  3910. double frequency;
  3911. } ma_notch2_config, ma_notch_config;
  3912. MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
  3913. typedef struct
  3914. {
  3915. ma_biquad bq;
  3916. } ma_notch2;
  3917. MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes);
  3918. MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter);
  3919. MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter);
  3920. MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3921. MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter);
  3922. MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3923. MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter);
  3924. /**************************************************************************************************************************************************************
  3925. Peaking EQ Filter
  3926. **************************************************************************************************************************************************************/
  3927. typedef struct
  3928. {
  3929. ma_format format;
  3930. ma_uint32 channels;
  3931. ma_uint32 sampleRate;
  3932. double gainDB;
  3933. double q;
  3934. double frequency;
  3935. } ma_peak2_config, ma_peak_config;
  3936. MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  3937. typedef struct
  3938. {
  3939. ma_biquad bq;
  3940. } ma_peak2;
  3941. MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes);
  3942. MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter);
  3943. MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter);
  3944. MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3945. MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter);
  3946. MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3947. MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter);
  3948. /**************************************************************************************************************************************************************
  3949. Low Shelf Filter
  3950. **************************************************************************************************************************************************************/
  3951. typedef struct
  3952. {
  3953. ma_format format;
  3954. ma_uint32 channels;
  3955. ma_uint32 sampleRate;
  3956. double gainDB;
  3957. double shelfSlope;
  3958. double frequency;
  3959. } ma_loshelf2_config, ma_loshelf_config;
  3960. MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
  3961. typedef struct
  3962. {
  3963. ma_biquad bq;
  3964. } ma_loshelf2;
  3965. MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes);
  3966. MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter);
  3967. MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter);
  3968. MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3969. MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter);
  3970. MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3971. MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter);
  3972. /**************************************************************************************************************************************************************
  3973. High Shelf Filter
  3974. **************************************************************************************************************************************************************/
  3975. typedef struct
  3976. {
  3977. ma_format format;
  3978. ma_uint32 channels;
  3979. ma_uint32 sampleRate;
  3980. double gainDB;
  3981. double shelfSlope;
  3982. double frequency;
  3983. } ma_hishelf2_config, ma_hishelf_config;
  3984. MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
  3985. typedef struct
  3986. {
  3987. ma_biquad bq;
  3988. } ma_hishelf2;
  3989. MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes);
  3990. MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter);
  3991. MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter);
  3992. MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3993. MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter);
  3994. MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3995. MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter);
  3996. /*
  3997. Delay
  3998. */
  3999. typedef struct
  4000. {
  4001. ma_uint32 channels;
  4002. ma_uint32 sampleRate;
  4003. ma_uint32 delayInFrames;
  4004. ma_bool32 delayStart; /* Set to true to delay the start of the output; false otherwise. */
  4005. float wet; /* 0..1. Default = 1. */
  4006. float dry; /* 0..1. Default = 1. */
  4007. float decay; /* 0..1. Default = 0 (no feedback). Feedback decay. Use this for echo. */
  4008. } ma_delay_config;
  4009. MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
  4010. typedef struct
  4011. {
  4012. ma_delay_config config;
  4013. ma_uint32 cursor; /* Feedback is written to this cursor. Always equal or in front of the read cursor. */
  4014. ma_uint32 bufferSizeInFrames;
  4015. float* pBuffer;
  4016. } ma_delay;
  4017. MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay);
  4018. MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks);
  4019. MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount);
  4020. MA_API void ma_delay_set_wet(ma_delay* pDelay, float value);
  4021. MA_API float ma_delay_get_wet(const ma_delay* pDelay);
  4022. MA_API void ma_delay_set_dry(ma_delay* pDelay, float value);
  4023. MA_API float ma_delay_get_dry(const ma_delay* pDelay);
  4024. MA_API void ma_delay_set_decay(ma_delay* pDelay, float value);
  4025. MA_API float ma_delay_get_decay(const ma_delay* pDelay);
  4026. /* Gainer for smooth volume changes. */
  4027. typedef struct
  4028. {
  4029. ma_uint32 channels;
  4030. ma_uint32 smoothTimeInFrames;
  4031. } ma_gainer_config;
  4032. MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames);
  4033. typedef struct
  4034. {
  4035. ma_gainer_config config;
  4036. ma_uint32 t;
  4037. float masterVolume;
  4038. float* pOldGains;
  4039. float* pNewGains;
  4040. /* Memory management. */
  4041. void* _pHeap;
  4042. ma_bool32 _ownsHeap;
  4043. } ma_gainer;
  4044. MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes);
  4045. MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer);
  4046. MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer);
  4047. MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks);
  4048. MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4049. MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain);
  4050. MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains);
  4051. MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume);
  4052. MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume);
  4053. /* Stereo panner. */
  4054. typedef enum
  4055. {
  4056. 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. */
  4057. ma_pan_mode_pan /* A true pan. The sound from one side will "move" to the other side and blend with it. */
  4058. } ma_pan_mode;
  4059. typedef struct
  4060. {
  4061. ma_format format;
  4062. ma_uint32 channels;
  4063. ma_pan_mode mode;
  4064. float pan;
  4065. } ma_panner_config;
  4066. MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels);
  4067. typedef struct
  4068. {
  4069. ma_format format;
  4070. ma_uint32 channels;
  4071. ma_pan_mode mode;
  4072. float pan; /* -1..1 where 0 is no pan, -1 is left side, +1 is right side. Defaults to 0. */
  4073. } ma_panner;
  4074. MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner);
  4075. MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4076. MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode);
  4077. MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner);
  4078. MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan);
  4079. MA_API float ma_panner_get_pan(const ma_panner* pPanner);
  4080. /* Fader. */
  4081. typedef struct
  4082. {
  4083. ma_format format;
  4084. ma_uint32 channels;
  4085. ma_uint32 sampleRate;
  4086. } ma_fader_config;
  4087. MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  4088. typedef struct
  4089. {
  4090. ma_fader_config config;
  4091. float volumeBeg; /* If volumeBeg and volumeEnd is equal to 1, no fading happens (ma_fader_process_pcm_frames() will run as a passthrough). */
  4092. float volumeEnd;
  4093. ma_uint64 lengthInFrames; /* The total length of the fade. */
  4094. ma_int64 cursorInFrames; /* The current time in frames. Incremented by ma_fader_process_pcm_frames(). Signed because it'll be offset by startOffsetInFrames in set_fade_ex(). */
  4095. } ma_fader;
  4096. MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader);
  4097. MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4098. MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate);
  4099. MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames);
  4100. MA_API void ma_fader_set_fade_ex(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames, ma_int64 startOffsetInFrames);
  4101. MA_API float ma_fader_get_current_volume(const ma_fader* pFader);
  4102. /* Spatializer. */
  4103. typedef struct
  4104. {
  4105. float x;
  4106. float y;
  4107. float z;
  4108. } ma_vec3f;
  4109. typedef struct
  4110. {
  4111. ma_vec3f v;
  4112. ma_spinlock lock;
  4113. } ma_atomic_vec3f;
  4114. typedef enum
  4115. {
  4116. ma_attenuation_model_none, /* No distance attenuation and no spatialization. */
  4117. ma_attenuation_model_inverse, /* Equivalent to OpenAL's AL_INVERSE_DISTANCE_CLAMPED. */
  4118. ma_attenuation_model_linear, /* Linear attenuation. Equivalent to OpenAL's AL_LINEAR_DISTANCE_CLAMPED. */
  4119. ma_attenuation_model_exponential /* Exponential attenuation. Equivalent to OpenAL's AL_EXPONENT_DISTANCE_CLAMPED. */
  4120. } ma_attenuation_model;
  4121. typedef enum
  4122. {
  4123. ma_positioning_absolute,
  4124. ma_positioning_relative
  4125. } ma_positioning;
  4126. typedef enum
  4127. {
  4128. ma_handedness_right,
  4129. ma_handedness_left
  4130. } ma_handedness;
  4131. typedef struct
  4132. {
  4133. ma_uint32 channelsOut;
  4134. ma_channel* pChannelMapOut;
  4135. 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. */
  4136. float coneInnerAngleInRadians;
  4137. float coneOuterAngleInRadians;
  4138. float coneOuterGain;
  4139. float speedOfSound;
  4140. ma_vec3f worldUp;
  4141. } ma_spatializer_listener_config;
  4142. MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut);
  4143. typedef struct
  4144. {
  4145. ma_spatializer_listener_config config;
  4146. ma_atomic_vec3f position; /* The absolute position of the listener. */
  4147. ma_atomic_vec3f direction; /* The direction the listener is facing. The world up vector is config.worldUp. */
  4148. ma_atomic_vec3f velocity;
  4149. ma_bool32 isEnabled;
  4150. /* Memory management. */
  4151. ma_bool32 _ownsHeap;
  4152. void* _pHeap;
  4153. } ma_spatializer_listener;
  4154. MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes);
  4155. MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener);
  4156. MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener);
  4157. MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks);
  4158. MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener);
  4159. MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  4160. MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  4161. MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z);
  4162. MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener);
  4163. MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z);
  4164. MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener);
  4165. MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z);
  4166. MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener);
  4167. MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound);
  4168. MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener);
  4169. MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z);
  4170. MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener);
  4171. MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled);
  4172. MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener);
  4173. typedef struct
  4174. {
  4175. ma_uint32 channelsIn;
  4176. ma_uint32 channelsOut;
  4177. ma_channel* pChannelMapIn;
  4178. ma_attenuation_model attenuationModel;
  4179. ma_positioning positioning;
  4180. 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. */
  4181. float minGain;
  4182. float maxGain;
  4183. float minDistance;
  4184. float maxDistance;
  4185. float rolloff;
  4186. float coneInnerAngleInRadians;
  4187. float coneOuterAngleInRadians;
  4188. float coneOuterGain;
  4189. float dopplerFactor; /* Set to 0 to disable doppler effect. */
  4190. float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
  4191. 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. */
  4192. ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
  4193. } ma_spatializer_config;
  4194. MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut);
  4195. typedef struct
  4196. {
  4197. ma_uint32 channelsIn;
  4198. ma_uint32 channelsOut;
  4199. ma_channel* pChannelMapIn;
  4200. ma_attenuation_model attenuationModel;
  4201. ma_positioning positioning;
  4202. 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. */
  4203. float minGain;
  4204. float maxGain;
  4205. float minDistance;
  4206. float maxDistance;
  4207. float rolloff;
  4208. float coneInnerAngleInRadians;
  4209. float coneOuterAngleInRadians;
  4210. float coneOuterGain;
  4211. float dopplerFactor; /* Set to 0 to disable doppler effect. */
  4212. float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
  4213. ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
  4214. ma_atomic_vec3f position;
  4215. ma_atomic_vec3f direction;
  4216. ma_atomic_vec3f velocity; /* For doppler effect. */
  4217. 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. */
  4218. float minSpatializationChannelGain;
  4219. ma_gainer gainer; /* For smooth gain transitions. */
  4220. 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. */
  4221. /* Memory management. */
  4222. void* _pHeap;
  4223. ma_bool32 _ownsHeap;
  4224. } ma_spatializer;
  4225. MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes);
  4226. MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer);
  4227. MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer);
  4228. MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks);
  4229. MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4230. MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume);
  4231. MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume);
  4232. MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer);
  4233. MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer);
  4234. MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel);
  4235. MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer);
  4236. MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning);
  4237. MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer);
  4238. MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff);
  4239. MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer);
  4240. MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain);
  4241. MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer);
  4242. MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain);
  4243. MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer);
  4244. MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance);
  4245. MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer);
  4246. MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance);
  4247. MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer);
  4248. MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  4249. MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  4250. MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor);
  4251. MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer);
  4252. MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor);
  4253. MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer);
  4254. MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z);
  4255. MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer);
  4256. MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z);
  4257. MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer);
  4258. MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z);
  4259. MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer);
  4260. 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);
  4261. /************************************************************************************************************************************************************
  4262. *************************************************************************************************************************************************************
  4263. DATA CONVERSION
  4264. ===============
  4265. This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc.
  4266. *************************************************************************************************************************************************************
  4267. ************************************************************************************************************************************************************/
  4268. /**************************************************************************************************************************************************************
  4269. Resampling
  4270. **************************************************************************************************************************************************************/
  4271. typedef struct
  4272. {
  4273. ma_format format;
  4274. ma_uint32 channels;
  4275. ma_uint32 sampleRateIn;
  4276. ma_uint32 sampleRateOut;
  4277. ma_uint32 lpfOrder; /* The low-pass filter order. Setting this to 0 will disable low-pass filtering. */
  4278. double lpfNyquistFactor; /* 0..1. Defaults to 1. 1 = Half the sampling frequency (Nyquist Frequency), 0.5 = Quarter the sampling frequency (half Nyquest Frequency), etc. */
  4279. } ma_linear_resampler_config;
  4280. MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4281. typedef struct
  4282. {
  4283. ma_linear_resampler_config config;
  4284. ma_uint32 inAdvanceInt;
  4285. ma_uint32 inAdvanceFrac;
  4286. ma_uint32 inTimeInt;
  4287. ma_uint32 inTimeFrac;
  4288. union
  4289. {
  4290. float* f32;
  4291. ma_int16* s16;
  4292. } x0; /* The previous input frame. */
  4293. union
  4294. {
  4295. float* f32;
  4296. ma_int16* s16;
  4297. } x1; /* The next input frame. */
  4298. ma_lpf lpf;
  4299. /* Memory management. */
  4300. void* _pHeap;
  4301. ma_bool32 _ownsHeap;
  4302. } ma_linear_resampler;
  4303. MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4304. MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler);
  4305. MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler);
  4306. MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
  4307. 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);
  4308. MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4309. MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut);
  4310. MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler);
  4311. MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler);
  4312. MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4313. MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4314. MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler);
  4315. typedef struct ma_resampler_config ma_resampler_config;
  4316. typedef void ma_resampling_backend;
  4317. typedef struct
  4318. {
  4319. ma_result (* onGetHeapSize )(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4320. ma_result (* onInit )(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend);
  4321. void (* onUninit )(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
  4322. ma_result (* onProcess )(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4323. ma_result (* onSetRate )(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); /* Optional. Rate changes will be disabled. */
  4324. ma_uint64 (* onGetInputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
  4325. ma_uint64 (* onGetOutputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
  4326. ma_result (* onGetRequiredInputFrameCount )(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); /* Optional. Latency mitigation will be disabled. */
  4327. ma_result (* onGetExpectedOutputFrameCount)(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); /* Optional. Latency mitigation will be disabled. */
  4328. ma_result (* onReset )(void* pUserData, ma_resampling_backend* pBackend);
  4329. } ma_resampling_backend_vtable;
  4330. typedef enum
  4331. {
  4332. ma_resample_algorithm_linear = 0, /* Fastest, lowest quality. Optional low-pass filtering. Default. */
  4333. ma_resample_algorithm_custom,
  4334. } ma_resample_algorithm;
  4335. struct ma_resampler_config
  4336. {
  4337. ma_format format; /* Must be either ma_format_f32 or ma_format_s16. */
  4338. ma_uint32 channels;
  4339. ma_uint32 sampleRateIn;
  4340. ma_uint32 sampleRateOut;
  4341. ma_resample_algorithm algorithm; /* When set to ma_resample_algorithm_custom, pBackendVTable will be used. */
  4342. ma_resampling_backend_vtable* pBackendVTable;
  4343. void* pBackendUserData;
  4344. struct
  4345. {
  4346. ma_uint32 lpfOrder;
  4347. } linear;
  4348. };
  4349. 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);
  4350. typedef struct
  4351. {
  4352. ma_resampling_backend* pBackend;
  4353. ma_resampling_backend_vtable* pBackendVTable;
  4354. void* pBackendUserData;
  4355. ma_format format;
  4356. ma_uint32 channels;
  4357. ma_uint32 sampleRateIn;
  4358. ma_uint32 sampleRateOut;
  4359. union
  4360. {
  4361. ma_linear_resampler linear;
  4362. } state; /* State for stock resamplers so we can avoid a malloc. For stock resamplers, pBackend will point here. */
  4363. /* Memory management. */
  4364. void* _pHeap;
  4365. ma_bool32 _ownsHeap;
  4366. } ma_resampler;
  4367. MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4368. MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler);
  4369. /*
  4370. Initializes a new resampler object from a config.
  4371. */
  4372. MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler);
  4373. /*
  4374. Uninitializes a resampler.
  4375. */
  4376. MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
  4377. /*
  4378. Converts the given input data.
  4379. Both the input and output frames must be in the format specified in the config when the resampler was initialized.
  4380. On input, [pFrameCountOut] contains the number of output frames to process. On output it contains the number of output frames that
  4381. were actually processed, which may be less than the requested amount which will happen if there's not enough input data. You can use
  4382. ma_resampler_get_expected_output_frame_count() to know how many output frames will be processed for a given number of input frames.
  4383. On input, [pFrameCountIn] contains the number of input frames contained in [pFramesIn]. On output it contains the number of whole
  4384. input frames that were actually processed. You can use ma_resampler_get_required_input_frame_count() to know how many input frames
  4385. you should provide for a given number of output frames. [pFramesIn] can be NULL, in which case zeroes will be used instead.
  4386. If [pFramesOut] is NULL, a seek is performed. In this case, if [pFrameCountOut] is not NULL it will seek by the specified number of
  4387. output frames. Otherwise, if [pFramesCountOut] is NULL and [pFrameCountIn] is not NULL, it will seek by the specified number of input
  4388. frames. When seeking, [pFramesIn] is allowed to NULL, in which case the internal timing state will be updated, but no input will be
  4389. processed. In this case, any internal filter state will be updated as if zeroes were passed in.
  4390. It is an error for [pFramesOut] to be non-NULL and [pFrameCountOut] to be NULL.
  4391. It is an error for both [pFrameCountOut] and [pFrameCountIn] to be NULL.
  4392. */
  4393. MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4394. /*
  4395. Sets the input and output sample rate.
  4396. */
  4397. MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4398. /*
  4399. Sets the input and output sample rate as a ratio.
  4400. The ration is in/out.
  4401. */
  4402. MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio);
  4403. /*
  4404. Retrieves the latency introduced by the resampler in input frames.
  4405. */
  4406. MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler);
  4407. /*
  4408. Retrieves the latency introduced by the resampler in output frames.
  4409. */
  4410. MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler);
  4411. /*
  4412. Calculates the number of whole input frames that would need to be read from the client in order to output the specified
  4413. number of output frames.
  4414. The returned value does not include cached input frames. It only returns the number of extra frames that would need to be
  4415. read from the input buffer in order to output the specified number of output frames.
  4416. */
  4417. MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4418. /*
  4419. Calculates the number of whole output frames that would be output after fully reading and consuming the specified number of
  4420. input frames.
  4421. */
  4422. MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4423. /*
  4424. Resets the resampler's timer and clears it's internal cache.
  4425. */
  4426. MA_API ma_result ma_resampler_reset(ma_resampler* pResampler);
  4427. /**************************************************************************************************************************************************************
  4428. Channel Conversion
  4429. **************************************************************************************************************************************************************/
  4430. typedef enum
  4431. {
  4432. ma_channel_conversion_path_unknown,
  4433. ma_channel_conversion_path_passthrough,
  4434. ma_channel_conversion_path_mono_out, /* Converting to mono. */
  4435. ma_channel_conversion_path_mono_in, /* Converting from mono. */
  4436. 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. */
  4437. ma_channel_conversion_path_weights /* Blended based on weights. */
  4438. } ma_channel_conversion_path;
  4439. typedef enum
  4440. {
  4441. ma_mono_expansion_mode_duplicate = 0, /* The default. */
  4442. ma_mono_expansion_mode_average, /* Average the mono channel across all channels. */
  4443. ma_mono_expansion_mode_stereo_only, /* Duplicate to the left and right channels only and ignore the others. */
  4444. ma_mono_expansion_mode_default = ma_mono_expansion_mode_duplicate
  4445. } ma_mono_expansion_mode;
  4446. typedef struct
  4447. {
  4448. ma_format format;
  4449. ma_uint32 channelsIn;
  4450. ma_uint32 channelsOut;
  4451. const ma_channel* pChannelMapIn;
  4452. const ma_channel* pChannelMapOut;
  4453. ma_channel_mix_mode mixingMode;
  4454. 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. */
  4455. float** ppWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
  4456. } ma_channel_converter_config;
  4457. 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);
  4458. typedef struct
  4459. {
  4460. ma_format format;
  4461. ma_uint32 channelsIn;
  4462. ma_uint32 channelsOut;
  4463. ma_channel_mix_mode mixingMode;
  4464. ma_channel_conversion_path conversionPath;
  4465. ma_channel* pChannelMapIn;
  4466. ma_channel* pChannelMapOut;
  4467. ma_uint8* pShuffleTable; /* Indexed by output channel index. */
  4468. union
  4469. {
  4470. float** f32;
  4471. ma_int32** s16;
  4472. } weights; /* [in][out] */
  4473. /* Memory management. */
  4474. void* _pHeap;
  4475. ma_bool32 _ownsHeap;
  4476. } ma_channel_converter;
  4477. MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes);
  4478. MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter);
  4479. MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter);
  4480. MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
  4481. MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4482. MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4483. MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4484. /**************************************************************************************************************************************************************
  4485. Data Conversion
  4486. **************************************************************************************************************************************************************/
  4487. typedef struct
  4488. {
  4489. ma_format formatIn;
  4490. ma_format formatOut;
  4491. ma_uint32 channelsIn;
  4492. ma_uint32 channelsOut;
  4493. ma_uint32 sampleRateIn;
  4494. ma_uint32 sampleRateOut;
  4495. ma_channel* pChannelMapIn;
  4496. ma_channel* pChannelMapOut;
  4497. ma_dither_mode ditherMode;
  4498. ma_channel_mix_mode channelMixMode;
  4499. 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. */
  4500. float** ppChannelWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
  4501. ma_bool32 allowDynamicSampleRate;
  4502. ma_resampler_config resampling;
  4503. } ma_data_converter_config;
  4504. MA_API ma_data_converter_config ma_data_converter_config_init_default(void);
  4505. 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);
  4506. typedef enum
  4507. {
  4508. ma_data_converter_execution_path_passthrough, /* No conversion. */
  4509. ma_data_converter_execution_path_format_only, /* Only format conversion. */
  4510. ma_data_converter_execution_path_channels_only, /* Only channel conversion. */
  4511. ma_data_converter_execution_path_resample_only, /* Only resampling. */
  4512. ma_data_converter_execution_path_resample_first, /* All conversions, but resample as the first step. */
  4513. ma_data_converter_execution_path_channels_first /* All conversions, but channels as the first step. */
  4514. } ma_data_converter_execution_path;
  4515. typedef struct
  4516. {
  4517. ma_format formatIn;
  4518. ma_format formatOut;
  4519. ma_uint32 channelsIn;
  4520. ma_uint32 channelsOut;
  4521. ma_uint32 sampleRateIn;
  4522. ma_uint32 sampleRateOut;
  4523. ma_dither_mode ditherMode;
  4524. ma_data_converter_execution_path executionPath; /* The execution path the data converter will follow when processing. */
  4525. ma_channel_converter channelConverter;
  4526. ma_resampler resampler;
  4527. ma_bool8 hasPreFormatConversion;
  4528. ma_bool8 hasPostFormatConversion;
  4529. ma_bool8 hasChannelConverter;
  4530. ma_bool8 hasResampler;
  4531. ma_bool8 isPassthrough;
  4532. /* Memory management. */
  4533. ma_bool8 _ownsHeap;
  4534. void* _pHeap;
  4535. } ma_data_converter;
  4536. MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes);
  4537. MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter);
  4538. MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter);
  4539. MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
  4540. 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);
  4541. MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4542. MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut);
  4543. MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter);
  4544. MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter);
  4545. MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4546. MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4547. MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4548. MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4549. MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter);
  4550. /************************************************************************************************************************************************************
  4551. Format Conversion
  4552. ************************************************************************************************************************************************************/
  4553. MA_API void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4554. MA_API void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4555. MA_API void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4556. MA_API void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4557. MA_API void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4558. MA_API void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4559. MA_API void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4560. MA_API void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4561. MA_API void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4562. MA_API void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4563. MA_API void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4564. MA_API void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4565. MA_API void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4566. MA_API void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4567. MA_API void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4568. MA_API void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4569. MA_API void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4570. MA_API void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4571. MA_API void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4572. MA_API void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4573. MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode);
  4574. 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);
  4575. /*
  4576. Deinterleaves an interleaved buffer.
  4577. */
  4578. MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames);
  4579. /*
  4580. Interleaves a group of deinterleaved buffers.
  4581. */
  4582. MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames);
  4583. /************************************************************************************************************************************************************
  4584. Channel Maps
  4585. ************************************************************************************************************************************************************/
  4586. /*
  4587. This is used in the shuffle table to indicate that the channel index is undefined and should be ignored.
  4588. */
  4589. #define MA_CHANNEL_INDEX_NULL 255
  4590. /*
  4591. Retrieves the channel position of the specified channel in the given channel map.
  4592. The pChannelMap parameter can be null, in which case miniaudio's default channel map will be assumed.
  4593. */
  4594. MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
  4595. /*
  4596. Initializes a blank channel map.
  4597. When a blank channel map is specified anywhere it indicates that the native channel map should be used.
  4598. */
  4599. MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels);
  4600. /*
  4601. Helper for retrieving a standard channel map.
  4602. The output channel map buffer must have a capacity of at least `channelMapCap`.
  4603. */
  4604. MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels);
  4605. /*
  4606. Copies a channel map.
  4607. Both input and output channel map buffers must have a capacity of at at least `channels`.
  4608. */
  4609. MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels);
  4610. /*
  4611. Copies a channel map if one is specified, otherwise copies the default channel map.
  4612. 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`.
  4613. */
  4614. MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels);
  4615. /*
  4616. Determines whether or not a channel map is valid.
  4617. 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
  4618. is usually treated as a passthrough.
  4619. Invalid channel maps:
  4620. - A channel map with no channels
  4621. - A channel map with more than one channel and a mono channel
  4622. The channel map buffer must have a capacity of at least `channels`.
  4623. */
  4624. MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels);
  4625. /*
  4626. Helper for comparing two channel maps for equality.
  4627. This assumes the channel count is the same between the two.
  4628. Both channels map buffers must have a capacity of at least `channels`.
  4629. */
  4630. MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels);
  4631. /*
  4632. Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE).
  4633. The channel map buffer must have a capacity of at least `channels`.
  4634. */
  4635. MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels);
  4636. /*
  4637. Helper for determining whether or not a channel is present in the given channel map.
  4638. The channel map buffer must have a capacity of at least `channels`.
  4639. */
  4640. MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition);
  4641. /*
  4642. Find a channel position in the given channel map. Returns MA_TRUE if the channel is found; MA_FALSE otherwise. The
  4643. index of the channel is output to `pChannelIndex`.
  4644. The channel map buffer must have a capacity of at least `channels`.
  4645. */
  4646. MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex);
  4647. /*
  4648. Generates a string representing the given channel map.
  4649. This is for printing and debugging purposes, not serialization/deserialization.
  4650. Returns the length of the string, not including the null terminator.
  4651. */
  4652. MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap);
  4653. /*
  4654. Retrieves a human readable version of a channel position.
  4655. */
  4656. MA_API const char* ma_channel_position_to_string(ma_channel channel);
  4657. /************************************************************************************************************************************************************
  4658. Conversion Helpers
  4659. ************************************************************************************************************************************************************/
  4660. /*
  4661. 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
  4662. determine the required size of the output buffer. frameCountOut should be set to the capacity of pOut. If pOut is NULL, frameCountOut is
  4663. ignored.
  4664. A return value of 0 indicates an error.
  4665. This function is useful for one-off bulk conversions, but if you're streaming data you should use the ma_data_converter APIs instead.
  4666. */
  4667. 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);
  4668. 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);
  4669. /************************************************************************************************************************************************************
  4670. Data Source
  4671. ************************************************************************************************************************************************************/
  4672. typedef void ma_data_source;
  4673. #define MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT 0x00000001
  4674. typedef struct
  4675. {
  4676. ma_result (* onRead)(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  4677. ma_result (* onSeek)(ma_data_source* pDataSource, ma_uint64 frameIndex);
  4678. ma_result (* onGetDataFormat)(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  4679. ma_result (* onGetCursor)(ma_data_source* pDataSource, ma_uint64* pCursor);
  4680. ma_result (* onGetLength)(ma_data_source* pDataSource, ma_uint64* pLength);
  4681. ma_result (* onSetLooping)(ma_data_source* pDataSource, ma_bool32 isLooping);
  4682. ma_uint32 flags;
  4683. } ma_data_source_vtable;
  4684. typedef ma_data_source* (* ma_data_source_get_next_proc)(ma_data_source* pDataSource);
  4685. typedef struct
  4686. {
  4687. const ma_data_source_vtable* vtable;
  4688. } ma_data_source_config;
  4689. MA_API ma_data_source_config ma_data_source_config_init(void);
  4690. typedef struct
  4691. {
  4692. const ma_data_source_vtable* vtable;
  4693. ma_uint64 rangeBegInFrames;
  4694. ma_uint64 rangeEndInFrames; /* Set to -1 for unranged (default). */
  4695. ma_uint64 loopBegInFrames; /* Relative to rangeBegInFrames. */
  4696. ma_uint64 loopEndInFrames; /* Relative to rangeBegInFrames. Set to -1 for the end of the range. */
  4697. 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. */
  4698. ma_data_source* pNext; /* When set to NULL, onGetNext will be used. */
  4699. ma_data_source_get_next_proc onGetNext; /* Will be used when pNext is NULL. If both are NULL, no next will be used. */
  4700. MA_ATOMIC(4, ma_bool32) isLooping;
  4701. } ma_data_source_base;
  4702. MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource);
  4703. MA_API void ma_data_source_uninit(ma_data_source* pDataSource);
  4704. 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. */
  4705. 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); */
  4706. MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex);
  4707. 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);
  4708. MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor);
  4709. 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. */
  4710. MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor);
  4711. MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength);
  4712. MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping);
  4713. MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource);
  4714. MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames);
  4715. MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames);
  4716. MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames);
  4717. MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames);
  4718. MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource);
  4719. MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource);
  4720. MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource);
  4721. MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource);
  4722. MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext);
  4723. MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource);
  4724. typedef struct
  4725. {
  4726. ma_data_source_base ds;
  4727. ma_format format;
  4728. ma_uint32 channels;
  4729. ma_uint32 sampleRate;
  4730. ma_uint64 cursor;
  4731. ma_uint64 sizeInFrames;
  4732. const void* pData;
  4733. } ma_audio_buffer_ref;
  4734. 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);
  4735. MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef);
  4736. MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames);
  4737. MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
  4738. MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex);
  4739. MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount);
  4740. 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. */
  4741. MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef);
  4742. MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor);
  4743. MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength);
  4744. MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames);
  4745. typedef struct
  4746. {
  4747. ma_format format;
  4748. ma_uint32 channels;
  4749. ma_uint32 sampleRate;
  4750. ma_uint64 sizeInFrames;
  4751. const void* pData; /* If set to NULL, will allocate a block of memory for you. */
  4752. ma_allocation_callbacks allocationCallbacks;
  4753. } ma_audio_buffer_config;
  4754. 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);
  4755. typedef struct
  4756. {
  4757. ma_audio_buffer_ref ref;
  4758. ma_allocation_callbacks allocationCallbacks;
  4759. 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(). */
  4760. ma_uint8 _pExtraData[1]; /* For allocating a buffer with the memory located directly after the other memory of the structure. */
  4761. } ma_audio_buffer;
  4762. MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
  4763. MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
  4764. 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. */
  4765. MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer);
  4766. MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer);
  4767. MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
  4768. MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex);
  4769. MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount);
  4770. 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. */
  4771. MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer);
  4772. MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor);
  4773. MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength);
  4774. MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames);
  4775. /*
  4776. Paged Audio Buffer
  4777. ==================
  4778. A paged audio buffer is made up of a linked list of pages. It's expandable, but not shrinkable. It
  4779. can be used for cases where audio data is streamed in asynchronously while allowing data to be read
  4780. at the same time.
  4781. This is lock-free, but not 100% thread safe. You can append a page and read from the buffer across
  4782. simultaneously across different threads, however only one thread at a time can append, and only one
  4783. thread at a time can read and seek.
  4784. */
  4785. typedef struct ma_paged_audio_buffer_page ma_paged_audio_buffer_page;
  4786. struct ma_paged_audio_buffer_page
  4787. {
  4788. MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pNext;
  4789. ma_uint64 sizeInFrames;
  4790. ma_uint8 pAudioData[1];
  4791. };
  4792. typedef struct
  4793. {
  4794. ma_format format;
  4795. ma_uint32 channels;
  4796. ma_paged_audio_buffer_page head; /* Dummy head for the lock-free algorithm. Always has a size of 0. */
  4797. MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pTail; /* Never null. Initially set to &head. */
  4798. } ma_paged_audio_buffer_data;
  4799. MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData);
  4800. MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks);
  4801. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData);
  4802. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData);
  4803. MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength);
  4804. 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);
  4805. 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);
  4806. MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage);
  4807. 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);
  4808. typedef struct
  4809. {
  4810. ma_paged_audio_buffer_data* pData; /* Must not be null. */
  4811. } ma_paged_audio_buffer_config;
  4812. MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData);
  4813. typedef struct
  4814. {
  4815. ma_data_source_base ds;
  4816. ma_paged_audio_buffer_data* pData; /* Audio data is read from here. Cannot be null. */
  4817. ma_paged_audio_buffer_page* pCurrent;
  4818. ma_uint64 relativeCursor; /* Relative to the current page. */
  4819. ma_uint64 absoluteCursor;
  4820. } ma_paged_audio_buffer;
  4821. MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer);
  4822. MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer);
  4823. 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. */
  4824. MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex);
  4825. MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor);
  4826. MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength);
  4827. /************************************************************************************************************************************************************
  4828. Ring Buffer
  4829. ************************************************************************************************************************************************************/
  4830. typedef struct
  4831. {
  4832. void* pBuffer;
  4833. ma_uint32 subbufferSizeInBytes;
  4834. ma_uint32 subbufferCount;
  4835. ma_uint32 subbufferStrideInBytes;
  4836. 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. */
  4837. 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. */
  4838. ma_bool8 ownsBuffer; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */
  4839. ma_bool8 clearOnWriteAcquire; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */
  4840. ma_allocation_callbacks allocationCallbacks;
  4841. } ma_rb;
  4842. 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);
  4843. MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
  4844. MA_API void ma_rb_uninit(ma_rb* pRB);
  4845. MA_API void ma_rb_reset(ma_rb* pRB);
  4846. MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
  4847. MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes);
  4848. MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
  4849. MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes);
  4850. MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes);
  4851. MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes);
  4852. 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. */
  4853. MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB);
  4854. MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB);
  4855. MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB);
  4856. MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB);
  4857. MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex);
  4858. MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer);
  4859. typedef struct
  4860. {
  4861. ma_data_source_base ds;
  4862. ma_rb rb;
  4863. ma_format format;
  4864. ma_uint32 channels;
  4865. ma_uint32 sampleRate; /* Not required for the ring buffer itself, but useful for associating the data with some sample rate, particularly for data sources. */
  4866. } ma_pcm_rb;
  4867. 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);
  4868. 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);
  4869. MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB);
  4870. MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB);
  4871. MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
  4872. MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
  4873. MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
  4874. MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
  4875. MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
  4876. MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
  4877. MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB); /* Return value is in frames. */
  4878. MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB);
  4879. MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB);
  4880. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB);
  4881. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB);
  4882. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex);
  4883. MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer);
  4884. MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB);
  4885. MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB);
  4886. MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB);
  4887. MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate);
  4888. /*
  4889. 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
  4890. capture device writes to it, and then a playback device reads from it.
  4891. At the moment this is just a simple naive implementation, but in the future I want to implement some dynamic resampling to seamlessly
  4892. handle desyncs. Note that the API is work in progress and may change at any time in any version.
  4893. 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
  4894. in frames. The internal sample rate of the capture device is also needed in order to calculate the size.
  4895. */
  4896. typedef struct
  4897. {
  4898. ma_pcm_rb rb;
  4899. } ma_duplex_rb;
  4900. 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);
  4901. MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB);
  4902. /************************************************************************************************************************************************************
  4903. Miscellaneous Helpers
  4904. ************************************************************************************************************************************************************/
  4905. /*
  4906. Retrieves a human readable description of the given result code.
  4907. */
  4908. MA_API const char* ma_result_description(ma_result result);
  4909. /*
  4910. malloc()
  4911. */
  4912. MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4913. /*
  4914. calloc()
  4915. */
  4916. MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4917. /*
  4918. realloc()
  4919. */
  4920. MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4921. /*
  4922. free()
  4923. */
  4924. MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  4925. /*
  4926. Performs an aligned malloc, with the assumption that the alignment is a power of 2.
  4927. */
  4928. MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks);
  4929. /*
  4930. Free's an aligned malloc'd buffer.
  4931. */
  4932. MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  4933. /*
  4934. Retrieves a friendly name for a format.
  4935. */
  4936. MA_API const char* ma_get_format_name(ma_format format);
  4937. /*
  4938. Blends two frames in floating point format.
  4939. */
  4940. MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels);
  4941. /*
  4942. Retrieves the size of a sample in bytes for the given format.
  4943. This API is efficient and is implemented using a lookup table.
  4944. Thread Safety: SAFE
  4945. This API is pure.
  4946. */
  4947. MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format);
  4948. static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; }
  4949. /*
  4950. Converts a log level to a string.
  4951. */
  4952. MA_API const char* ma_log_level_to_string(ma_uint32 logLevel);
  4953. /************************************************************************************************************************************************************
  4954. Synchronization
  4955. ************************************************************************************************************************************************************/
  4956. /*
  4957. Locks a spinlock.
  4958. */
  4959. MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock);
  4960. /*
  4961. Locks a spinlock, but does not yield() when looping.
  4962. */
  4963. MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock);
  4964. /*
  4965. Unlocks a spinlock.
  4966. */
  4967. MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock);
  4968. #ifndef MA_NO_THREADING
  4969. /*
  4970. Creates a mutex.
  4971. A mutex must be created from a valid context. A mutex is initially unlocked.
  4972. */
  4973. MA_API ma_result ma_mutex_init(ma_mutex* pMutex);
  4974. /*
  4975. Deletes a mutex.
  4976. */
  4977. MA_API void ma_mutex_uninit(ma_mutex* pMutex);
  4978. /*
  4979. Locks a mutex with an infinite timeout.
  4980. */
  4981. MA_API void ma_mutex_lock(ma_mutex* pMutex);
  4982. /*
  4983. Unlocks a mutex.
  4984. */
  4985. MA_API void ma_mutex_unlock(ma_mutex* pMutex);
  4986. /*
  4987. Initializes an auto-reset event.
  4988. */
  4989. MA_API ma_result ma_event_init(ma_event* pEvent);
  4990. /*
  4991. Uninitializes an auto-reset event.
  4992. */
  4993. MA_API void ma_event_uninit(ma_event* pEvent);
  4994. /*
  4995. Waits for the specified auto-reset event to become signalled.
  4996. */
  4997. MA_API ma_result ma_event_wait(ma_event* pEvent);
  4998. /*
  4999. Signals the specified auto-reset event.
  5000. */
  5001. MA_API ma_result ma_event_signal(ma_event* pEvent);
  5002. #endif /* MA_NO_THREADING */
  5003. /*
  5004. Fence
  5005. =====
  5006. This locks while the counter is larger than 0. Counter can be incremented and decremented by any
  5007. thread, but care needs to be taken when waiting. It is possible for one thread to acquire the
  5008. fence just as another thread returns from ma_fence_wait().
  5009. The idea behind a fence is to allow you to wait for a group of operations to complete. When an
  5010. operation starts, the counter is incremented which locks the fence. When the operation completes,
  5011. the fence will be released which decrements the counter. ma_fence_wait() will block until the
  5012. counter hits zero.
  5013. If threading is disabled, ma_fence_wait() will spin on the counter.
  5014. */
  5015. typedef struct
  5016. {
  5017. #ifndef MA_NO_THREADING
  5018. ma_event e;
  5019. #endif
  5020. ma_uint32 counter;
  5021. } ma_fence;
  5022. MA_API ma_result ma_fence_init(ma_fence* pFence);
  5023. MA_API void ma_fence_uninit(ma_fence* pFence);
  5024. MA_API ma_result ma_fence_acquire(ma_fence* pFence); /* Increment counter. */
  5025. MA_API ma_result ma_fence_release(ma_fence* pFence); /* Decrement counter. */
  5026. MA_API ma_result ma_fence_wait(ma_fence* pFence); /* Wait for counter to reach 0. */
  5027. /*
  5028. Notification callback for asynchronous operations.
  5029. */
  5030. typedef void ma_async_notification;
  5031. typedef struct
  5032. {
  5033. void (* onSignal)(ma_async_notification* pNotification);
  5034. } ma_async_notification_callbacks;
  5035. MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification);
  5036. /*
  5037. Simple polling notification.
  5038. This just sets a variable when the notification has been signalled which is then polled with ma_async_notification_poll_is_signalled()
  5039. */
  5040. typedef struct
  5041. {
  5042. ma_async_notification_callbacks cb;
  5043. ma_bool32 signalled;
  5044. } ma_async_notification_poll;
  5045. MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll);
  5046. MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll);
  5047. /*
  5048. Event Notification
  5049. This uses an ma_event. If threading is disabled (MA_NO_THREADING), initialization will fail.
  5050. */
  5051. typedef struct
  5052. {
  5053. ma_async_notification_callbacks cb;
  5054. #ifndef MA_NO_THREADING
  5055. ma_event e;
  5056. #endif
  5057. } ma_async_notification_event;
  5058. MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent);
  5059. MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent);
  5060. MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent);
  5061. MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent);
  5062. /************************************************************************************************************************************************************
  5063. Job Queue
  5064. ************************************************************************************************************************************************************/
  5065. /*
  5066. Slot Allocator
  5067. --------------
  5068. 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
  5069. as the insertion point for an object.
  5070. Slots are reference counted to help mitigate the ABA problem in the lock-free queue we use for tracking jobs.
  5071. The slot index is stored in the low 32 bits. The reference counter is stored in the high 32 bits:
  5072. +-----------------+-----------------+
  5073. | 32 Bits | 32 Bits |
  5074. +-----------------+-----------------+
  5075. | Reference Count | Slot Index |
  5076. +-----------------+-----------------+
  5077. */
  5078. typedef struct
  5079. {
  5080. ma_uint32 capacity; /* The number of slots to make available. */
  5081. } ma_slot_allocator_config;
  5082. MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity);
  5083. typedef struct
  5084. {
  5085. 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. */
  5086. } ma_slot_allocator_group;
  5087. typedef struct
  5088. {
  5089. ma_slot_allocator_group* pGroups; /* Slots are grouped in chunks of 32. */
  5090. ma_uint32* pSlots; /* 32 bits for reference counting for ABA mitigation. */
  5091. ma_uint32 count; /* Allocation count. */
  5092. ma_uint32 capacity;
  5093. /* Memory management. */
  5094. ma_bool32 _ownsHeap;
  5095. void* _pHeap;
  5096. } ma_slot_allocator;
  5097. MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes);
  5098. MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator);
  5099. MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator);
  5100. MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks);
  5101. MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot);
  5102. MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot);
  5103. typedef struct ma_job ma_job;
  5104. /*
  5105. Callback for processing a job. Each job type will have their own processing callback which will be
  5106. called by ma_job_process().
  5107. */
  5108. typedef ma_result (* ma_job_proc)(ma_job* pJob);
  5109. /* When a job type is added here an callback needs to be added go "g_jobVTable" in the implementation section. */
  5110. typedef enum
  5111. {
  5112. /* Miscellaneous. */
  5113. MA_JOB_TYPE_QUIT = 0,
  5114. MA_JOB_TYPE_CUSTOM,
  5115. /* Resource Manager. */
  5116. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE,
  5117. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE,
  5118. MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE,
  5119. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER,
  5120. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER,
  5121. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM,
  5122. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM,
  5123. MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM,
  5124. MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM,
  5125. /* Device. */
  5126. MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE,
  5127. /* Count. Must always be last. */
  5128. MA_JOB_TYPE_COUNT
  5129. } ma_job_type;
  5130. struct ma_job
  5131. {
  5132. union
  5133. {
  5134. struct
  5135. {
  5136. ma_uint16 code; /* Job type. */
  5137. ma_uint16 slot; /* Index into a ma_slot_allocator. */
  5138. ma_uint32 refcount;
  5139. } breakup;
  5140. ma_uint64 allocation;
  5141. } toc; /* 8 bytes. We encode the job code into the slot allocation data to save space. */
  5142. MA_ATOMIC(8, ma_uint64) next; /* refcount + slot for the next item. Does not include the job code. */
  5143. 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. */
  5144. union
  5145. {
  5146. /* Miscellaneous. */
  5147. struct
  5148. {
  5149. ma_job_proc proc;
  5150. ma_uintptr data0;
  5151. ma_uintptr data1;
  5152. } custom;
  5153. /* Resource Manager */
  5154. union
  5155. {
  5156. struct
  5157. {
  5158. /*ma_resource_manager**/ void* pResourceManager;
  5159. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  5160. char* pFilePath;
  5161. wchar_t* pFilePathW;
  5162. ma_uint32 flags; /* Resource manager data source flags that were used when initializing the data buffer. */
  5163. ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  5164. 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. */
  5165. ma_fence* pInitFence; /* Released when initialization of the decoder is complete. */
  5166. ma_fence* pDoneFence; /* Released if initialization of the decoder fails. Passed through to PAGE_DATA_BUFFER_NODE untouched if init is successful. */
  5167. } loadDataBufferNode;
  5168. struct
  5169. {
  5170. /*ma_resource_manager**/ void* pResourceManager;
  5171. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  5172. ma_async_notification* pDoneNotification;
  5173. ma_fence* pDoneFence;
  5174. } freeDataBufferNode;
  5175. struct
  5176. {
  5177. /*ma_resource_manager**/ void* pResourceManager;
  5178. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  5179. /*ma_decoder**/ void* pDecoder;
  5180. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
  5181. ma_fence* pDoneFence; /* Passed through from LOAD_DATA_BUFFER_NODE and released when the data buffer completes decoding or an error occurs. */
  5182. } pageDataBufferNode;
  5183. struct
  5184. {
  5185. /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
  5186. ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  5187. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
  5188. ma_fence* pInitFence; /* Released when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  5189. ma_fence* pDoneFence; /* Released when the data buffer has been fully decoded. */
  5190. ma_uint64 rangeBegInPCMFrames;
  5191. ma_uint64 rangeEndInPCMFrames;
  5192. ma_uint64 loopPointBegInPCMFrames;
  5193. ma_uint64 loopPointEndInPCMFrames;
  5194. ma_uint32 isLooping;
  5195. } loadDataBuffer;
  5196. struct
  5197. {
  5198. /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
  5199. ma_async_notification* pDoneNotification;
  5200. ma_fence* pDoneFence;
  5201. } freeDataBuffer;
  5202. struct
  5203. {
  5204. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5205. char* pFilePath; /* Allocated when the job is posted, freed by the job thread after loading. */
  5206. wchar_t* pFilePathW; /* ^ As above ^. Only used if pFilePath is NULL. */
  5207. ma_uint64 initialSeekPoint;
  5208. ma_async_notification* pInitNotification; /* Signalled after the first two pages have been decoded and frames can be read from the stream. */
  5209. ma_fence* pInitFence;
  5210. } loadDataStream;
  5211. struct
  5212. {
  5213. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5214. ma_async_notification* pDoneNotification;
  5215. ma_fence* pDoneFence;
  5216. } freeDataStream;
  5217. struct
  5218. {
  5219. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5220. ma_uint32 pageIndex; /* The index of the page to decode into. */
  5221. } pageDataStream;
  5222. struct
  5223. {
  5224. /*ma_resource_manager_data_stream**/ void* pDataStream;
  5225. ma_uint64 frameIndex;
  5226. } seekDataStream;
  5227. } resourceManager;
  5228. /* Device. */
  5229. union
  5230. {
  5231. union
  5232. {
  5233. struct
  5234. {
  5235. /*ma_device**/ void* pDevice;
  5236. /*ma_device_type*/ ma_uint32 deviceType;
  5237. } reroute;
  5238. } aaudio;
  5239. } device;
  5240. } data;
  5241. };
  5242. MA_API ma_job ma_job_init(ma_uint16 code);
  5243. MA_API ma_result ma_job_process(ma_job* pJob);
  5244. /*
  5245. When set, ma_job_queue_next() will not wait and no semaphore will be signaled in
  5246. ma_job_queue_post(). ma_job_queue_next() will return MA_NO_DATA_AVAILABLE if nothing is available.
  5247. This flag should always be used for platforms that do not support multithreading.
  5248. */
  5249. typedef enum
  5250. {
  5251. MA_JOB_QUEUE_FLAG_NON_BLOCKING = 0x00000001
  5252. } ma_job_queue_flags;
  5253. typedef struct
  5254. {
  5255. ma_uint32 flags;
  5256. ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. */
  5257. } ma_job_queue_config;
  5258. MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity);
  5259. typedef struct
  5260. {
  5261. ma_uint32 flags; /* Flags passed in at initialization time. */
  5262. ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. Set by the config. */
  5263. MA_ATOMIC(8, ma_uint64) head; /* The first item in the list. Required for removing from the top of the list. */
  5264. MA_ATOMIC(8, ma_uint64) tail; /* The last item in the list. Required for appending to the end of the list. */
  5265. #ifndef MA_NO_THREADING
  5266. ma_semaphore sem; /* Only used when MA_JOB_QUEUE_FLAG_NON_BLOCKING is unset. */
  5267. #endif
  5268. ma_slot_allocator allocator;
  5269. ma_job* pJobs;
  5270. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  5271. ma_spinlock lock;
  5272. #endif
  5273. /* Memory management. */
  5274. void* _pHeap;
  5275. ma_bool32 _ownsHeap;
  5276. } ma_job_queue;
  5277. MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes);
  5278. MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue);
  5279. MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue);
  5280. MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks);
  5281. MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob);
  5282. 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. */
  5283. /************************************************************************************************************************************************************
  5284. *************************************************************************************************************************************************************
  5285. DEVICE I/O
  5286. ==========
  5287. This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc.
  5288. *************************************************************************************************************************************************************
  5289. ************************************************************************************************************************************************************/
  5290. #ifndef MA_NO_DEVICE_IO
  5291. /* Some backends are only supported on certain platforms. */
  5292. #if defined(MA_WIN32)
  5293. #define MA_SUPPORT_WASAPI
  5294. #if defined(MA_WIN32_DESKTOP) /* DirectSound and WinMM backends are only supported on desktops. */
  5295. #define MA_SUPPORT_DSOUND
  5296. #define MA_SUPPORT_WINMM
  5297. /* Don't enable JACK here if compiling with Cosmopolitan. It'll be enabled in the Linux section below. */
  5298. #if !defined(__COSMOPOLITAN__)
  5299. #define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */
  5300. #endif
  5301. #endif
  5302. #endif
  5303. #if defined(MA_UNIX) && !defined(MA_ORBIS) && !defined(MA_PROSPERO)
  5304. #if defined(MA_LINUX)
  5305. #if !defined(MA_ANDROID) && !defined(__COSMOPOLITAN__) /* ALSA is not supported on Android. */
  5306. #define MA_SUPPORT_ALSA
  5307. #endif
  5308. #endif
  5309. #if !defined(MA_BSD) && !defined(MA_ANDROID) && !defined(MA_EMSCRIPTEN)
  5310. #define MA_SUPPORT_PULSEAUDIO
  5311. #define MA_SUPPORT_JACK
  5312. #endif
  5313. #if defined(__OpenBSD__) /* <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. */
  5314. #define MA_SUPPORT_SNDIO /* sndio is only supported on OpenBSD for now. May be expanded later if there's demand. */
  5315. #endif
  5316. #if defined(__NetBSD__) || defined(__OpenBSD__)
  5317. #define MA_SUPPORT_AUDIO4 /* Only support audio(4) on platforms with known support. */
  5318. #endif
  5319. #if defined(__FreeBSD__) || defined(__DragonFly__)
  5320. #define MA_SUPPORT_OSS /* Only support OSS on specific platforms with known support. */
  5321. #endif
  5322. #endif
  5323. #if defined(MA_ANDROID)
  5324. #define MA_SUPPORT_AAUDIO
  5325. #define MA_SUPPORT_OPENSL
  5326. #endif
  5327. #if defined(MA_APPLE)
  5328. #define MA_SUPPORT_COREAUDIO
  5329. #endif
  5330. #if defined(MA_EMSCRIPTEN)
  5331. #define MA_SUPPORT_WEBAUDIO
  5332. #endif
  5333. /* All platforms should support custom backends. */
  5334. #define MA_SUPPORT_CUSTOM
  5335. /* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */
  5336. #if !defined(MA_EMSCRIPTEN)
  5337. #define MA_SUPPORT_NULL
  5338. #endif
  5339. #if defined(MA_SUPPORT_WASAPI) && !defined(MA_NO_WASAPI) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WASAPI))
  5340. #define MA_HAS_WASAPI
  5341. #endif
  5342. #if defined(MA_SUPPORT_DSOUND) && !defined(MA_NO_DSOUND) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_DSOUND))
  5343. #define MA_HAS_DSOUND
  5344. #endif
  5345. #if defined(MA_SUPPORT_WINMM) && !defined(MA_NO_WINMM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WINMM))
  5346. #define MA_HAS_WINMM
  5347. #endif
  5348. #if defined(MA_SUPPORT_ALSA) && !defined(MA_NO_ALSA) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_ALSA))
  5349. #define MA_HAS_ALSA
  5350. #endif
  5351. #if defined(MA_SUPPORT_PULSEAUDIO) && !defined(MA_NO_PULSEAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_PULSEAUDIO))
  5352. #define MA_HAS_PULSEAUDIO
  5353. #endif
  5354. #if defined(MA_SUPPORT_JACK) && !defined(MA_NO_JACK) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_JACK))
  5355. #define MA_HAS_JACK
  5356. #endif
  5357. #if defined(MA_SUPPORT_COREAUDIO) && !defined(MA_NO_COREAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_COREAUDIO))
  5358. #define MA_HAS_COREAUDIO
  5359. #endif
  5360. #if defined(MA_SUPPORT_SNDIO) && !defined(MA_NO_SNDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_SNDIO))
  5361. #define MA_HAS_SNDIO
  5362. #endif
  5363. #if defined(MA_SUPPORT_AUDIO4) && !defined(MA_NO_AUDIO4) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AUDIO4))
  5364. #define MA_HAS_AUDIO4
  5365. #endif
  5366. #if defined(MA_SUPPORT_OSS) && !defined(MA_NO_OSS) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OSS))
  5367. #define MA_HAS_OSS
  5368. #endif
  5369. #if defined(MA_SUPPORT_AAUDIO) && !defined(MA_NO_AAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AAUDIO))
  5370. #define MA_HAS_AAUDIO
  5371. #endif
  5372. #if defined(MA_SUPPORT_OPENSL) && !defined(MA_NO_OPENSL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OPENSL))
  5373. #define MA_HAS_OPENSL
  5374. #endif
  5375. #if defined(MA_SUPPORT_WEBAUDIO) && !defined(MA_NO_WEBAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WEBAUDIO))
  5376. #define MA_HAS_WEBAUDIO
  5377. #endif
  5378. #if defined(MA_SUPPORT_CUSTOM) && !defined(MA_NO_CUSTOM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_CUSTOM))
  5379. #define MA_HAS_CUSTOM
  5380. #endif
  5381. #if defined(MA_SUPPORT_NULL) && !defined(MA_NO_NULL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_NULL))
  5382. #define MA_HAS_NULL
  5383. #endif
  5384. typedef enum
  5385. {
  5386. ma_device_state_uninitialized = 0,
  5387. ma_device_state_stopped = 1, /* The device's default state after initialization. */
  5388. ma_device_state_started = 2, /* The device is started and is requesting and/or delivering audio data. */
  5389. ma_device_state_starting = 3, /* Transitioning from a stopped state to started. */
  5390. ma_device_state_stopping = 4 /* Transitioning from a started state to stopped. */
  5391. } ma_device_state;
  5392. MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, device_state)
  5393. #ifdef MA_SUPPORT_WASAPI
  5394. /* We need a IMMNotificationClient object for WASAPI. */
  5395. typedef struct
  5396. {
  5397. void* lpVtbl;
  5398. ma_uint32 counter;
  5399. ma_device* pDevice;
  5400. } ma_IMMNotificationClient;
  5401. #endif
  5402. /* Backend enums must be in priority order. */
  5403. typedef enum
  5404. {
  5405. ma_backend_wasapi,
  5406. ma_backend_dsound,
  5407. ma_backend_winmm,
  5408. ma_backend_coreaudio,
  5409. ma_backend_sndio,
  5410. ma_backend_audio4,
  5411. ma_backend_oss,
  5412. ma_backend_pulseaudio,
  5413. ma_backend_alsa,
  5414. ma_backend_jack,
  5415. ma_backend_aaudio,
  5416. ma_backend_opensl,
  5417. ma_backend_webaudio,
  5418. ma_backend_custom, /* <-- Custom backend, with callbacks defined by the context config. */
  5419. ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */
  5420. } ma_backend;
  5421. #define MA_BACKEND_COUNT (ma_backend_null+1)
  5422. /*
  5423. Device job thread. This is used by backends that require asynchronous processing of certain
  5424. operations. It is not used by all backends.
  5425. The device job thread is made up of a thread and a job queue. You can post a job to the thread with
  5426. ma_device_job_thread_post(). The thread will do the processing of the job.
  5427. */
  5428. typedef struct
  5429. {
  5430. ma_bool32 noThread; /* Set this to true if you want to process jobs yourself. */
  5431. ma_uint32 jobQueueCapacity;
  5432. ma_uint32 jobQueueFlags;
  5433. } ma_device_job_thread_config;
  5434. MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void);
  5435. typedef struct
  5436. {
  5437. ma_thread thread;
  5438. ma_job_queue jobQueue;
  5439. ma_bool32 _hasThread;
  5440. } ma_device_job_thread;
  5441. 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);
  5442. MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks);
  5443. MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob);
  5444. MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob);
  5445. /* Device notification types. */
  5446. typedef enum
  5447. {
  5448. ma_device_notification_type_started,
  5449. ma_device_notification_type_stopped,
  5450. ma_device_notification_type_rerouted,
  5451. ma_device_notification_type_interruption_began,
  5452. ma_device_notification_type_interruption_ended
  5453. } ma_device_notification_type;
  5454. typedef struct
  5455. {
  5456. ma_device* pDevice;
  5457. ma_device_notification_type type;
  5458. union
  5459. {
  5460. struct
  5461. {
  5462. int _unused;
  5463. } started;
  5464. struct
  5465. {
  5466. int _unused;
  5467. } stopped;
  5468. struct
  5469. {
  5470. int _unused;
  5471. } rerouted;
  5472. struct
  5473. {
  5474. int _unused;
  5475. } interruption;
  5476. } data;
  5477. } ma_device_notification;
  5478. /*
  5479. The notification callback for when the application should be notified of a change to the device.
  5480. This callback is used for notifying the application of changes such as when the device has started,
  5481. stopped, rerouted or an interruption has occurred. Note that not all backends will post all
  5482. notification types. For example, some backends will perform automatic stream routing without any
  5483. kind of notification to the host program which means miniaudio will never know about it and will
  5484. never be able to fire the rerouted notification. You should keep this in mind when designing your
  5485. program.
  5486. The stopped notification will *not* get fired when a device is rerouted.
  5487. Parameters
  5488. ----------
  5489. pNotification (in)
  5490. A pointer to a structure containing information about the event. Use the `pDevice` member of
  5491. this object to retrieve the relevant device. The `type` member can be used to discriminate
  5492. against each of the notification types.
  5493. Remarks
  5494. -------
  5495. Do not restart or uninitialize the device from the callback.
  5496. Not all notifications will be triggered by all backends, however the started and stopped events
  5497. should be reliable for all backends. Some backends do not have a good way to detect device
  5498. stoppages due to unplugging the device which may result in the stopped callback not getting
  5499. fired. This has been observed with at least one BSD variant.
  5500. The rerouted notification is fired *after* the reroute has occurred. The stopped notification will
  5501. *not* get fired when a device is rerouted. The following backends are known to do automatic stream
  5502. rerouting, but do not have a way to be notified of the change:
  5503. * DirectSound
  5504. The interruption notifications are used on mobile platforms for detecting when audio is interrupted
  5505. due to things like an incoming phone call. Currently this is only implemented on iOS. None of the
  5506. Android backends will report this notification.
  5507. */
  5508. typedef void (* ma_device_notification_proc)(const ma_device_notification* pNotification);
  5509. /*
  5510. The callback for processing audio data from the device.
  5511. 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
  5512. 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
  5513. callback will be fired with a consistent frame count.
  5514. Parameters
  5515. ----------
  5516. pDevice (in)
  5517. A pointer to the relevant device.
  5518. pOutput (out)
  5519. 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
  5520. full-duplex device and null for a capture and loopback device.
  5521. pInput (in)
  5522. 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
  5523. playback device.
  5524. frameCount (in)
  5525. 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
  5526. `periodSizeInFrames` and `periodSizeInMilliseconds` members of the device config are just hints, and are not necessarily exactly what you'll get. You must
  5527. not assume this will always be the same value each time the callback is fired.
  5528. Remarks
  5529. -------
  5530. 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
  5531. callback. The following APIs cannot be called from inside the callback:
  5532. ma_device_init()
  5533. ma_device_init_ex()
  5534. ma_device_uninit()
  5535. ma_device_start()
  5536. ma_device_stop()
  5537. The proper way to stop the device is to call `ma_device_stop()` from a different thread, normally the main application thread.
  5538. */
  5539. typedef void (* ma_device_data_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
  5540. /*
  5541. DEPRECATED. Use ma_device_notification_proc instead.
  5542. The callback for when the device has been stopped.
  5543. 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
  5544. such as being unplugged or an internal error occurring.
  5545. Parameters
  5546. ----------
  5547. pDevice (in)
  5548. A pointer to the device that has just stopped.
  5549. Remarks
  5550. -------
  5551. Do not restart or uninitialize the device from the callback.
  5552. */
  5553. typedef void (* ma_stop_proc)(ma_device* pDevice); /* DEPRECATED. Use ma_device_notification_proc instead. */
  5554. typedef enum
  5555. {
  5556. ma_device_type_playback = 1,
  5557. ma_device_type_capture = 2,
  5558. ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, /* 3 */
  5559. ma_device_type_loopback = 4
  5560. } ma_device_type;
  5561. typedef enum
  5562. {
  5563. ma_share_mode_shared = 0,
  5564. ma_share_mode_exclusive
  5565. } ma_share_mode;
  5566. /* iOS/tvOS/watchOS session categories. */
  5567. typedef enum
  5568. {
  5569. ma_ios_session_category_default = 0, /* AVAudioSessionCategoryPlayAndRecord. */
  5570. ma_ios_session_category_none, /* Leave the session category unchanged. */
  5571. ma_ios_session_category_ambient, /* AVAudioSessionCategoryAmbient */
  5572. ma_ios_session_category_solo_ambient, /* AVAudioSessionCategorySoloAmbient */
  5573. ma_ios_session_category_playback, /* AVAudioSessionCategoryPlayback */
  5574. ma_ios_session_category_record, /* AVAudioSessionCategoryRecord */
  5575. ma_ios_session_category_play_and_record, /* AVAudioSessionCategoryPlayAndRecord */
  5576. ma_ios_session_category_multi_route /* AVAudioSessionCategoryMultiRoute */
  5577. } ma_ios_session_category;
  5578. /* iOS/tvOS/watchOS session category options */
  5579. typedef enum
  5580. {
  5581. ma_ios_session_category_option_mix_with_others = 0x01, /* AVAudioSessionCategoryOptionMixWithOthers */
  5582. ma_ios_session_category_option_duck_others = 0x02, /* AVAudioSessionCategoryOptionDuckOthers */
  5583. ma_ios_session_category_option_allow_bluetooth = 0x04, /* AVAudioSessionCategoryOptionAllowBluetooth */
  5584. ma_ios_session_category_option_default_to_speaker = 0x08, /* AVAudioSessionCategoryOptionDefaultToSpeaker */
  5585. ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others = 0x11, /* AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */
  5586. ma_ios_session_category_option_allow_bluetooth_a2dp = 0x20, /* AVAudioSessionCategoryOptionAllowBluetoothA2DP */
  5587. ma_ios_session_category_option_allow_air_play = 0x40, /* AVAudioSessionCategoryOptionAllowAirPlay */
  5588. } ma_ios_session_category_option;
  5589. /* OpenSL stream types. */
  5590. typedef enum
  5591. {
  5592. ma_opensl_stream_type_default = 0, /* Leaves the stream type unset. */
  5593. ma_opensl_stream_type_voice, /* SL_ANDROID_STREAM_VOICE */
  5594. ma_opensl_stream_type_system, /* SL_ANDROID_STREAM_SYSTEM */
  5595. ma_opensl_stream_type_ring, /* SL_ANDROID_STREAM_RING */
  5596. ma_opensl_stream_type_media, /* SL_ANDROID_STREAM_MEDIA */
  5597. ma_opensl_stream_type_alarm, /* SL_ANDROID_STREAM_ALARM */
  5598. ma_opensl_stream_type_notification /* SL_ANDROID_STREAM_NOTIFICATION */
  5599. } ma_opensl_stream_type;
  5600. /* OpenSL recording presets. */
  5601. typedef enum
  5602. {
  5603. ma_opensl_recording_preset_default = 0, /* Leaves the input preset unset. */
  5604. ma_opensl_recording_preset_generic, /* SL_ANDROID_RECORDING_PRESET_GENERIC */
  5605. ma_opensl_recording_preset_camcorder, /* SL_ANDROID_RECORDING_PRESET_CAMCORDER */
  5606. ma_opensl_recording_preset_voice_recognition, /* SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION */
  5607. ma_opensl_recording_preset_voice_communication, /* SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION */
  5608. ma_opensl_recording_preset_voice_unprocessed /* SL_ANDROID_RECORDING_PRESET_UNPROCESSED */
  5609. } ma_opensl_recording_preset;
  5610. /* WASAPI audio thread priority characteristics. */
  5611. typedef enum
  5612. {
  5613. ma_wasapi_usage_default = 0,
  5614. ma_wasapi_usage_games,
  5615. ma_wasapi_usage_pro_audio,
  5616. } ma_wasapi_usage;
  5617. /* AAudio usage types. */
  5618. typedef enum
  5619. {
  5620. ma_aaudio_usage_default = 0, /* Leaves the usage type unset. */
  5621. ma_aaudio_usage_media, /* AAUDIO_USAGE_MEDIA */
  5622. ma_aaudio_usage_voice_communication, /* AAUDIO_USAGE_VOICE_COMMUNICATION */
  5623. ma_aaudio_usage_voice_communication_signalling, /* AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING */
  5624. ma_aaudio_usage_alarm, /* AAUDIO_USAGE_ALARM */
  5625. ma_aaudio_usage_notification, /* AAUDIO_USAGE_NOTIFICATION */
  5626. ma_aaudio_usage_notification_ringtone, /* AAUDIO_USAGE_NOTIFICATION_RINGTONE */
  5627. ma_aaudio_usage_notification_event, /* AAUDIO_USAGE_NOTIFICATION_EVENT */
  5628. ma_aaudio_usage_assistance_accessibility, /* AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY */
  5629. ma_aaudio_usage_assistance_navigation_guidance, /* AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */
  5630. ma_aaudio_usage_assistance_sonification, /* AAUDIO_USAGE_ASSISTANCE_SONIFICATION */
  5631. ma_aaudio_usage_game, /* AAUDIO_USAGE_GAME */
  5632. ma_aaudio_usage_assitant, /* AAUDIO_USAGE_ASSISTANT */
  5633. ma_aaudio_usage_emergency, /* AAUDIO_SYSTEM_USAGE_EMERGENCY */
  5634. ma_aaudio_usage_safety, /* AAUDIO_SYSTEM_USAGE_SAFETY */
  5635. ma_aaudio_usage_vehicle_status, /* AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS */
  5636. ma_aaudio_usage_announcement /* AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT */
  5637. } ma_aaudio_usage;
  5638. /* AAudio content types. */
  5639. typedef enum
  5640. {
  5641. ma_aaudio_content_type_default = 0, /* Leaves the content type unset. */
  5642. ma_aaudio_content_type_speech, /* AAUDIO_CONTENT_TYPE_SPEECH */
  5643. ma_aaudio_content_type_music, /* AAUDIO_CONTENT_TYPE_MUSIC */
  5644. ma_aaudio_content_type_movie, /* AAUDIO_CONTENT_TYPE_MOVIE */
  5645. ma_aaudio_content_type_sonification /* AAUDIO_CONTENT_TYPE_SONIFICATION */
  5646. } ma_aaudio_content_type;
  5647. /* AAudio input presets. */
  5648. typedef enum
  5649. {
  5650. ma_aaudio_input_preset_default = 0, /* Leaves the input preset unset. */
  5651. ma_aaudio_input_preset_generic, /* AAUDIO_INPUT_PRESET_GENERIC */
  5652. ma_aaudio_input_preset_camcorder, /* AAUDIO_INPUT_PRESET_CAMCORDER */
  5653. ma_aaudio_input_preset_voice_recognition, /* AAUDIO_INPUT_PRESET_VOICE_RECOGNITION */
  5654. ma_aaudio_input_preset_voice_communication, /* AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION */
  5655. ma_aaudio_input_preset_unprocessed, /* AAUDIO_INPUT_PRESET_UNPROCESSED */
  5656. ma_aaudio_input_preset_voice_performance /* AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE */
  5657. } ma_aaudio_input_preset;
  5658. typedef enum
  5659. {
  5660. ma_aaudio_allow_capture_default = 0, /* Leaves the allowed capture policy unset. */
  5661. ma_aaudio_allow_capture_by_all, /* AAUDIO_ALLOW_CAPTURE_BY_ALL */
  5662. ma_aaudio_allow_capture_by_system, /* AAUDIO_ALLOW_CAPTURE_BY_SYSTEM */
  5663. ma_aaudio_allow_capture_by_none /* AAUDIO_ALLOW_CAPTURE_BY_NONE */
  5664. } ma_aaudio_allowed_capture_policy;
  5665. typedef union
  5666. {
  5667. ma_int64 counter;
  5668. double counterD;
  5669. } ma_timer;
  5670. typedef union
  5671. {
  5672. ma_wchar_win32 wasapi[64]; /* WASAPI uses a wchar_t string for identification. */
  5673. ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */
  5674. /*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. */
  5675. char alsa[256]; /* ALSA uses a name string for identification. */
  5676. char pulse[256]; /* PulseAudio uses a name string for identification. */
  5677. int jack; /* JACK always uses default devices. */
  5678. char coreaudio[256]; /* Core Audio uses a string for identification. */
  5679. char sndio[256]; /* "snd/0", etc. */
  5680. char audio4[256]; /* "/dev/audio", etc. */
  5681. char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */
  5682. ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */
  5683. ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */
  5684. char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */
  5685. union
  5686. {
  5687. int i;
  5688. char s[256];
  5689. void* p;
  5690. } custom; /* The custom backend could be anything. Give them a few options. */
  5691. int nullbackend; /* The null backend uses an integer for device IDs. */
  5692. } ma_device_id;
  5693. typedef struct ma_context_config ma_context_config;
  5694. typedef struct ma_device_config ma_device_config;
  5695. typedef struct ma_backend_callbacks ma_backend_callbacks;
  5696. #define MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE (1U << 1) /* If set, this is supported in exclusive mode. Otherwise not natively supported by exclusive mode. */
  5697. #ifndef MA_MAX_DEVICE_NAME_LENGTH
  5698. #define MA_MAX_DEVICE_NAME_LENGTH 255
  5699. #endif
  5700. typedef struct
  5701. {
  5702. /* Basic info. This is the only information guaranteed to be filled in during device enumeration. */
  5703. ma_device_id id;
  5704. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* +1 for null terminator. */
  5705. ma_bool32 isDefault;
  5706. ma_uint32 nativeDataFormatCount;
  5707. struct
  5708. {
  5709. ma_format format; /* Sample format. If set to ma_format_unknown, all sample formats are supported. */
  5710. ma_uint32 channels; /* If set to 0, all channels are supported. */
  5711. ma_uint32 sampleRate; /* If set to 0, all sample rates are supported. */
  5712. ma_uint32 flags; /* A combination of MA_DATA_FORMAT_FLAG_* flags. */
  5713. } 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. */
  5714. } ma_device_info;
  5715. struct ma_device_config
  5716. {
  5717. ma_device_type deviceType;
  5718. ma_uint32 sampleRate;
  5719. ma_uint32 periodSizeInFrames;
  5720. ma_uint32 periodSizeInMilliseconds;
  5721. ma_uint32 periods;
  5722. ma_performance_profile performanceProfile;
  5723. 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. */
  5724. ma_bool8 noClip; /* When set to true, the contents of the output buffer passed into the data callback will not be clipped after returning. Only applies when the playback sample format is f32. */
  5725. ma_bool8 noDisableDenormals; /* Do not disable denormals when firing the data callback. */
  5726. 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. */
  5727. ma_device_data_proc dataCallback;
  5728. ma_device_notification_proc notificationCallback;
  5729. ma_stop_proc stopCallback;
  5730. void* pUserData;
  5731. ma_resampler_config resampling;
  5732. struct
  5733. {
  5734. const ma_device_id* pDeviceID;
  5735. ma_format format;
  5736. ma_uint32 channels;
  5737. ma_channel* pChannelMap;
  5738. ma_channel_mix_mode channelMixMode;
  5739. 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. */
  5740. ma_share_mode shareMode;
  5741. } playback;
  5742. struct
  5743. {
  5744. const ma_device_id* pDeviceID;
  5745. ma_format format;
  5746. ma_uint32 channels;
  5747. ma_channel* pChannelMap;
  5748. ma_channel_mix_mode channelMixMode;
  5749. 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. */
  5750. ma_share_mode shareMode;
  5751. } capture;
  5752. struct
  5753. {
  5754. ma_wasapi_usage usage; /* When configured, uses Avrt APIs to set the thread characteristics. */
  5755. ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
  5756. ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
  5757. ma_bool8 noAutoStreamRouting; /* Disables automatic stream routing. */
  5758. ma_bool8 noHardwareOffloading; /* Disables WASAPI's hardware offloading feature. */
  5759. 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. */
  5760. ma_bool8 loopbackProcessExclude; /* When set to true, excludes the process specified by loopbackProcessID. By default, the process will be included. */
  5761. } wasapi;
  5762. struct
  5763. {
  5764. ma_bool32 noMMap; /* Disables MMap mode. */
  5765. ma_bool32 noAutoFormat; /* Opens the ALSA device with SND_PCM_NO_AUTO_FORMAT. */
  5766. ma_bool32 noAutoChannels; /* Opens the ALSA device with SND_PCM_NO_AUTO_CHANNELS. */
  5767. ma_bool32 noAutoResample; /* Opens the ALSA device with SND_PCM_NO_AUTO_RESAMPLE. */
  5768. } alsa;
  5769. struct
  5770. {
  5771. const char* pStreamNamePlayback;
  5772. const char* pStreamNameCapture;
  5773. } pulse;
  5774. struct
  5775. {
  5776. ma_bool32 allowNominalSampleRateChange; /* Desktop only. When enabled, allows changing of the sample rate at the operating system level. */
  5777. } coreaudio;
  5778. struct
  5779. {
  5780. ma_opensl_stream_type streamType;
  5781. ma_opensl_recording_preset recordingPreset;
  5782. ma_bool32 enableCompatibilityWorkarounds;
  5783. } opensl;
  5784. struct
  5785. {
  5786. ma_aaudio_usage usage;
  5787. ma_aaudio_content_type contentType;
  5788. ma_aaudio_input_preset inputPreset;
  5789. ma_aaudio_allowed_capture_policy allowedCapturePolicy;
  5790. ma_bool32 noAutoStartAfterReroute;
  5791. ma_bool32 enableCompatibilityWorkarounds;
  5792. } aaudio;
  5793. };
  5794. /*
  5795. The callback for handling device enumeration. This is fired from `ma_context_enumerate_devices()`.
  5796. Parameters
  5797. ----------
  5798. pContext (in)
  5799. A pointer to the context performing the enumeration.
  5800. deviceType (in)
  5801. The type of the device being enumerated. This will always be either `ma_device_type_playback` or `ma_device_type_capture`.
  5802. pInfo (in)
  5803. 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,
  5804. 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
  5805. is too inefficient.
  5806. pUserData (in)
  5807. The user data pointer passed into `ma_context_enumerate_devices()`.
  5808. */
  5809. typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData);
  5810. /*
  5811. Describes some basic details about a playback or capture device.
  5812. */
  5813. typedef struct
  5814. {
  5815. const ma_device_id* pDeviceID;
  5816. ma_share_mode shareMode;
  5817. ma_format format;
  5818. ma_uint32 channels;
  5819. ma_uint32 sampleRate;
  5820. ma_channel channelMap[MA_MAX_CHANNELS];
  5821. ma_uint32 periodSizeInFrames;
  5822. ma_uint32 periodSizeInMilliseconds;
  5823. ma_uint32 periodCount;
  5824. } ma_device_descriptor;
  5825. /*
  5826. 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
  5827. to many devices. A device is created from a context.
  5828. The general flow goes like this:
  5829. 1) A context is created with `onContextInit()`
  5830. 1a) Available devices can be enumerated with `onContextEnumerateDevices()` if required.
  5831. 1b) Detailed information about a device can be queried with `onContextGetDeviceInfo()` if required.
  5832. 2) A device is created from the context that was created in the first step using `onDeviceInit()`, and optionally a device ID that was
  5833. selected from device enumeration via `onContextEnumerateDevices()`.
  5834. 3) A device is started or stopped with `onDeviceStart()` / `onDeviceStop()`
  5835. 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
  5836. to `onDeviceInit()`. Conversion between the device's native format and the format requested by the application will be handled by
  5837. miniaudio internally.
  5838. Initialization of the context is quite simple. You need to do any necessary initialization of internal objects and then output the
  5839. callbacks defined in this structure.
  5840. Once the context has been initialized you can initialize a device. Before doing so, however, the application may want to know which
  5841. physical devices are available. This is where `onContextEnumerateDevices()` comes in. This is fairly simple. For each device, fire the
  5842. given callback with, at a minimum, the basic information filled out in `ma_device_info`. When the callback returns `MA_FALSE`, enumeration
  5843. needs to stop and the `onContextEnumerateDevices()` function returns with a success code.
  5844. Detailed device information can be retrieved from a device ID using `onContextGetDeviceInfo()`. This takes as input the device type and ID,
  5845. and on output returns detailed information about the device in `ma_device_info`. The `onContextGetDeviceInfo()` callback must handle the
  5846. case when the device ID is NULL, in which case information about the default device needs to be retrieved.
  5847. Once the context has been created and the device ID retrieved (if using anything other than the default device), the device can be created.
  5848. This is a little bit more complicated than initialization of the context due to it's more complicated configuration. When initializing a
  5849. device, a duplex device may be requested. This means a separate data format needs to be specified for both playback and capture. On input,
  5850. 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
  5851. the requested format. The conversion between the format requested by the application and the device's native format will be handled
  5852. internally by miniaudio.
  5853. 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
  5854. 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
  5855. sample rate. For the channel map, the default should be used when `ma_channel_map_is_blank()` returns true (all channels set to
  5856. `MA_CHANNEL_NONE`). On input, the `periodSizeInFrames` or `periodSizeInMilliseconds` option should always be set. The backend should
  5857. inspect both of these variables. If `periodSizeInFrames` is set, it should take priority, otherwise it needs to be derived from the period
  5858. size in milliseconds (`periodSizeInMilliseconds`) and the sample rate, keeping in mind that the sample rate may be 0, in which case the
  5859. sample rate will need to be determined before calculating the period size in frames. On output, all members of the `ma_device_descriptor`
  5860. object should be set to a valid value, except for `periodSizeInMilliseconds` which is optional (`periodSizeInFrames` *must* be set).
  5861. Starting and stopping of the device is done with `onDeviceStart()` and `onDeviceStop()` and should be self-explanatory. If the backend uses
  5862. asynchronous reading and writing, `onDeviceStart()` and `onDeviceStop()` should always be implemented.
  5863. The handling of data delivery between the application and the device is the most complicated part of the process. To make this a bit
  5864. easier, some helper callbacks are available. If the backend uses a blocking read/write style of API, the `onDeviceRead()` and
  5865. `onDeviceWrite()` callbacks can optionally be implemented. These are blocking and work just like reading and writing from a file. If the
  5866. backend uses a callback for data delivery, that callback must call `ma_device_handle_backend_data_callback()` from within it's callback.
  5867. This allows miniaudio to then process any necessary data conversion and then pass it to the miniaudio data callback.
  5868. If the backend requires absolute flexibility with it's data delivery, it can optionally implement the `onDeviceDataLoop()` callback
  5869. which will allow it to implement the logic that will run on the audio thread. This is much more advanced and is completely optional.
  5870. 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
  5871. encountered. Do not start or stop the device here. That will be handled from outside the `onDeviceDataLoop()` callback.
  5872. The invocation of the `onDeviceDataLoop()` callback will be handled by miniaudio. When you start the device, miniaudio will fire this
  5873. callback. When the device is stopped, the `ma_device_get_state() == ma_device_state_started` condition will fail and the loop will be terminated
  5874. which will then fall through to the part that stops the device. For an example on how to implement the `onDeviceDataLoop()` callback,
  5875. look at `ma_device_audio_thread__default_read_write()`. Implement the `onDeviceDataLoopWakeup()` callback if you need a mechanism to
  5876. wake up the audio thread.
  5877. If the backend supports an optimized retrieval of device information from an initialized `ma_device` object, it should implement the
  5878. `onDeviceGetInfo()` callback. This is optional, in which case it will fall back to `onContextGetDeviceInfo()` which is less efficient.
  5879. */
  5880. struct ma_backend_callbacks
  5881. {
  5882. ma_result (* onContextInit)(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks);
  5883. ma_result (* onContextUninit)(ma_context* pContext);
  5884. ma_result (* onContextEnumerateDevices)(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
  5885. ma_result (* onContextGetDeviceInfo)(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo);
  5886. ma_result (* onDeviceInit)(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture);
  5887. ma_result (* onDeviceUninit)(ma_device* pDevice);
  5888. ma_result (* onDeviceStart)(ma_device* pDevice);
  5889. ma_result (* onDeviceStop)(ma_device* pDevice);
  5890. ma_result (* onDeviceRead)(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead);
  5891. ma_result (* onDeviceWrite)(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten);
  5892. ma_result (* onDeviceDataLoop)(ma_device* pDevice);
  5893. ma_result (* onDeviceDataLoopWakeup)(ma_device* pDevice);
  5894. ma_result (* onDeviceGetInfo)(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
  5895. };
  5896. struct ma_context_config
  5897. {
  5898. ma_log* pLog;
  5899. ma_thread_priority threadPriority;
  5900. size_t threadStackSize;
  5901. void* pUserData;
  5902. ma_allocation_callbacks allocationCallbacks;
  5903. struct
  5904. {
  5905. ma_bool32 useVerboseDeviceEnumeration;
  5906. } alsa;
  5907. struct
  5908. {
  5909. const char* pApplicationName;
  5910. const char* pServerName;
  5911. ma_bool32 tryAutoSpawn; /* Enables autospawning of the PulseAudio daemon if necessary. */
  5912. } pulse;
  5913. struct
  5914. {
  5915. ma_ios_session_category sessionCategory;
  5916. ma_uint32 sessionCategoryOptions;
  5917. ma_bool32 noAudioSessionActivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. */
  5918. ma_bool32 noAudioSessionDeactivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. */
  5919. } coreaudio;
  5920. struct
  5921. {
  5922. const char* pClientName;
  5923. ma_bool32 tryStartServer;
  5924. } jack;
  5925. ma_backend_callbacks custom;
  5926. };
  5927. /* WASAPI specific structure for some commands which must run on a common thread due to bugs in WASAPI. */
  5928. typedef struct
  5929. {
  5930. int code;
  5931. ma_event* pEvent; /* This will be signalled when the event is complete. */
  5932. union
  5933. {
  5934. struct
  5935. {
  5936. int _unused;
  5937. } quit;
  5938. struct
  5939. {
  5940. ma_device_type deviceType;
  5941. void* pAudioClient;
  5942. void** ppAudioClientService;
  5943. ma_result* pResult; /* The result from creating the audio client service. */
  5944. } createAudioClient;
  5945. struct
  5946. {
  5947. ma_device* pDevice;
  5948. ma_device_type deviceType;
  5949. } releaseAudioClient;
  5950. } data;
  5951. } ma_context_command__wasapi;
  5952. struct ma_context
  5953. {
  5954. ma_backend_callbacks callbacks;
  5955. ma_backend backend; /* DirectSound, ALSA, etc. */
  5956. ma_log* pLog;
  5957. ma_log log; /* Only used if the log is owned by the context. The pLog member will be set to &log in this case. */
  5958. ma_thread_priority threadPriority;
  5959. size_t threadStackSize;
  5960. void* pUserData;
  5961. ma_allocation_callbacks allocationCallbacks;
  5962. ma_mutex deviceEnumLock; /* Used to make ma_context_get_devices() thread safe. */
  5963. ma_mutex deviceInfoLock; /* Used to make ma_context_get_device_info() thread safe. */
  5964. ma_uint32 deviceInfoCapacity; /* Total capacity of pDeviceInfos. */
  5965. ma_uint32 playbackDeviceInfoCount;
  5966. ma_uint32 captureDeviceInfoCount;
  5967. ma_device_info* pDeviceInfos; /* Playback devices first, then capture. */
  5968. union
  5969. {
  5970. #ifdef MA_SUPPORT_WASAPI
  5971. struct
  5972. {
  5973. ma_thread commandThread;
  5974. ma_mutex commandLock;
  5975. ma_semaphore commandSem;
  5976. ma_uint32 commandIndex;
  5977. ma_uint32 commandCount;
  5978. ma_context_command__wasapi commands[4];
  5979. ma_handle hAvrt;
  5980. ma_proc AvSetMmThreadCharacteristicsA;
  5981. ma_proc AvRevertMmThreadcharacteristics;
  5982. ma_handle hMMDevapi;
  5983. ma_proc ActivateAudioInterfaceAsync;
  5984. } wasapi;
  5985. #endif
  5986. #ifdef MA_SUPPORT_DSOUND
  5987. struct
  5988. {
  5989. ma_handle hDSoundDLL;
  5990. ma_proc DirectSoundCreate;
  5991. ma_proc DirectSoundEnumerateA;
  5992. ma_proc DirectSoundCaptureCreate;
  5993. ma_proc DirectSoundCaptureEnumerateA;
  5994. } dsound;
  5995. #endif
  5996. #ifdef MA_SUPPORT_WINMM
  5997. struct
  5998. {
  5999. ma_handle hWinMM;
  6000. ma_proc waveOutGetNumDevs;
  6001. ma_proc waveOutGetDevCapsA;
  6002. ma_proc waveOutOpen;
  6003. ma_proc waveOutClose;
  6004. ma_proc waveOutPrepareHeader;
  6005. ma_proc waveOutUnprepareHeader;
  6006. ma_proc waveOutWrite;
  6007. ma_proc waveOutReset;
  6008. ma_proc waveInGetNumDevs;
  6009. ma_proc waveInGetDevCapsA;
  6010. ma_proc waveInOpen;
  6011. ma_proc waveInClose;
  6012. ma_proc waveInPrepareHeader;
  6013. ma_proc waveInUnprepareHeader;
  6014. ma_proc waveInAddBuffer;
  6015. ma_proc waveInStart;
  6016. ma_proc waveInReset;
  6017. } winmm;
  6018. #endif
  6019. #ifdef MA_SUPPORT_ALSA
  6020. struct
  6021. {
  6022. ma_handle asoundSO;
  6023. ma_proc snd_pcm_open;
  6024. ma_proc snd_pcm_close;
  6025. ma_proc snd_pcm_hw_params_sizeof;
  6026. ma_proc snd_pcm_hw_params_any;
  6027. ma_proc snd_pcm_hw_params_set_format;
  6028. ma_proc snd_pcm_hw_params_set_format_first;
  6029. ma_proc snd_pcm_hw_params_get_format_mask;
  6030. ma_proc snd_pcm_hw_params_set_channels;
  6031. ma_proc snd_pcm_hw_params_set_channels_near;
  6032. ma_proc snd_pcm_hw_params_set_channels_minmax;
  6033. ma_proc snd_pcm_hw_params_set_rate_resample;
  6034. ma_proc snd_pcm_hw_params_set_rate;
  6035. ma_proc snd_pcm_hw_params_set_rate_near;
  6036. ma_proc snd_pcm_hw_params_set_buffer_size_near;
  6037. ma_proc snd_pcm_hw_params_set_periods_near;
  6038. ma_proc snd_pcm_hw_params_set_access;
  6039. ma_proc snd_pcm_hw_params_get_format;
  6040. ma_proc snd_pcm_hw_params_get_channels;
  6041. ma_proc snd_pcm_hw_params_get_channels_min;
  6042. ma_proc snd_pcm_hw_params_get_channels_max;
  6043. ma_proc snd_pcm_hw_params_get_rate;
  6044. ma_proc snd_pcm_hw_params_get_rate_min;
  6045. ma_proc snd_pcm_hw_params_get_rate_max;
  6046. ma_proc snd_pcm_hw_params_get_buffer_size;
  6047. ma_proc snd_pcm_hw_params_get_periods;
  6048. ma_proc snd_pcm_hw_params_get_access;
  6049. ma_proc snd_pcm_hw_params_test_format;
  6050. ma_proc snd_pcm_hw_params_test_channels;
  6051. ma_proc snd_pcm_hw_params_test_rate;
  6052. ma_proc snd_pcm_hw_params;
  6053. ma_proc snd_pcm_sw_params_sizeof;
  6054. ma_proc snd_pcm_sw_params_current;
  6055. ma_proc snd_pcm_sw_params_get_boundary;
  6056. ma_proc snd_pcm_sw_params_set_avail_min;
  6057. ma_proc snd_pcm_sw_params_set_start_threshold;
  6058. ma_proc snd_pcm_sw_params_set_stop_threshold;
  6059. ma_proc snd_pcm_sw_params;
  6060. ma_proc snd_pcm_format_mask_sizeof;
  6061. ma_proc snd_pcm_format_mask_test;
  6062. ma_proc snd_pcm_get_chmap;
  6063. ma_proc snd_pcm_state;
  6064. ma_proc snd_pcm_prepare;
  6065. ma_proc snd_pcm_start;
  6066. ma_proc snd_pcm_drop;
  6067. ma_proc snd_pcm_drain;
  6068. ma_proc snd_pcm_reset;
  6069. ma_proc snd_device_name_hint;
  6070. ma_proc snd_device_name_get_hint;
  6071. ma_proc snd_card_get_index;
  6072. ma_proc snd_device_name_free_hint;
  6073. ma_proc snd_pcm_mmap_begin;
  6074. ma_proc snd_pcm_mmap_commit;
  6075. ma_proc snd_pcm_recover;
  6076. ma_proc snd_pcm_readi;
  6077. ma_proc snd_pcm_writei;
  6078. ma_proc snd_pcm_avail;
  6079. ma_proc snd_pcm_avail_update;
  6080. ma_proc snd_pcm_wait;
  6081. ma_proc snd_pcm_nonblock;
  6082. ma_proc snd_pcm_info;
  6083. ma_proc snd_pcm_info_sizeof;
  6084. ma_proc snd_pcm_info_get_name;
  6085. ma_proc snd_pcm_poll_descriptors;
  6086. ma_proc snd_pcm_poll_descriptors_count;
  6087. ma_proc snd_pcm_poll_descriptors_revents;
  6088. ma_proc snd_config_update_free_global;
  6089. ma_mutex internalDeviceEnumLock;
  6090. ma_bool32 useVerboseDeviceEnumeration;
  6091. } alsa;
  6092. #endif
  6093. #ifdef MA_SUPPORT_PULSEAUDIO
  6094. struct
  6095. {
  6096. ma_handle pulseSO;
  6097. ma_proc pa_mainloop_new;
  6098. ma_proc pa_mainloop_free;
  6099. ma_proc pa_mainloop_quit;
  6100. ma_proc pa_mainloop_get_api;
  6101. ma_proc pa_mainloop_iterate;
  6102. ma_proc pa_mainloop_wakeup;
  6103. ma_proc pa_threaded_mainloop_new;
  6104. ma_proc pa_threaded_mainloop_free;
  6105. ma_proc pa_threaded_mainloop_start;
  6106. ma_proc pa_threaded_mainloop_stop;
  6107. ma_proc pa_threaded_mainloop_lock;
  6108. ma_proc pa_threaded_mainloop_unlock;
  6109. ma_proc pa_threaded_mainloop_wait;
  6110. ma_proc pa_threaded_mainloop_signal;
  6111. ma_proc pa_threaded_mainloop_accept;
  6112. ma_proc pa_threaded_mainloop_get_retval;
  6113. ma_proc pa_threaded_mainloop_get_api;
  6114. ma_proc pa_threaded_mainloop_in_thread;
  6115. ma_proc pa_threaded_mainloop_set_name;
  6116. ma_proc pa_context_new;
  6117. ma_proc pa_context_unref;
  6118. ma_proc pa_context_connect;
  6119. ma_proc pa_context_disconnect;
  6120. ma_proc pa_context_set_state_callback;
  6121. ma_proc pa_context_get_state;
  6122. ma_proc pa_context_get_sink_info_list;
  6123. ma_proc pa_context_get_source_info_list;
  6124. ma_proc pa_context_get_sink_info_by_name;
  6125. ma_proc pa_context_get_source_info_by_name;
  6126. ma_proc pa_operation_unref;
  6127. ma_proc pa_operation_get_state;
  6128. ma_proc pa_channel_map_init_extend;
  6129. ma_proc pa_channel_map_valid;
  6130. ma_proc pa_channel_map_compatible;
  6131. ma_proc pa_stream_new;
  6132. ma_proc pa_stream_unref;
  6133. ma_proc pa_stream_connect_playback;
  6134. ma_proc pa_stream_connect_record;
  6135. ma_proc pa_stream_disconnect;
  6136. ma_proc pa_stream_get_state;
  6137. ma_proc pa_stream_get_sample_spec;
  6138. ma_proc pa_stream_get_channel_map;
  6139. ma_proc pa_stream_get_buffer_attr;
  6140. ma_proc pa_stream_set_buffer_attr;
  6141. ma_proc pa_stream_get_device_name;
  6142. ma_proc pa_stream_set_write_callback;
  6143. ma_proc pa_stream_set_read_callback;
  6144. ma_proc pa_stream_set_suspended_callback;
  6145. ma_proc pa_stream_set_moved_callback;
  6146. ma_proc pa_stream_is_suspended;
  6147. ma_proc pa_stream_flush;
  6148. ma_proc pa_stream_drain;
  6149. ma_proc pa_stream_is_corked;
  6150. ma_proc pa_stream_cork;
  6151. ma_proc pa_stream_trigger;
  6152. ma_proc pa_stream_begin_write;
  6153. ma_proc pa_stream_write;
  6154. ma_proc pa_stream_peek;
  6155. ma_proc pa_stream_drop;
  6156. ma_proc pa_stream_writable_size;
  6157. ma_proc pa_stream_readable_size;
  6158. /*pa_mainloop**/ ma_ptr pMainLoop;
  6159. /*pa_context**/ ma_ptr pPulseContext;
  6160. char* pApplicationName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
  6161. char* pServerName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
  6162. } pulse;
  6163. #endif
  6164. #ifdef MA_SUPPORT_JACK
  6165. struct
  6166. {
  6167. ma_handle jackSO;
  6168. ma_proc jack_client_open;
  6169. ma_proc jack_client_close;
  6170. ma_proc jack_client_name_size;
  6171. ma_proc jack_set_process_callback;
  6172. ma_proc jack_set_buffer_size_callback;
  6173. ma_proc jack_on_shutdown;
  6174. ma_proc jack_get_sample_rate;
  6175. ma_proc jack_get_buffer_size;
  6176. ma_proc jack_get_ports;
  6177. ma_proc jack_activate;
  6178. ma_proc jack_deactivate;
  6179. ma_proc jack_connect;
  6180. ma_proc jack_port_register;
  6181. ma_proc jack_port_name;
  6182. ma_proc jack_port_get_buffer;
  6183. ma_proc jack_free;
  6184. char* pClientName;
  6185. ma_bool32 tryStartServer;
  6186. } jack;
  6187. #endif
  6188. #ifdef MA_SUPPORT_COREAUDIO
  6189. struct
  6190. {
  6191. ma_handle hCoreFoundation;
  6192. ma_proc CFStringGetCString;
  6193. ma_proc CFRelease;
  6194. ma_handle hCoreAudio;
  6195. ma_proc AudioObjectGetPropertyData;
  6196. ma_proc AudioObjectGetPropertyDataSize;
  6197. ma_proc AudioObjectSetPropertyData;
  6198. ma_proc AudioObjectAddPropertyListener;
  6199. ma_proc AudioObjectRemovePropertyListener;
  6200. ma_handle hAudioUnit; /* Could possibly be set to AudioToolbox on later versions of macOS. */
  6201. ma_proc AudioComponentFindNext;
  6202. ma_proc AudioComponentInstanceDispose;
  6203. ma_proc AudioComponentInstanceNew;
  6204. ma_proc AudioOutputUnitStart;
  6205. ma_proc AudioOutputUnitStop;
  6206. ma_proc AudioUnitAddPropertyListener;
  6207. ma_proc AudioUnitGetPropertyInfo;
  6208. ma_proc AudioUnitGetProperty;
  6209. ma_proc AudioUnitSetProperty;
  6210. ma_proc AudioUnitInitialize;
  6211. ma_proc AudioUnitRender;
  6212. /*AudioComponent*/ ma_ptr component;
  6213. 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(). */
  6214. } coreaudio;
  6215. #endif
  6216. #ifdef MA_SUPPORT_SNDIO
  6217. struct
  6218. {
  6219. ma_handle sndioSO;
  6220. ma_proc sio_open;
  6221. ma_proc sio_close;
  6222. ma_proc sio_setpar;
  6223. ma_proc sio_getpar;
  6224. ma_proc sio_getcap;
  6225. ma_proc sio_start;
  6226. ma_proc sio_stop;
  6227. ma_proc sio_read;
  6228. ma_proc sio_write;
  6229. ma_proc sio_onmove;
  6230. ma_proc sio_nfds;
  6231. ma_proc sio_pollfd;
  6232. ma_proc sio_revents;
  6233. ma_proc sio_eof;
  6234. ma_proc sio_setvol;
  6235. ma_proc sio_onvol;
  6236. ma_proc sio_initpar;
  6237. } sndio;
  6238. #endif
  6239. #ifdef MA_SUPPORT_AUDIO4
  6240. struct
  6241. {
  6242. int _unused;
  6243. } audio4;
  6244. #endif
  6245. #ifdef MA_SUPPORT_OSS
  6246. struct
  6247. {
  6248. int versionMajor;
  6249. int versionMinor;
  6250. } oss;
  6251. #endif
  6252. #ifdef MA_SUPPORT_AAUDIO
  6253. struct
  6254. {
  6255. ma_handle hAAudio; /* libaaudio.so */
  6256. ma_proc AAudio_createStreamBuilder;
  6257. ma_proc AAudioStreamBuilder_delete;
  6258. ma_proc AAudioStreamBuilder_setDeviceId;
  6259. ma_proc AAudioStreamBuilder_setDirection;
  6260. ma_proc AAudioStreamBuilder_setSharingMode;
  6261. ma_proc AAudioStreamBuilder_setFormat;
  6262. ma_proc AAudioStreamBuilder_setChannelCount;
  6263. ma_proc AAudioStreamBuilder_setSampleRate;
  6264. ma_proc AAudioStreamBuilder_setBufferCapacityInFrames;
  6265. ma_proc AAudioStreamBuilder_setFramesPerDataCallback;
  6266. ma_proc AAudioStreamBuilder_setDataCallback;
  6267. ma_proc AAudioStreamBuilder_setErrorCallback;
  6268. ma_proc AAudioStreamBuilder_setPerformanceMode;
  6269. ma_proc AAudioStreamBuilder_setUsage;
  6270. ma_proc AAudioStreamBuilder_setContentType;
  6271. ma_proc AAudioStreamBuilder_setInputPreset;
  6272. ma_proc AAudioStreamBuilder_setAllowedCapturePolicy;
  6273. ma_proc AAudioStreamBuilder_openStream;
  6274. ma_proc AAudioStream_close;
  6275. ma_proc AAudioStream_getState;
  6276. ma_proc AAudioStream_waitForStateChange;
  6277. ma_proc AAudioStream_getFormat;
  6278. ma_proc AAudioStream_getChannelCount;
  6279. ma_proc AAudioStream_getSampleRate;
  6280. ma_proc AAudioStream_getBufferCapacityInFrames;
  6281. ma_proc AAudioStream_getFramesPerDataCallback;
  6282. ma_proc AAudioStream_getFramesPerBurst;
  6283. ma_proc AAudioStream_requestStart;
  6284. ma_proc AAudioStream_requestStop;
  6285. ma_device_job_thread jobThread; /* For processing operations outside of the error callback, specifically device disconnections and rerouting. */
  6286. } aaudio;
  6287. #endif
  6288. #ifdef MA_SUPPORT_OPENSL
  6289. struct
  6290. {
  6291. ma_handle libOpenSLES;
  6292. ma_handle SL_IID_ENGINE;
  6293. ma_handle SL_IID_AUDIOIODEVICECAPABILITIES;
  6294. ma_handle SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  6295. ma_handle SL_IID_RECORD;
  6296. ma_handle SL_IID_PLAY;
  6297. ma_handle SL_IID_OUTPUTMIX;
  6298. ma_handle SL_IID_ANDROIDCONFIGURATION;
  6299. ma_proc slCreateEngine;
  6300. } opensl;
  6301. #endif
  6302. #ifdef MA_SUPPORT_WEBAUDIO
  6303. struct
  6304. {
  6305. int _unused;
  6306. } webaudio;
  6307. #endif
  6308. #ifdef MA_SUPPORT_NULL
  6309. struct
  6310. {
  6311. int _unused;
  6312. } null_backend;
  6313. #endif
  6314. };
  6315. union
  6316. {
  6317. #if defined(MA_WIN32)
  6318. struct
  6319. {
  6320. /*HMODULE*/ ma_handle hOle32DLL;
  6321. ma_proc CoInitialize;
  6322. ma_proc CoInitializeEx;
  6323. ma_proc CoUninitialize;
  6324. ma_proc CoCreateInstance;
  6325. ma_proc CoTaskMemFree;
  6326. ma_proc PropVariantClear;
  6327. ma_proc StringFromGUID2;
  6328. /*HMODULE*/ ma_handle hUser32DLL;
  6329. ma_proc GetForegroundWindow;
  6330. ma_proc GetDesktopWindow;
  6331. /*HMODULE*/ ma_handle hAdvapi32DLL;
  6332. ma_proc RegOpenKeyExA;
  6333. ma_proc RegCloseKey;
  6334. ma_proc RegQueryValueExA;
  6335. /*HRESULT*/ long CoInitializeResult;
  6336. } win32;
  6337. #endif
  6338. #ifdef MA_POSIX
  6339. struct
  6340. {
  6341. int _unused;
  6342. } posix;
  6343. #endif
  6344. int _unused;
  6345. };
  6346. };
  6347. struct ma_device
  6348. {
  6349. ma_context* pContext;
  6350. ma_device_type type;
  6351. ma_uint32 sampleRate;
  6352. 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. */
  6353. ma_device_data_proc onData; /* Set once at initialization time and should not be changed after. */
  6354. ma_device_notification_proc onNotification; /* Set once at initialization time and should not be changed after. */
  6355. ma_stop_proc onStop; /* DEPRECATED. Use the notification callback instead. Set once at initialization time and should not be changed after. */
  6356. void* pUserData; /* Application defined data. */
  6357. ma_mutex startStopLock;
  6358. ma_event wakeupEvent;
  6359. ma_event startEvent;
  6360. ma_event stopEvent;
  6361. ma_thread thread;
  6362. ma_result workResult; /* This is set by the worker thread after it's finished doing a job. */
  6363. 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(). */
  6364. ma_bool8 noPreSilencedOutputBuffer;
  6365. ma_bool8 noClip;
  6366. ma_bool8 noDisableDenormals;
  6367. ma_bool8 noFixedSizedCallback;
  6368. ma_atomic_float masterVolumeFactor; /* Linear 0..1. Can be read and written simultaneously by different threads. Must be used atomically. */
  6369. ma_duplex_rb duplexRB; /* Intermediary buffer for duplex device on asynchronous backends. */
  6370. struct
  6371. {
  6372. ma_resample_algorithm algorithm;
  6373. ma_resampling_backend_vtable* pBackendVTable;
  6374. void* pBackendUserData;
  6375. struct
  6376. {
  6377. ma_uint32 lpfOrder;
  6378. } linear;
  6379. } resampling;
  6380. struct
  6381. {
  6382. ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
  6383. 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. */
  6384. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
  6385. ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
  6386. ma_format format;
  6387. ma_uint32 channels;
  6388. ma_channel channelMap[MA_MAX_CHANNELS];
  6389. ma_format internalFormat;
  6390. ma_uint32 internalChannels;
  6391. ma_uint32 internalSampleRate;
  6392. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  6393. ma_uint32 internalPeriodSizeInFrames;
  6394. ma_uint32 internalPeriods;
  6395. ma_channel_mix_mode channelMixMode;
  6396. ma_bool32 calculateLFEFromSpatialChannels;
  6397. ma_data_converter converter;
  6398. void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
  6399. ma_uint32 intermediaryBufferCap;
  6400. ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
  6401. void* pInputCache; /* In external format. Can be null. */
  6402. ma_uint64 inputCacheCap;
  6403. ma_uint64 inputCacheConsumed;
  6404. ma_uint64 inputCacheRemaining;
  6405. } playback;
  6406. struct
  6407. {
  6408. ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
  6409. 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. */
  6410. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
  6411. ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
  6412. ma_format format;
  6413. ma_uint32 channels;
  6414. ma_channel channelMap[MA_MAX_CHANNELS];
  6415. ma_format internalFormat;
  6416. ma_uint32 internalChannels;
  6417. ma_uint32 internalSampleRate;
  6418. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  6419. ma_uint32 internalPeriodSizeInFrames;
  6420. ma_uint32 internalPeriods;
  6421. ma_channel_mix_mode channelMixMode;
  6422. ma_bool32 calculateLFEFromSpatialChannels;
  6423. ma_data_converter converter;
  6424. void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
  6425. ma_uint32 intermediaryBufferCap;
  6426. ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
  6427. } capture;
  6428. union
  6429. {
  6430. #ifdef MA_SUPPORT_WASAPI
  6431. struct
  6432. {
  6433. /*IAudioClient**/ ma_ptr pAudioClientPlayback;
  6434. /*IAudioClient**/ ma_ptr pAudioClientCapture;
  6435. /*IAudioRenderClient**/ ma_ptr pRenderClient;
  6436. /*IAudioCaptureClient**/ ma_ptr pCaptureClient;
  6437. /*IMMDeviceEnumerator**/ ma_ptr pDeviceEnumerator; /* Used for IMMNotificationClient notifications. Required for detecting default device changes. */
  6438. ma_IMMNotificationClient notificationClient;
  6439. /*HANDLE*/ ma_handle hEventPlayback; /* Auto reset. Initialized to signaled. */
  6440. /*HANDLE*/ ma_handle hEventCapture; /* Auto reset. Initialized to unsignaled. */
  6441. 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. */
  6442. ma_uint32 actualBufferSizeInFramesCapture;
  6443. ma_uint32 originalPeriodSizeInFrames;
  6444. ma_uint32 originalPeriodSizeInMilliseconds;
  6445. ma_uint32 originalPeriods;
  6446. ma_performance_profile originalPerformanceProfile;
  6447. ma_uint32 periodSizeInFramesPlayback;
  6448. ma_uint32 periodSizeInFramesCapture;
  6449. void* pMappedBufferCapture;
  6450. ma_uint32 mappedBufferCaptureCap;
  6451. ma_uint32 mappedBufferCaptureLen;
  6452. void* pMappedBufferPlayback;
  6453. ma_uint32 mappedBufferPlaybackCap;
  6454. ma_uint32 mappedBufferPlaybackLen;
  6455. ma_atomic_bool32 isStartedCapture; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
  6456. ma_atomic_bool32 isStartedPlayback; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
  6457. ma_uint32 loopbackProcessID;
  6458. ma_bool8 loopbackProcessExclude;
  6459. ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
  6460. ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
  6461. ma_bool8 noHardwareOffloading;
  6462. ma_bool8 allowCaptureAutoStreamRouting;
  6463. ma_bool8 allowPlaybackAutoStreamRouting;
  6464. ma_bool8 isDetachedPlayback;
  6465. ma_bool8 isDetachedCapture;
  6466. ma_wasapi_usage usage;
  6467. void* hAvrtHandle;
  6468. ma_mutex rerouteLock;
  6469. } wasapi;
  6470. #endif
  6471. #ifdef MA_SUPPORT_DSOUND
  6472. struct
  6473. {
  6474. /*LPDIRECTSOUND*/ ma_ptr pPlayback;
  6475. /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackPrimaryBuffer;
  6476. /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackBuffer;
  6477. /*LPDIRECTSOUNDCAPTURE*/ ma_ptr pCapture;
  6478. /*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
  6479. } dsound;
  6480. #endif
  6481. #ifdef MA_SUPPORT_WINMM
  6482. struct
  6483. {
  6484. /*HWAVEOUT*/ ma_handle hDevicePlayback;
  6485. /*HWAVEIN*/ ma_handle hDeviceCapture;
  6486. /*HANDLE*/ ma_handle hEventPlayback;
  6487. /*HANDLE*/ ma_handle hEventCapture;
  6488. ma_uint32 fragmentSizeInFrames;
  6489. ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
  6490. ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
  6491. ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
  6492. ma_uint32 headerFramesConsumedCapture; /* ^^^ */
  6493. /*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
  6494. /*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
  6495. ma_uint8* pIntermediaryBufferPlayback;
  6496. ma_uint8* pIntermediaryBufferCapture;
  6497. ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
  6498. } winmm;
  6499. #endif
  6500. #ifdef MA_SUPPORT_ALSA
  6501. struct
  6502. {
  6503. /*snd_pcm_t**/ ma_ptr pPCMPlayback;
  6504. /*snd_pcm_t**/ ma_ptr pPCMCapture;
  6505. /*struct pollfd**/ void* pPollDescriptorsPlayback;
  6506. /*struct pollfd**/ void* pPollDescriptorsCapture;
  6507. int pollDescriptorCountPlayback;
  6508. int pollDescriptorCountCapture;
  6509. int wakeupfdPlayback; /* eventfd for waking up from poll() when the playback device is stopped. */
  6510. int wakeupfdCapture; /* eventfd for waking up from poll() when the capture device is stopped. */
  6511. ma_bool8 isUsingMMapPlayback;
  6512. ma_bool8 isUsingMMapCapture;
  6513. } alsa;
  6514. #endif
  6515. #ifdef MA_SUPPORT_PULSEAUDIO
  6516. struct
  6517. {
  6518. /*pa_mainloop**/ ma_ptr pMainLoop;
  6519. /*pa_context**/ ma_ptr pPulseContext;
  6520. /*pa_stream**/ ma_ptr pStreamPlayback;
  6521. /*pa_stream**/ ma_ptr pStreamCapture;
  6522. } pulse;
  6523. #endif
  6524. #ifdef MA_SUPPORT_JACK
  6525. struct
  6526. {
  6527. /*jack_client_t**/ ma_ptr pClient;
  6528. /*jack_port_t**/ ma_ptr* ppPortsPlayback;
  6529. /*jack_port_t**/ ma_ptr* ppPortsCapture;
  6530. float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */
  6531. float* pIntermediaryBufferCapture;
  6532. } jack;
  6533. #endif
  6534. #ifdef MA_SUPPORT_COREAUDIO
  6535. struct
  6536. {
  6537. ma_uint32 deviceObjectIDPlayback;
  6538. ma_uint32 deviceObjectIDCapture;
  6539. /*AudioUnit*/ ma_ptr audioUnitPlayback;
  6540. /*AudioUnit*/ ma_ptr audioUnitCapture;
  6541. /*AudioBufferList**/ ma_ptr pAudioBufferList; /* Only used for input devices. */
  6542. ma_uint32 audioBufferCapInFrames; /* Only used for input devices. The capacity in frames of each buffer in pAudioBufferList. */
  6543. ma_event stopEvent;
  6544. ma_uint32 originalPeriodSizeInFrames;
  6545. ma_uint32 originalPeriodSizeInMilliseconds;
  6546. ma_uint32 originalPeriods;
  6547. ma_performance_profile originalPerformanceProfile;
  6548. ma_bool32 isDefaultPlaybackDevice;
  6549. ma_bool32 isDefaultCaptureDevice;
  6550. ma_bool32 isSwitchingPlaybackDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
  6551. ma_bool32 isSwitchingCaptureDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
  6552. void* pNotificationHandler; /* Only used on mobile platforms. Obj-C object for handling route changes. */
  6553. } coreaudio;
  6554. #endif
  6555. #ifdef MA_SUPPORT_SNDIO
  6556. struct
  6557. {
  6558. ma_ptr handlePlayback;
  6559. ma_ptr handleCapture;
  6560. ma_bool32 isStartedPlayback;
  6561. ma_bool32 isStartedCapture;
  6562. } sndio;
  6563. #endif
  6564. #ifdef MA_SUPPORT_AUDIO4
  6565. struct
  6566. {
  6567. int fdPlayback;
  6568. int fdCapture;
  6569. } audio4;
  6570. #endif
  6571. #ifdef MA_SUPPORT_OSS
  6572. struct
  6573. {
  6574. int fdPlayback;
  6575. int fdCapture;
  6576. } oss;
  6577. #endif
  6578. #ifdef MA_SUPPORT_AAUDIO
  6579. struct
  6580. {
  6581. /*AAudioStream**/ ma_ptr pStreamPlayback;
  6582. /*AAudioStream**/ ma_ptr pStreamCapture;
  6583. ma_aaudio_usage usage;
  6584. ma_aaudio_content_type contentType;
  6585. ma_aaudio_input_preset inputPreset;
  6586. ma_aaudio_allowed_capture_policy allowedCapturePolicy;
  6587. ma_bool32 noAutoStartAfterReroute;
  6588. } aaudio;
  6589. #endif
  6590. #ifdef MA_SUPPORT_OPENSL
  6591. struct
  6592. {
  6593. /*SLObjectItf*/ ma_ptr pOutputMixObj;
  6594. /*SLOutputMixItf*/ ma_ptr pOutputMix;
  6595. /*SLObjectItf*/ ma_ptr pAudioPlayerObj;
  6596. /*SLPlayItf*/ ma_ptr pAudioPlayer;
  6597. /*SLObjectItf*/ ma_ptr pAudioRecorderObj;
  6598. /*SLRecordItf*/ ma_ptr pAudioRecorder;
  6599. /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueuePlayback;
  6600. /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture;
  6601. ma_bool32 isDrainingCapture;
  6602. ma_bool32 isDrainingPlayback;
  6603. ma_uint32 currentBufferIndexPlayback;
  6604. ma_uint32 currentBufferIndexCapture;
  6605. ma_uint8* pBufferPlayback; /* This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. */
  6606. ma_uint8* pBufferCapture;
  6607. } opensl;
  6608. #endif
  6609. #ifdef MA_SUPPORT_WEBAUDIO
  6610. struct
  6611. {
  6612. /* AudioWorklets path. */
  6613. /* EMSCRIPTEN_WEBAUDIO_T */ int audioContext;
  6614. /* EMSCRIPTEN_WEBAUDIO_T */ int audioWorklet;
  6615. float* pIntermediaryBuffer;
  6616. void* pStackBuffer;
  6617. ma_result initResult; /* Set to MA_BUSY while initialization is in progress. */
  6618. int deviceIndex; /* We store the device in a list on the JavaScript side. This is used to map our C object to the JS object. */
  6619. } webaudio;
  6620. #endif
  6621. #ifdef MA_SUPPORT_NULL
  6622. struct
  6623. {
  6624. ma_thread deviceThread;
  6625. ma_event operationEvent;
  6626. ma_event operationCompletionEvent;
  6627. ma_semaphore operationSemaphore;
  6628. ma_uint32 operation;
  6629. ma_result operationResult;
  6630. ma_timer timer;
  6631. double priorRunTime;
  6632. ma_uint32 currentPeriodFramesRemainingPlayback;
  6633. ma_uint32 currentPeriodFramesRemainingCapture;
  6634. ma_uint64 lastProcessedFramePlayback;
  6635. ma_uint64 lastProcessedFrameCapture;
  6636. ma_atomic_bool32 isStarted; /* Read and written by multiple threads. Must be used atomically, and must be 32-bit for compiler compatibility. */
  6637. } null_device;
  6638. #endif
  6639. };
  6640. };
  6641. #if defined(_MSC_VER) && !defined(__clang__)
  6642. #pragma warning(pop)
  6643. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  6644. #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  6645. #endif
  6646. /*
  6647. Initializes a `ma_context_config` object.
  6648. Return Value
  6649. ------------
  6650. A `ma_context_config` initialized to defaults.
  6651. Remarks
  6652. -------
  6653. 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
  6654. is updated and new members are added to `ma_context_config`. It also sets logical defaults.
  6655. You can override members of the returned object by changing it's members directly.
  6656. See Also
  6657. --------
  6658. ma_context_init()
  6659. */
  6660. MA_API ma_context_config ma_context_config_init(void);
  6661. /*
  6662. Initializes a context.
  6663. 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
  6664. device. There is one context to many devices, and a device is created from a context. A context is required to enumerate devices.
  6665. Parameters
  6666. ----------
  6667. backends (in, optional)
  6668. A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
  6669. backendCount (in, optional)
  6670. The number of items in `backend`. Ignored if `backend` is NULL.
  6671. pConfig (in, optional)
  6672. The context configuration.
  6673. pContext (in)
  6674. A pointer to the context object being initialized.
  6675. Return Value
  6676. ------------
  6677. MA_SUCCESS if successful; any other error code otherwise.
  6678. Thread Safety
  6679. -------------
  6680. Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
  6681. Remarks
  6682. -------
  6683. When `backends` is NULL, the default priority order will be used. Below is a list of backends in priority order:
  6684. |-------------|-----------------------|--------------------------------------------------------|
  6685. | Name | Enum Name | Supported Operating Systems |
  6686. |-------------|-----------------------|--------------------------------------------------------|
  6687. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  6688. | DirectSound | ma_backend_dsound | Windows XP+ |
  6689. | WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
  6690. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  6691. | ALSA | ma_backend_alsa | Linux |
  6692. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  6693. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  6694. | sndio | ma_backend_sndio | OpenBSD |
  6695. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  6696. | OSS | ma_backend_oss | FreeBSD |
  6697. | AAudio | ma_backend_aaudio | Android 8+ |
  6698. | OpenSL|ES | ma_backend_opensl | Android (API level 16+) |
  6699. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  6700. | Null | ma_backend_null | Cross Platform (not used on Web) |
  6701. |-------------|-----------------------|--------------------------------------------------------|
  6702. The context can be configured via the `pConfig` argument. The config object is initialized with `ma_context_config_init()`. Individual configuration settings
  6703. can then be set directly on the structure. Below are the members of the `ma_context_config` object.
  6704. pLog
  6705. A pointer to the `ma_log` to post log messages to. Can be NULL if the application does not
  6706. require logging. See the `ma_log` API for details on how to use the logging system.
  6707. threadPriority
  6708. The desired priority to use for the audio thread. Allowable values include the following:
  6709. |--------------------------------------|
  6710. | Thread Priority |
  6711. |--------------------------------------|
  6712. | ma_thread_priority_idle |
  6713. | ma_thread_priority_lowest |
  6714. | ma_thread_priority_low |
  6715. | ma_thread_priority_normal |
  6716. | ma_thread_priority_high |
  6717. | ma_thread_priority_highest (default) |
  6718. | ma_thread_priority_realtime |
  6719. | ma_thread_priority_default |
  6720. |--------------------------------------|
  6721. threadStackSize
  6722. The desired size of the stack for the audio thread. Defaults to the operating system's default.
  6723. pUserData
  6724. A pointer to application-defined data. This can be accessed from the context object directly such as `context.pUserData`.
  6725. allocationCallbacks
  6726. Structure containing custom allocation callbacks. Leaving this at defaults will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. These allocation
  6727. callbacks will be used for anything tied to the context, including devices.
  6728. alsa.useVerboseDeviceEnumeration
  6729. ALSA will typically enumerate many different devices which can be intrusive and not user-friendly. To combat this, miniaudio will enumerate only unique
  6730. card/device pairs by default. The problem with this is that you lose a bit of flexibility and control. Setting alsa.useVerboseDeviceEnumeration makes
  6731. it so the ALSA backend includes all devices. Defaults to false.
  6732. pulse.pApplicationName
  6733. PulseAudio only. The application name to use when initializing the PulseAudio context with `pa_context_new()`.
  6734. pulse.pServerName
  6735. PulseAudio only. The name of the server to connect to with `pa_context_connect()`.
  6736. pulse.tryAutoSpawn
  6737. 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
  6738. 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
  6739. intrusive for the end user.
  6740. coreaudio.sessionCategory
  6741. iOS only. The session category to use for the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
  6742. |-----------------------------------------|-------------------------------------|
  6743. | miniaudio Token | Core Audio Token |
  6744. |-----------------------------------------|-------------------------------------|
  6745. | ma_ios_session_category_ambient | AVAudioSessionCategoryAmbient |
  6746. | ma_ios_session_category_solo_ambient | AVAudioSessionCategorySoloAmbient |
  6747. | ma_ios_session_category_playback | AVAudioSessionCategoryPlayback |
  6748. | ma_ios_session_category_record | AVAudioSessionCategoryRecord |
  6749. | ma_ios_session_category_play_and_record | AVAudioSessionCategoryPlayAndRecord |
  6750. | ma_ios_session_category_multi_route | AVAudioSessionCategoryMultiRoute |
  6751. | ma_ios_session_category_none | AVAudioSessionCategoryAmbient |
  6752. | ma_ios_session_category_default | AVAudioSessionCategoryAmbient |
  6753. |-----------------------------------------|-------------------------------------|
  6754. coreaudio.sessionCategoryOptions
  6755. iOS only. Session category options to use with the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
  6756. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6757. | miniaudio Token | Core Audio Token |
  6758. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6759. | ma_ios_session_category_option_mix_with_others | AVAudioSessionCategoryOptionMixWithOthers |
  6760. | ma_ios_session_category_option_duck_others | AVAudioSessionCategoryOptionDuckOthers |
  6761. | ma_ios_session_category_option_allow_bluetooth | AVAudioSessionCategoryOptionAllowBluetooth |
  6762. | ma_ios_session_category_option_default_to_speaker | AVAudioSessionCategoryOptionDefaultToSpeaker |
  6763. | ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers |
  6764. | ma_ios_session_category_option_allow_bluetooth_a2dp | AVAudioSessionCategoryOptionAllowBluetoothA2DP |
  6765. | ma_ios_session_category_option_allow_air_play | AVAudioSessionCategoryOptionAllowAirPlay |
  6766. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6767. coreaudio.noAudioSessionActivate
  6768. iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization.
  6769. coreaudio.noAudioSessionDeactivate
  6770. iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization.
  6771. jack.pClientName
  6772. The name of the client to pass to `jack_client_open()`.
  6773. jack.tryStartServer
  6774. Whether or not to try auto-starting the JACK server. Defaults to false.
  6775. 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
  6776. relevant backends every time it's initialized.
  6777. 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
  6778. reason for this is that a pointer to the context is stored in the `ma_device` structure.
  6779. Example 1 - Default Initialization
  6780. ----------------------------------
  6781. The example below shows how to initialize the context using the default configuration.
  6782. ```c
  6783. ma_context context;
  6784. ma_result result = ma_context_init(NULL, 0, NULL, &context);
  6785. if (result != MA_SUCCESS) {
  6786. // Error.
  6787. }
  6788. ```
  6789. Example 2 - Custom Configuration
  6790. --------------------------------
  6791. The example below shows how to initialize the context using custom backend priorities and a custom configuration. In this hypothetical example, the program
  6792. 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
  6793. want an error to be returned if no valid backend is available which they achieve by excluding the Null backend.
  6794. 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.
  6795. ```c
  6796. ma_backend backends[] = {
  6797. ma_backend_alsa,
  6798. ma_backend_pulseaudio,
  6799. ma_backend_wasapi,
  6800. ma_backend_dsound
  6801. };
  6802. ma_log log;
  6803. ma_log_init(&log);
  6804. ma_log_register_callback(&log, ma_log_callback_init(my_log_callbac, pMyLogUserData));
  6805. ma_context_config config = ma_context_config_init();
  6806. config.pLog = &log; // Specify a custom log object in the config so any logs that are posted from ma_context_init() are captured.
  6807. ma_context context;
  6808. ma_result result = ma_context_init(backends, sizeof(backends)/sizeof(backends[0]), &config, &context);
  6809. if (result != MA_SUCCESS) {
  6810. // Error.
  6811. if (result == MA_NO_BACKEND) {
  6812. // Couldn't find an appropriate backend.
  6813. }
  6814. }
  6815. // You could also attach a log callback post-initialization:
  6816. ma_log_register_callback(ma_context_get_log(&context), ma_log_callback_init(my_log_callback, pMyLogUserData));
  6817. ```
  6818. See Also
  6819. --------
  6820. ma_context_config_init()
  6821. ma_context_uninit()
  6822. */
  6823. MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext);
  6824. /*
  6825. Uninitializes a context.
  6826. Return Value
  6827. ------------
  6828. MA_SUCCESS if successful; any other error code otherwise.
  6829. Thread Safety
  6830. -------------
  6831. Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
  6832. Remarks
  6833. -------
  6834. Results are undefined if you call this while any device created by this context is still active.
  6835. See Also
  6836. --------
  6837. ma_context_init()
  6838. */
  6839. MA_API ma_result ma_context_uninit(ma_context* pContext);
  6840. /*
  6841. Retrieves the size of the ma_context object.
  6842. This is mainly for the purpose of bindings to know how much memory to allocate.
  6843. */
  6844. MA_API size_t ma_context_sizeof(void);
  6845. /*
  6846. Retrieves a pointer to the log object associated with this context.
  6847. Remarks
  6848. -------
  6849. Pass the returned pointer to `ma_log_post()`, `ma_log_postv()` or `ma_log_postf()` to post a log
  6850. message.
  6851. You can attach your own logging callback to the log with `ma_log_register_callback()`
  6852. Return Value
  6853. ------------
  6854. A pointer to the `ma_log` object that the context uses to post log messages. If some error occurs,
  6855. NULL will be returned.
  6856. */
  6857. MA_API ma_log* ma_context_get_log(ma_context* pContext);
  6858. /*
  6859. Enumerates over every device (both playback and capture).
  6860. 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
  6861. an internal heap allocation, or it simply suits your code better.
  6862. 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
  6863. 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,
  6864. but don't call it from within the enumeration callback.
  6865. Returning false from the callback will stop enumeration. Returning true will continue enumeration.
  6866. Parameters
  6867. ----------
  6868. pContext (in)
  6869. A pointer to the context performing the enumeration.
  6870. callback (in)
  6871. The callback to fire for each enumerated device.
  6872. pUserData (in)
  6873. A pointer to application-defined data passed to the callback.
  6874. Return Value
  6875. ------------
  6876. MA_SUCCESS if successful; any other error code otherwise.
  6877. Thread Safety
  6878. -------------
  6879. Safe. This is guarded using a simple mutex lock.
  6880. Remarks
  6881. -------
  6882. Do _not_ assume the first enumerated device of a given type is the default device.
  6883. Some backends and platforms may only support default playback and capture devices.
  6884. 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,
  6885. do not try to call `ma_context_get_device_info()` from within the callback.
  6886. Consider using `ma_context_get_devices()` for a simpler and safer API, albeit at the expense of an internal heap allocation.
  6887. Example 1 - Simple Enumeration
  6888. ------------------------------
  6889. ma_bool32 ma_device_enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
  6890. {
  6891. printf("Device Name: %s\n", pInfo->name);
  6892. return MA_TRUE;
  6893. }
  6894. ma_result result = ma_context_enumerate_devices(&context, my_device_enum_callback, pMyUserData);
  6895. if (result != MA_SUCCESS) {
  6896. // Error.
  6897. }
  6898. See Also
  6899. --------
  6900. ma_context_get_devices()
  6901. */
  6902. MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
  6903. /*
  6904. Retrieves basic information about every active playback and/or capture device.
  6905. This function will allocate memory internally for the device lists and return a pointer to them through the `ppPlaybackDeviceInfos` and `ppCaptureDeviceInfos`
  6906. 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.
  6907. Parameters
  6908. ----------
  6909. pContext (in)
  6910. A pointer to the context performing the enumeration.
  6911. ppPlaybackDeviceInfos (out)
  6912. A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for playback devices.
  6913. pPlaybackDeviceCount (out)
  6914. A pointer to an unsigned integer that will receive the number of playback devices.
  6915. ppCaptureDeviceInfos (out)
  6916. A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for capture devices.
  6917. pCaptureDeviceCount (out)
  6918. A pointer to an unsigned integer that will receive the number of capture devices.
  6919. Return Value
  6920. ------------
  6921. MA_SUCCESS if successful; any other error code otherwise.
  6922. Thread Safety
  6923. -------------
  6924. Unsafe. Since each call to this function invalidates the pointers from the previous call, you should not be calling this simultaneously across multiple
  6925. threads. Instead, you need to make a copy of the returned data with your own higher level synchronization.
  6926. Remarks
  6927. -------
  6928. It is _not_ safe to assume the first device in the list is the default device.
  6929. You can pass in NULL for the playback or capture lists in which case they'll be ignored.
  6930. 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.
  6931. See Also
  6932. --------
  6933. ma_context_get_devices()
  6934. */
  6935. 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);
  6936. /*
  6937. Retrieves information about a device of the given type, with the specified ID and share mode.
  6938. Parameters
  6939. ----------
  6940. pContext (in)
  6941. A pointer to the context performing the query.
  6942. deviceType (in)
  6943. The type of the device being queried. Must be either `ma_device_type_playback` or `ma_device_type_capture`.
  6944. pDeviceID (in)
  6945. The ID of the device being queried.
  6946. pDeviceInfo (out)
  6947. A pointer to the `ma_device_info` structure that will receive the device information.
  6948. Return Value
  6949. ------------
  6950. MA_SUCCESS if successful; any other error code otherwise.
  6951. Thread Safety
  6952. -------------
  6953. Safe. This is guarded using a simple mutex lock.
  6954. Remarks
  6955. -------
  6956. Do _not_ call this from within the `ma_context_enumerate_devices()` callback.
  6957. 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
  6958. 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
  6959. 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
  6960. the requested share mode is unsupported.
  6961. This leaves pDeviceInfo unmodified in the result of an error.
  6962. */
  6963. 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);
  6964. /*
  6965. Determines if the given context supports loopback mode.
  6966. Parameters
  6967. ----------
  6968. pContext (in)
  6969. A pointer to the context getting queried.
  6970. Return Value
  6971. ------------
  6972. MA_TRUE if the context supports loopback mode; MA_FALSE otherwise.
  6973. */
  6974. MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext);
  6975. /*
  6976. Initializes a device config with default settings.
  6977. Parameters
  6978. ----------
  6979. deviceType (in)
  6980. The type of the device this config is being initialized for. This must set to one of the following:
  6981. |-------------------------|
  6982. | Device Type |
  6983. |-------------------------|
  6984. | ma_device_type_playback |
  6985. | ma_device_type_capture |
  6986. | ma_device_type_duplex |
  6987. | ma_device_type_loopback |
  6988. |-------------------------|
  6989. Return Value
  6990. ------------
  6991. A new device config object with default settings. You will typically want to adjust the config after this function returns. See remarks.
  6992. Thread Safety
  6993. -------------
  6994. Safe.
  6995. Callback Safety
  6996. ---------------
  6997. Safe, but don't try initializing a device in a callback.
  6998. Remarks
  6999. -------
  7000. 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
  7001. 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
  7002. before initializing the device.
  7003. See `ma_device_init()` for details on specific configuration options.
  7004. Example 1 - Simple Configuration
  7005. --------------------------------
  7006. 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
  7007. 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
  7008. to the `ma_device_config` structure.
  7009. ```c
  7010. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  7011. config.playback.format = ma_format_f32;
  7012. config.playback.channels = 2;
  7013. config.sampleRate = 48000;
  7014. config.dataCallback = ma_data_callback;
  7015. config.pUserData = pMyUserData;
  7016. ```
  7017. See Also
  7018. --------
  7019. ma_device_init()
  7020. ma_device_init_ex()
  7021. */
  7022. MA_API ma_device_config ma_device_config_init(ma_device_type deviceType);
  7023. /*
  7024. Initializes a device.
  7025. 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
  7026. 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
  7027. 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
  7028. device is done via a callback which is fired by miniaudio at periodic time intervals.
  7029. 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
  7030. or milliseconds, whichever is more convenient. Generally speaking, the smaller the period, the lower the latency at the expense of higher CPU usage and
  7031. 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
  7032. 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
  7033. 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
  7034. backend is ultimately responsible for what it gives you. You cannot assume you will get exactly what you ask for.
  7035. 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
  7036. 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
  7037. 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.
  7038. Parameters
  7039. ----------
  7040. pContext (in, optional)
  7041. A pointer to the context that owns the device. This can be null, in which case it creates a default context internally.
  7042. pConfig (in)
  7043. A pointer to the device configuration. Cannot be null. See remarks for details.
  7044. pDevice (out)
  7045. A pointer to the device object being initialized.
  7046. Return Value
  7047. ------------
  7048. MA_SUCCESS if successful; any other error code otherwise.
  7049. Thread Safety
  7050. -------------
  7051. 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
  7052. calling this at the same time as `ma_device_uninit()`.
  7053. Callback Safety
  7054. ---------------
  7055. Unsafe. It is not safe to call this inside any callback.
  7056. Remarks
  7057. -------
  7058. Setting `pContext` to NULL will result in miniaudio creating a default context internally and is equivalent to passing in a context initialized like so:
  7059. ```c
  7060. ma_context_init(NULL, 0, NULL, &context);
  7061. ```
  7062. 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
  7063. device.pContext for the initialization of other devices.
  7064. The device can be configured via the `pConfig` argument. The config object is initialized with `ma_device_config_init()`. Individual configuration settings can
  7065. then be set directly on the structure. Below are the members of the `ma_device_config` object.
  7066. deviceType
  7067. Must be `ma_device_type_playback`, `ma_device_type_capture`, `ma_device_type_duplex` of `ma_device_type_loopback`.
  7068. sampleRate
  7069. 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.
  7070. periodSizeInFrames
  7071. 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
  7072. be used depending on the selected performance profile. This value affects latency. See below for details.
  7073. periodSizeInMilliseconds
  7074. 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
  7075. used depending on the selected performance profile. The value affects latency. See below for details.
  7076. periods
  7077. The number of periods making up the device's entire buffer. The total buffer size is `periodSizeInFrames` or `periodSizeInMilliseconds` multiplied by
  7078. this value. This is just a hint as backends will be the ones who ultimately decide how your periods will be configured.
  7079. performanceProfile
  7080. A hint to miniaudio as to the performance requirements of your program. Can be either `ma_performance_profile_low_latency` (default) or
  7081. `ma_performance_profile_conservative`. This mainly affects the size of default buffers and can usually be left at it's default value.
  7082. noPreSilencedOutputBuffer
  7083. 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
  7084. 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
  7085. callback will write to every sample in the output buffer, or if you are doing your own clearing.
  7086. noClip
  7087. When set to true, the contents of the output buffer are left alone after returning and it will be left up to the backend itself to decide whether or
  7088. not to clip. When set to false (default), the contents of the output buffer passed into the data callback will be clipped after returning. This only
  7089. applies when the playback sample format is f32.
  7090. noDisableDenormals
  7091. By default, miniaudio will disable denormals when the data callback is called. Setting this to true will prevent the disabling of denormals.
  7092. noFixedSizedCallback
  7093. 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
  7094. consistent frame count as specified by `periodSizeInFrames` or `periodSizeInMilliseconds`. When set to true, miniaudio will fire the callback with
  7095. whatever the backend requests, which could be anything.
  7096. dataCallback
  7097. The callback to fire whenever data is ready to be delivered to or from the device.
  7098. notificationCallback
  7099. The callback to fire when something has changed with the device, such as whether or not it has been started or stopped.
  7100. pUserData
  7101. The user data pointer to use with the device. You can access this directly from the device object like `device.pUserData`.
  7102. resampling.algorithm
  7103. The resampling algorithm to use when miniaudio needs to perform resampling between the rate specified by `sampleRate` and the device's native rate. The
  7104. default value is `ma_resample_algorithm_linear`, and the quality can be configured with `resampling.linear.lpfOrder`.
  7105. resampling.pBackendVTable
  7106. A pointer to an optional vtable that can be used for plugging in a custom resampler.
  7107. resampling.pBackendUserData
  7108. A pointer that will passed to callbacks in pBackendVTable.
  7109. resampling.linear.lpfOrder
  7110. 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
  7111. the value, the better the quality, in general. Setting this to 0 will disable low-pass filtering altogether. The maximum value is
  7112. `MA_MAX_FILTER_ORDER`. The default value is `min(4, MA_MAX_FILTER_ORDER)`.
  7113. playback.pDeviceID
  7114. 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
  7115. default playback device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
  7116. playback.format
  7117. 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
  7118. initialization from the device object directly with `device.playback.format`.
  7119. playback.channels
  7120. 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
  7121. from the device object directly with `device.playback.channels`.
  7122. playback.pChannelMap
  7123. 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
  7124. device object direct with `device.playback.pChannelMap`. When set, the buffer should contain `channels` items.
  7125. playback.shareMode
  7126. 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
  7127. 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
  7128. ma_share_mode_shared and reinitializing.
  7129. capture.pDeviceID
  7130. 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
  7131. default capture device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
  7132. capture.format
  7133. 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
  7134. initialization from the device object directly with `device.capture.format`.
  7135. capture.channels
  7136. 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
  7137. from the device object directly with `device.capture.channels`.
  7138. capture.pChannelMap
  7139. 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
  7140. device object direct with `device.capture.pChannelMap`. When set, the buffer should contain `channels` items.
  7141. capture.shareMode
  7142. 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
  7143. 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
  7144. ma_share_mode_shared and reinitializing.
  7145. wasapi.noAutoConvertSRC
  7146. WASAPI only. When set to true, disables WASAPI's automatic resampling and forces the use of miniaudio's resampler. Defaults to false.
  7147. wasapi.noDefaultQualitySRC
  7148. WASAPI only. Only used when `wasapi.noAutoConvertSRC` is set to false. When set to true, disables the use of `AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY`.
  7149. You should usually leave this set to false, which is the default.
  7150. wasapi.noAutoStreamRouting
  7151. WASAPI only. When set to true, disables automatic stream routing on the WASAPI backend. Defaults to false.
  7152. wasapi.noHardwareOffloading
  7153. WASAPI only. When set to true, disables the use of WASAPI's hardware offloading feature. Defaults to false.
  7154. alsa.noMMap
  7155. ALSA only. When set to true, disables MMap mode. Defaults to false.
  7156. alsa.noAutoFormat
  7157. ALSA only. When set to true, disables ALSA's automatic format conversion by including the SND_PCM_NO_AUTO_FORMAT flag. Defaults to false.
  7158. alsa.noAutoChannels
  7159. ALSA only. When set to true, disables ALSA's automatic channel conversion by including the SND_PCM_NO_AUTO_CHANNELS flag. Defaults to false.
  7160. alsa.noAutoResample
  7161. ALSA only. When set to true, disables ALSA's automatic resampling by including the SND_PCM_NO_AUTO_RESAMPLE flag. Defaults to false.
  7162. pulse.pStreamNamePlayback
  7163. PulseAudio only. Sets the stream name for playback.
  7164. pulse.pStreamNameCapture
  7165. PulseAudio only. Sets the stream name for capture.
  7166. coreaudio.allowNominalSampleRateChange
  7167. Core Audio only. Desktop only. When enabled, allows the sample rate of the device to be changed at the operating system level. This
  7168. 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
  7169. that is known to be natively supported by the hardware thereby avoiding the cost of resampling. When set to true, miniaudio will
  7170. find the closest match between the sample rate requested in the device config and the sample rates natively supported by the
  7171. hardware. When set to false, the sample rate currently set by the operating system will always be used.
  7172. opensl.streamType
  7173. OpenSL only. Explicitly sets the stream type. If left unset (`ma_opensl_stream_type_default`), the
  7174. stream type will be left unset. Think of this as the type of audio you're playing.
  7175. opensl.recordingPreset
  7176. OpenSL only. Explicitly sets the type of recording your program will be doing. When left
  7177. unset, the recording preset will be left unchanged.
  7178. aaudio.usage
  7179. AAudio only. Explicitly sets the nature of the audio the program will be consuming. When
  7180. left unset, the usage will be left unchanged.
  7181. aaudio.contentType
  7182. AAudio only. Sets the content type. When left unset, the content type will be left unchanged.
  7183. aaudio.inputPreset
  7184. AAudio only. Explicitly sets the type of recording your program will be doing. When left
  7185. unset, the input preset will be left unchanged.
  7186. aaudio.noAutoStartAfterReroute
  7187. AAudio only. Controls whether or not the device should be automatically restarted after a
  7188. stream reroute. When set to false (default) the device will be restarted automatically;
  7189. otherwise the device will be stopped.
  7190. Once initialized, the device's config is immutable. If you need to change the config you will need to initialize a new device.
  7191. After initializing the device it will be in a stopped state. To start it, use `ma_device_start()`.
  7192. If both `periodSizeInFrames` and `periodSizeInMilliseconds` are set to zero, it will default to `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY` or
  7193. `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE`, depending on whether or not `performanceProfile` is set to `ma_performance_profile_low_latency` or
  7194. `ma_performance_profile_conservative`.
  7195. 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
  7196. 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
  7197. 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,
  7198. 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.
  7199. Starting with Windows 10, miniaudio will use low-latency shared mode where possible which may make exclusive mode unnecessary.
  7200. 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
  7201. 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
  7202. on an optimized pass-through fast path. You can retrieve the format, channel count and sample rate by inspecting the `playback/capture.format`,
  7203. `playback/capture.channels` and `sampleRate` members of the device object.
  7204. 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
  7205. asking for permissions. Please refer to the official documentation for ActivateAudioInterfaceAsync() for more information.
  7206. ALSA Specific: When initializing the default device, requesting shared mode will try using the "dmix" device for playback and the "dsnoop" device for capture.
  7207. If these fail it will try falling back to the "hw" device.
  7208. Example 1 - Simple Initialization
  7209. ---------------------------------
  7210. 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
  7211. playback device this is usually all you need.
  7212. ```c
  7213. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  7214. config.playback.format = ma_format_f32;
  7215. config.playback.channels = 2;
  7216. config.sampleRate = 48000;
  7217. config.dataCallback = ma_data_callback;
  7218. config.pMyUserData = pMyUserData;
  7219. ma_device device;
  7220. ma_result result = ma_device_init(NULL, &config, &device);
  7221. if (result != MA_SUCCESS) {
  7222. // Error
  7223. }
  7224. ```
  7225. Example 2 - Advanced Initialization
  7226. -----------------------------------
  7227. 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
  7228. 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
  7229. enumeration.
  7230. ```c
  7231. ma_context context;
  7232. ma_result result = ma_context_init(NULL, 0, NULL, &context);
  7233. if (result != MA_SUCCESS) {
  7234. // Error
  7235. }
  7236. ma_device_info* pPlaybackDeviceInfos;
  7237. ma_uint32 playbackDeviceCount;
  7238. result = ma_context_get_devices(&context, &pPlaybackDeviceInfos, &playbackDeviceCount, NULL, NULL);
  7239. if (result != MA_SUCCESS) {
  7240. // Error
  7241. }
  7242. // ... choose a device from pPlaybackDeviceInfos ...
  7243. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  7244. config.playback.pDeviceID = pMyChosenDeviceID; // <-- Get this from the `id` member of one of the `ma_device_info` objects returned by ma_context_get_devices().
  7245. config.playback.format = ma_format_f32;
  7246. config.playback.channels = 2;
  7247. config.sampleRate = 48000;
  7248. config.dataCallback = ma_data_callback;
  7249. config.pUserData = pMyUserData;
  7250. config.periodSizeInMilliseconds = 10;
  7251. config.periods = 3;
  7252. ma_device device;
  7253. result = ma_device_init(&context, &config, &device);
  7254. if (result != MA_SUCCESS) {
  7255. // Error
  7256. }
  7257. ```
  7258. See Also
  7259. --------
  7260. ma_device_config_init()
  7261. ma_device_uninit()
  7262. ma_device_start()
  7263. ma_context_init()
  7264. ma_context_get_devices()
  7265. ma_context_enumerate_devices()
  7266. */
  7267. MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice);
  7268. /*
  7269. Initializes a device without a context, with extra parameters for controlling the configuration of the internal self-managed context.
  7270. 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
  7271. allows you to configure the internally created context.
  7272. Parameters
  7273. ----------
  7274. backends (in, optional)
  7275. A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
  7276. backendCount (in, optional)
  7277. The number of items in `backend`. Ignored if `backend` is NULL.
  7278. pContextConfig (in, optional)
  7279. The context configuration.
  7280. pConfig (in)
  7281. A pointer to the device configuration. Cannot be null. See remarks for details.
  7282. pDevice (out)
  7283. A pointer to the device object being initialized.
  7284. Return Value
  7285. ------------
  7286. MA_SUCCESS if successful; any other error code otherwise.
  7287. Thread Safety
  7288. -------------
  7289. 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
  7290. calling this at the same time as `ma_device_uninit()`.
  7291. Callback Safety
  7292. ---------------
  7293. Unsafe. It is not safe to call this inside any callback.
  7294. Remarks
  7295. -------
  7296. 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
  7297. your own context.
  7298. See the documentation for `ma_context_init()` for information on the different context configuration options.
  7299. See Also
  7300. --------
  7301. ma_device_init()
  7302. ma_device_uninit()
  7303. ma_device_config_init()
  7304. ma_context_init()
  7305. */
  7306. 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);
  7307. /*
  7308. Uninitializes a device.
  7309. This will explicitly stop the device. You do not need to call `ma_device_stop()` beforehand, but it's harmless if you do.
  7310. Parameters
  7311. ----------
  7312. pDevice (in)
  7313. A pointer to the device to stop.
  7314. Return Value
  7315. ------------
  7316. Nothing
  7317. Thread Safety
  7318. -------------
  7319. Unsafe. As soon as this API is called the device should be considered undefined.
  7320. Callback Safety
  7321. ---------------
  7322. Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
  7323. See Also
  7324. --------
  7325. ma_device_init()
  7326. ma_device_stop()
  7327. */
  7328. MA_API void ma_device_uninit(ma_device* pDevice);
  7329. /*
  7330. Retrieves a pointer to the context that owns the given device.
  7331. */
  7332. MA_API ma_context* ma_device_get_context(ma_device* pDevice);
  7333. /*
  7334. Helper function for retrieving the log object associated with the context that owns this device.
  7335. */
  7336. MA_API ma_log* ma_device_get_log(ma_device* pDevice);
  7337. /*
  7338. Retrieves information about the device.
  7339. Parameters
  7340. ----------
  7341. pDevice (in)
  7342. A pointer to the device whose information is being retrieved.
  7343. type (in)
  7344. The device type. This parameter is required for duplex devices. When retrieving device
  7345. information, you are doing so for an individual playback or capture device.
  7346. pDeviceInfo (out)
  7347. A pointer to the `ma_device_info` that will receive the device information.
  7348. Return Value
  7349. ------------
  7350. MA_SUCCESS if successful; any other error code otherwise.
  7351. Thread Safety
  7352. -------------
  7353. Unsafe. This should be considered unsafe because it may be calling into the backend which may or
  7354. may not be safe.
  7355. Callback Safety
  7356. ---------------
  7357. Unsafe. You should avoid calling this in the data callback because it may call into the backend
  7358. which may or may not be safe.
  7359. */
  7360. MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
  7361. /*
  7362. Retrieves the name of the device.
  7363. Parameters
  7364. ----------
  7365. pDevice (in)
  7366. A pointer to the device whose information is being retrieved.
  7367. type (in)
  7368. The device type. This parameter is required for duplex devices. When retrieving device
  7369. information, you are doing so for an individual playback or capture device.
  7370. pName (out)
  7371. A pointer to the buffer that will receive the name.
  7372. nameCap (in)
  7373. The capacity of the output buffer, including space for the null terminator.
  7374. pLengthNotIncludingNullTerminator (out, optional)
  7375. A pointer to the variable that will receive the length of the name, not including the null
  7376. terminator.
  7377. Return Value
  7378. ------------
  7379. MA_SUCCESS if successful; any other error code otherwise.
  7380. Thread Safety
  7381. -------------
  7382. Unsafe. This should be considered unsafe because it may be calling into the backend which may or
  7383. may not be safe.
  7384. Callback Safety
  7385. ---------------
  7386. Unsafe. You should avoid calling this in the data callback because it may call into the backend
  7387. which may or may not be safe.
  7388. Remarks
  7389. -------
  7390. If the name does not fully fit into the output buffer, it'll be truncated. You can pass in NULL to
  7391. `pName` if you want to first get the length of the name for the purpose of memory allocation of the
  7392. output buffer. Allocating a buffer of size `MA_MAX_DEVICE_NAME_LENGTH + 1` should be enough for
  7393. most cases and will avoid the need for the inefficiency of calling this function twice.
  7394. This is implemented in terms of `ma_device_get_info()`.
  7395. */
  7396. MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator);
  7397. /*
  7398. Starts the device. For playback devices this begins playback. For capture devices it begins recording.
  7399. Use `ma_device_stop()` to stop the device.
  7400. Parameters
  7401. ----------
  7402. pDevice (in)
  7403. A pointer to the device to start.
  7404. Return Value
  7405. ------------
  7406. MA_SUCCESS if successful; any other error code otherwise.
  7407. Thread Safety
  7408. -------------
  7409. Safe. It's safe to call this from any thread with the exception of the callback thread.
  7410. Callback Safety
  7411. ---------------
  7412. Unsafe. It is not safe to call this inside any callback.
  7413. Remarks
  7414. -------
  7415. 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
  7416. audio data in the buffer, which needs to be done before the device begins playback.
  7417. 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.
  7418. Do not call this in any callback.
  7419. See Also
  7420. --------
  7421. ma_device_stop()
  7422. */
  7423. MA_API ma_result ma_device_start(ma_device* pDevice);
  7424. /*
  7425. Stops the device. For playback devices this stops playback. For capture devices it stops recording.
  7426. Use `ma_device_start()` to start the device again.
  7427. Parameters
  7428. ----------
  7429. pDevice (in)
  7430. A pointer to the device to stop.
  7431. Return Value
  7432. ------------
  7433. MA_SUCCESS if successful; any other error code otherwise.
  7434. Thread Safety
  7435. -------------
  7436. Safe. It's safe to call this from any thread with the exception of the callback thread.
  7437. Callback Safety
  7438. ---------------
  7439. Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
  7440. Remarks
  7441. -------
  7442. 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
  7443. 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
  7444. that was specified at initialization time).
  7445. 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
  7446. 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
  7447. speakers or received from the microphone which can in turn result in de-syncs.
  7448. Do not call this in any callback.
  7449. See Also
  7450. --------
  7451. ma_device_start()
  7452. */
  7453. MA_API ma_result ma_device_stop(ma_device* pDevice);
  7454. /*
  7455. Determines whether or not the device is started.
  7456. Parameters
  7457. ----------
  7458. pDevice (in)
  7459. A pointer to the device whose start state is being retrieved.
  7460. Return Value
  7461. ------------
  7462. True if the device is started, false otherwise.
  7463. Thread Safety
  7464. -------------
  7465. 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
  7466. value will be out of sync.
  7467. Callback Safety
  7468. ---------------
  7469. Safe. This is implemented as a simple accessor.
  7470. See Also
  7471. --------
  7472. ma_device_start()
  7473. ma_device_stop()
  7474. */
  7475. MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice);
  7476. /*
  7477. Retrieves the state of the device.
  7478. Parameters
  7479. ----------
  7480. pDevice (in)
  7481. A pointer to the device whose state is being retrieved.
  7482. Return Value
  7483. ------------
  7484. The current state of the device. The return value will be one of the following:
  7485. +-------------------------------+------------------------------------------------------------------------------+
  7486. | ma_device_state_uninitialized | Will only be returned if the device is in the middle of initialization. |
  7487. +-------------------------------+------------------------------------------------------------------------------+
  7488. | ma_device_state_stopped | The device is stopped. The initial state of the device after initialization. |
  7489. +-------------------------------+------------------------------------------------------------------------------+
  7490. | ma_device_state_started | The device started and requesting and/or delivering audio data. |
  7491. +-------------------------------+------------------------------------------------------------------------------+
  7492. | ma_device_state_starting | The device is in the process of starting. |
  7493. +-------------------------------+------------------------------------------------------------------------------+
  7494. | ma_device_state_stopping | The device is in the process of stopping. |
  7495. +-------------------------------+------------------------------------------------------------------------------+
  7496. Thread Safety
  7497. -------------
  7498. 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,
  7499. there's a possibility the return value could be out of sync. See remarks.
  7500. Callback Safety
  7501. ---------------
  7502. Safe. This is implemented as a simple accessor.
  7503. Remarks
  7504. -------
  7505. The general flow of a devices state goes like this:
  7506. ```
  7507. ma_device_init() -> ma_device_state_uninitialized -> ma_device_state_stopped
  7508. ma_device_start() -> ma_device_state_starting -> ma_device_state_started
  7509. ma_device_stop() -> ma_device_state_stopping -> ma_device_state_stopped
  7510. ```
  7511. 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
  7512. value returned by this function could potentially be out of sync. If this is significant to your program you need to implement your own
  7513. synchronization.
  7514. */
  7515. MA_API ma_device_state ma_device_get_state(const ma_device* pDevice);
  7516. /*
  7517. Performs post backend initialization routines for setting up internal data conversion.
  7518. This should be called whenever the backend is initialized. The only time this should be called from
  7519. outside of miniaudio is if you're implementing a custom backend, and you would only do it if you
  7520. are reinitializing the backend due to rerouting or reinitializing for some reason.
  7521. Parameters
  7522. ----------
  7523. pDevice [in]
  7524. A pointer to the device.
  7525. deviceType [in]
  7526. The type of the device that was just reinitialized.
  7527. pPlaybackDescriptor [in]
  7528. The descriptor of the playback device containing the internal data format and buffer sizes.
  7529. pPlaybackDescriptor [in]
  7530. The descriptor of the capture device containing the internal data format and buffer sizes.
  7531. Return Value
  7532. ------------
  7533. MA_SUCCESS if successful; any other error otherwise.
  7534. Thread Safety
  7535. -------------
  7536. Unsafe. This will be reinitializing internal data converters which may be in use by another thread.
  7537. Callback Safety
  7538. ---------------
  7539. Unsafe. This will be reinitializing internal data converters which may be in use by the callback.
  7540. Remarks
  7541. -------
  7542. For a duplex device, you can call this for only one side of the system. This is why the deviceType
  7543. is specified as a parameter rather than deriving it from the device.
  7544. You do not need to call this manually unless you are doing a custom backend, in which case you need
  7545. only do it if you're manually performing rerouting or reinitialization.
  7546. */
  7547. 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);
  7548. /*
  7549. Sets the master volume factor for the device.
  7550. 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
  7551. values less than 0 decreases the volume.
  7552. Parameters
  7553. ----------
  7554. pDevice (in)
  7555. A pointer to the device whose volume is being set.
  7556. volume (in)
  7557. The new volume factor. Must be >= 0.
  7558. Return Value
  7559. ------------
  7560. MA_SUCCESS if the volume was set successfully.
  7561. MA_INVALID_ARGS if pDevice is NULL.
  7562. MA_INVALID_ARGS if volume is negative.
  7563. Thread Safety
  7564. -------------
  7565. Safe. This just sets a local member of the device object.
  7566. Callback Safety
  7567. ---------------
  7568. Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
  7569. Remarks
  7570. -------
  7571. This applies the volume factor across all channels.
  7572. This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
  7573. See Also
  7574. --------
  7575. ma_device_get_master_volume()
  7576. ma_device_set_master_volume_db()
  7577. ma_device_get_master_volume_db()
  7578. */
  7579. MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume);
  7580. /*
  7581. Retrieves the master volume factor for the device.
  7582. Parameters
  7583. ----------
  7584. pDevice (in)
  7585. A pointer to the device whose volume factor is being retrieved.
  7586. pVolume (in)
  7587. A pointer to the variable that will receive the volume factor. The returned value will be in the range of [0, 1].
  7588. Return Value
  7589. ------------
  7590. MA_SUCCESS if successful.
  7591. MA_INVALID_ARGS if pDevice is NULL.
  7592. MA_INVALID_ARGS if pVolume is NULL.
  7593. Thread Safety
  7594. -------------
  7595. Safe. This just a simple member retrieval.
  7596. Callback Safety
  7597. ---------------
  7598. Safe.
  7599. Remarks
  7600. -------
  7601. If an error occurs, `*pVolume` will be set to 0.
  7602. See Also
  7603. --------
  7604. ma_device_set_master_volume()
  7605. ma_device_set_master_volume_gain_db()
  7606. ma_device_get_master_volume_gain_db()
  7607. */
  7608. MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume);
  7609. /*
  7610. Sets the master volume for the device as gain in decibels.
  7611. A gain of 0 is full volume, whereas a gain of < 0 will decrease the volume.
  7612. Parameters
  7613. ----------
  7614. pDevice (in)
  7615. A pointer to the device whose gain is being set.
  7616. gainDB (in)
  7617. 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.
  7618. Return Value
  7619. ------------
  7620. MA_SUCCESS if the volume was set successfully.
  7621. MA_INVALID_ARGS if pDevice is NULL.
  7622. MA_INVALID_ARGS if the gain is > 0.
  7623. Thread Safety
  7624. -------------
  7625. Safe. This just sets a local member of the device object.
  7626. Callback Safety
  7627. ---------------
  7628. Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
  7629. Remarks
  7630. -------
  7631. This applies the gain across all channels.
  7632. This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
  7633. See Also
  7634. --------
  7635. ma_device_get_master_volume_gain_db()
  7636. ma_device_set_master_volume()
  7637. ma_device_get_master_volume()
  7638. */
  7639. MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB);
  7640. /*
  7641. Retrieves the master gain in decibels.
  7642. Parameters
  7643. ----------
  7644. pDevice (in)
  7645. A pointer to the device whose gain is being retrieved.
  7646. pGainDB (in)
  7647. A pointer to the variable that will receive the gain in decibels. The returned value will be <= 0.
  7648. Return Value
  7649. ------------
  7650. MA_SUCCESS if successful.
  7651. MA_INVALID_ARGS if pDevice is NULL.
  7652. MA_INVALID_ARGS if pGainDB is NULL.
  7653. Thread Safety
  7654. -------------
  7655. Safe. This just a simple member retrieval.
  7656. Callback Safety
  7657. ---------------
  7658. Safe.
  7659. Remarks
  7660. -------
  7661. If an error occurs, `*pGainDB` will be set to 0.
  7662. See Also
  7663. --------
  7664. ma_device_set_master_volume_db()
  7665. ma_device_set_master_volume()
  7666. ma_device_get_master_volume()
  7667. */
  7668. MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB);
  7669. /*
  7670. Called from the data callback of asynchronous backends to allow miniaudio to process the data and fire the miniaudio data callback.
  7671. Parameters
  7672. ----------
  7673. pDevice (in)
  7674. A pointer to device whose processing the data callback.
  7675. pOutput (out)
  7676. 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
  7677. this can be NULL, in which case pInput must not be NULL.
  7678. pInput (in)
  7679. 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
  7680. NULL, in which case `pOutput` must not be NULL.
  7681. frameCount (in)
  7682. The number of frames being processed.
  7683. Return Value
  7684. ------------
  7685. MA_SUCCESS if successful; any other result code otherwise.
  7686. Thread Safety
  7687. -------------
  7688. This function should only ever be called from the internal data callback of the backend. It is safe to call this simultaneously between a
  7689. playback and capture device in duplex setups.
  7690. Callback Safety
  7691. ---------------
  7692. Do not call this from the miniaudio data callback. It should only ever be called from the internal data callback of the backend.
  7693. Remarks
  7694. -------
  7695. If both `pOutput` and `pInput` are NULL, and error will be returned. In duplex scenarios, both `pOutput` and `pInput` can be non-NULL, in
  7696. which case `pInput` will be processed first, followed by `pOutput`.
  7697. 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
  7698. callback.
  7699. */
  7700. MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
  7701. /*
  7702. Calculates an appropriate buffer size from a descriptor, native sample rate and performance profile.
  7703. This function is used by backends for helping determine an appropriately sized buffer to use with
  7704. the device depending on the values of `periodSizeInFrames` and `periodSizeInMilliseconds` in the
  7705. `pDescriptor` object. Since buffer size calculations based on time depends on the sample rate, a
  7706. best guess at the device's native sample rate is also required which is where `nativeSampleRate`
  7707. comes in. In addition, the performance profile is also needed for cases where both the period size
  7708. in frames and milliseconds are both zero.
  7709. Parameters
  7710. ----------
  7711. pDescriptor (in)
  7712. A pointer to device descriptor whose `periodSizeInFrames` and `periodSizeInMilliseconds` members
  7713. will be used for the calculation of the buffer size.
  7714. nativeSampleRate (in)
  7715. The device's native sample rate. This is only ever used when the `periodSizeInFrames` member of
  7716. `pDescriptor` is zero. In this case, `periodSizeInMilliseconds` will be used instead, in which
  7717. case a sample rate is required to convert to a size in frames.
  7718. performanceProfile (in)
  7719. When both the `periodSizeInFrames` and `periodSizeInMilliseconds` members of `pDescriptor` are
  7720. zero, miniaudio will fall back to a buffer size based on the performance profile. The profile
  7721. to use for this calculation is determine by this parameter.
  7722. Return Value
  7723. ------------
  7724. The calculated buffer size in frames.
  7725. Thread Safety
  7726. -------------
  7727. This is safe so long as nothing modifies `pDescriptor` at the same time. However, this function
  7728. should only ever be called from within the backend's device initialization routine and therefore
  7729. shouldn't have any multithreading concerns.
  7730. Callback Safety
  7731. ---------------
  7732. This is safe to call within the data callback, but there is no reason to ever do this.
  7733. Remarks
  7734. -------
  7735. If `nativeSampleRate` is zero, this function will fall back to `pDescriptor->sampleRate`. If that
  7736. is also zero, `MA_DEFAULT_SAMPLE_RATE` will be used instead.
  7737. */
  7738. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile);
  7739. /*
  7740. Retrieves a friendly name for a backend.
  7741. */
  7742. MA_API const char* ma_get_backend_name(ma_backend backend);
  7743. /*
  7744. Retrieves the backend enum from the given name.
  7745. */
  7746. MA_API ma_result ma_get_backend_from_name(const char* pBackendName, ma_backend* pBackend);
  7747. /*
  7748. Determines whether or not the given backend is available by the compilation environment.
  7749. */
  7750. MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend);
  7751. /*
  7752. Retrieves compile-time enabled backends.
  7753. Parameters
  7754. ----------
  7755. pBackends (out, optional)
  7756. A pointer to the buffer that will receive the enabled backends. Set to NULL to retrieve the backend count. Setting
  7757. the capacity of the buffer to `MA_BUFFER_COUNT` will guarantee it's large enough for all backends.
  7758. backendCap (in)
  7759. The capacity of the `pBackends` buffer.
  7760. pBackendCount (out)
  7761. A pointer to the variable that will receive the enabled backend count.
  7762. Return Value
  7763. ------------
  7764. MA_SUCCESS if successful.
  7765. MA_INVALID_ARGS if `pBackendCount` is NULL.
  7766. MA_NO_SPACE if the capacity of `pBackends` is not large enough.
  7767. If `MA_NO_SPACE` is returned, the `pBackends` buffer will be filled with `*pBackendCount` values.
  7768. Thread Safety
  7769. -------------
  7770. Safe.
  7771. Callback Safety
  7772. ---------------
  7773. Safe.
  7774. Remarks
  7775. -------
  7776. If you want to retrieve the number of backends so you can determine the capacity of `pBackends` buffer, you can call
  7777. this function with `pBackends` set to NULL.
  7778. This will also enumerate the null backend. If you don't want to include this you need to check for `ma_backend_null`
  7779. when you enumerate over the returned backends and handle it appropriately. Alternatively, you can disable it at
  7780. compile time with `MA_NO_NULL`.
  7781. The returned backends are determined based on compile time settings, not the platform it's currently running on. For
  7782. example, PulseAudio will be returned if it was enabled at compile time, even when the user doesn't actually have
  7783. PulseAudio installed.
  7784. Example 1
  7785. ---------
  7786. The example below retrieves the enabled backend count using a fixed sized buffer allocated on the stack. The buffer is
  7787. given a capacity of `MA_BACKEND_COUNT` which will guarantee it'll be large enough to store all available backends.
  7788. Since `MA_BACKEND_COUNT` is always a relatively small value, this should be suitable for most scenarios.
  7789. ```
  7790. ma_backend enabledBackends[MA_BACKEND_COUNT];
  7791. size_t enabledBackendCount;
  7792. result = ma_get_enabled_backends(enabledBackends, MA_BACKEND_COUNT, &enabledBackendCount);
  7793. if (result != MA_SUCCESS) {
  7794. // Failed to retrieve enabled backends. Should never happen in this example since all inputs are valid.
  7795. }
  7796. ```
  7797. See Also
  7798. --------
  7799. ma_is_backend_enabled()
  7800. */
  7801. MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount);
  7802. /*
  7803. Determines whether or not loopback mode is support by a backend.
  7804. */
  7805. MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend);
  7806. #endif /* MA_NO_DEVICE_IO */
  7807. /************************************************************************************************************************************************************
  7808. Utilities
  7809. ************************************************************************************************************************************************************/
  7810. /*
  7811. Calculates a buffer size in milliseconds from the specified number of frames and sample rate.
  7812. */
  7813. MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate);
  7814. /*
  7815. Calculates a buffer size in frames from the specified number of milliseconds and sample rate.
  7816. */
  7817. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate);
  7818. /*
  7819. Copies PCM frames from one buffer to another.
  7820. */
  7821. MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7822. /*
  7823. Copies silent frames into the given buffer.
  7824. Remarks
  7825. -------
  7826. 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
  7827. makes more sense for the purpose of mixing to initialize it to the center point.
  7828. */
  7829. MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7830. /*
  7831. Offsets a pointer by the specified number of PCM frames.
  7832. */
  7833. MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
  7834. MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
  7835. 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); }
  7836. 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); }
  7837. /*
  7838. Clips samples.
  7839. */
  7840. MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count);
  7841. MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count);
  7842. MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count);
  7843. MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count);
  7844. MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count);
  7845. MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7846. /*
  7847. Helper for applying a volume factor to samples.
  7848. Note that the source and destination buffers can be the same, in which case it'll perform the operation in-place.
  7849. */
  7850. MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor);
  7851. MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor);
  7852. MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor);
  7853. MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor);
  7854. MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor);
  7855. MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor);
  7856. MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor);
  7857. MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor);
  7858. MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor);
  7859. MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor);
  7860. 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);
  7861. 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);
  7862. 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);
  7863. 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);
  7864. 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);
  7865. 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);
  7866. MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7867. MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7868. MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7869. MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7870. MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7871. MA_API void ma_apply_volume_factor_pcm_frames(void* pFrames, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor);
  7872. 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);
  7873. MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume);
  7874. MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume);
  7875. MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume);
  7876. MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume);
  7877. MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume);
  7878. 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);
  7879. /*
  7880. Helper for converting a linear factor to gain in decibels.
  7881. */
  7882. MA_API float ma_volume_linear_to_db(float factor);
  7883. /*
  7884. Helper for converting gain in decibels to a linear factor.
  7885. */
  7886. MA_API float ma_volume_db_to_linear(float gain);
  7887. /*
  7888. Mixes the specified number of frames in floating point format with a volume factor.
  7889. This will run on an optimized path when the volume is equal to 1.
  7890. */
  7891. MA_API ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume);
  7892. /************************************************************************************************************************************************************
  7893. VFS
  7894. ===
  7895. 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
  7896. appropriate for a given situation.
  7897. ************************************************************************************************************************************************************/
  7898. typedef void ma_vfs;
  7899. typedef ma_handle ma_vfs_file;
  7900. typedef enum
  7901. {
  7902. MA_OPEN_MODE_READ = 0x00000001,
  7903. MA_OPEN_MODE_WRITE = 0x00000002
  7904. } ma_open_mode_flags;
  7905. typedef enum
  7906. {
  7907. ma_seek_origin_start,
  7908. ma_seek_origin_current,
  7909. ma_seek_origin_end /* Not used by decoders. */
  7910. } ma_seek_origin;
  7911. typedef struct
  7912. {
  7913. ma_uint64 sizeInBytes;
  7914. } ma_file_info;
  7915. typedef struct
  7916. {
  7917. ma_result (* onOpen) (ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7918. ma_result (* onOpenW)(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7919. ma_result (* onClose)(ma_vfs* pVFS, ma_vfs_file file);
  7920. ma_result (* onRead) (ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
  7921. ma_result (* onWrite)(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
  7922. ma_result (* onSeek) (ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
  7923. ma_result (* onTell) (ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
  7924. ma_result (* onInfo) (ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
  7925. } ma_vfs_callbacks;
  7926. MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7927. MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7928. MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file);
  7929. MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
  7930. MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
  7931. MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
  7932. MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
  7933. MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
  7934. 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);
  7935. typedef struct
  7936. {
  7937. ma_vfs_callbacks cb;
  7938. ma_allocation_callbacks allocationCallbacks; /* Only used for the wchar_t version of open() on non-Windows platforms. */
  7939. } ma_default_vfs;
  7940. MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks);
  7941. typedef ma_result (* ma_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead);
  7942. typedef ma_result (* ma_seek_proc)(void* pUserData, ma_int64 offset, ma_seek_origin origin);
  7943. typedef ma_result (* ma_tell_proc)(void* pUserData, ma_int64* pCursor);
  7944. #if !defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING)
  7945. typedef enum
  7946. {
  7947. ma_encoding_format_unknown = 0,
  7948. ma_encoding_format_wav,
  7949. ma_encoding_format_flac,
  7950. ma_encoding_format_mp3,
  7951. ma_encoding_format_vorbis
  7952. } ma_encoding_format;
  7953. #endif
  7954. /************************************************************************************************************************************************************
  7955. Decoding
  7956. ========
  7957. 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
  7958. you do your own synchronization.
  7959. ************************************************************************************************************************************************************/
  7960. #ifndef MA_NO_DECODING
  7961. typedef struct ma_decoder ma_decoder;
  7962. typedef struct
  7963. {
  7964. ma_format preferredFormat;
  7965. ma_uint32 seekPointCount; /* Set to > 0 to generate a seektable if the decoding backend supports it. */
  7966. } ma_decoding_backend_config;
  7967. MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount);
  7968. typedef struct
  7969. {
  7970. 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);
  7971. ma_result (* onInitFile )(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */
  7972. 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. */
  7973. 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. */
  7974. void (* onUninit )(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
  7975. } ma_decoding_backend_vtable;
  7976. typedef ma_result (* ma_decoder_read_proc)(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead); /* Returns the number of bytes read. */
  7977. typedef ma_result (* ma_decoder_seek_proc)(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin);
  7978. typedef ma_result (* ma_decoder_tell_proc)(ma_decoder* pDecoder, ma_int64* pCursor);
  7979. typedef struct
  7980. {
  7981. ma_format format; /* Set to 0 or ma_format_unknown to use the stream's internal format. */
  7982. ma_uint32 channels; /* Set to 0 to use the stream's internal channels. */
  7983. ma_uint32 sampleRate; /* Set to 0 to use the stream's internal sample rate. */
  7984. ma_channel* pChannelMap;
  7985. ma_channel_mix_mode channelMixMode;
  7986. ma_dither_mode ditherMode;
  7987. ma_resampler_config resampling;
  7988. ma_allocation_callbacks allocationCallbacks;
  7989. ma_encoding_format encodingFormat;
  7990. 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. */
  7991. ma_decoding_backend_vtable** ppCustomBackendVTables;
  7992. ma_uint32 customBackendCount;
  7993. void* pCustomBackendUserData;
  7994. } ma_decoder_config;
  7995. struct ma_decoder
  7996. {
  7997. ma_data_source_base ds;
  7998. ma_data_source* pBackend; /* The decoding backend we'll be pulling data from. */
  7999. const ma_decoding_backend_vtable* pBackendVTable; /* The vtable for the decoding backend. This needs to be stored so we can access the onUninit() callback. */
  8000. void* pBackendUserData;
  8001. ma_decoder_read_proc onRead;
  8002. ma_decoder_seek_proc onSeek;
  8003. ma_decoder_tell_proc onTell;
  8004. void* pUserData;
  8005. ma_uint64 readPointerInPCMFrames; /* In output sample rate. Used for keeping track of how many frames are available for decoding. */
  8006. ma_format outputFormat;
  8007. ma_uint32 outputChannels;
  8008. ma_uint32 outputSampleRate;
  8009. ma_data_converter converter; /* Data conversion is achieved by running frames through this. */
  8010. void* pInputCache; /* In input format. Can be null if it's not needed. */
  8011. ma_uint64 inputCacheCap; /* The capacity of the input cache. */
  8012. ma_uint64 inputCacheConsumed; /* The number of frames that have been consumed in the cache. Used for determining the next valid frame. */
  8013. ma_uint64 inputCacheRemaining; /* The number of valid frames remaining in the cahce. */
  8014. ma_allocation_callbacks allocationCallbacks;
  8015. union
  8016. {
  8017. struct
  8018. {
  8019. ma_vfs* pVFS;
  8020. ma_vfs_file file;
  8021. } vfs;
  8022. struct
  8023. {
  8024. const ma_uint8* pData;
  8025. size_t dataSize;
  8026. size_t currentReadPos;
  8027. } memory; /* Only used for decoders that were opened against a block of memory. */
  8028. } data;
  8029. };
  8030. MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate);
  8031. MA_API ma_decoder_config ma_decoder_config_init_default(void);
  8032. 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);
  8033. MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8034. MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8035. MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8036. MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8037. MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  8038. /*
  8039. Uninitializes a decoder.
  8040. */
  8041. MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder);
  8042. /*
  8043. Reads PCM frames from the given decoder.
  8044. This is not thread safe without your own synchronization.
  8045. */
  8046. MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8047. /*
  8048. Seeks to a PCM frame based on it's absolute index.
  8049. This is not thread safe without your own synchronization.
  8050. */
  8051. MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex);
  8052. /*
  8053. Retrieves the decoder's output data format.
  8054. */
  8055. 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);
  8056. /*
  8057. Retrieves the current position of the read cursor in PCM frames.
  8058. */
  8059. MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor);
  8060. /*
  8061. Retrieves the length of the decoder in PCM frames.
  8062. Do not call this on streams of an undefined length, such as internet radio.
  8063. If the length is unknown or an error occurs, 0 will be returned.
  8064. This will always return 0 for Vorbis decoders. This is due to a limitation with stb_vorbis in push mode which is what miniaudio
  8065. uses internally.
  8066. For MP3's, this will decode the entire file. Do not call this in time critical scenarios.
  8067. This function is not thread safe without your own synchronization.
  8068. */
  8069. MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength);
  8070. /*
  8071. Retrieves the number of frames that can be read before reaching the end.
  8072. This calls `ma_decoder_get_length_in_pcm_frames()` so you need to be aware of the rules for that function, in
  8073. particular ensuring you do not call it on streams of an undefined length, such as internet radio.
  8074. If the total length of the decoder cannot be retrieved, such as with Vorbis decoders, `MA_NOT_IMPLEMENTED` will be
  8075. returned.
  8076. */
  8077. MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames);
  8078. /*
  8079. Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input,
  8080. pConfig should be set to what you want. On output it will be set to what you got.
  8081. */
  8082. MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  8083. MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  8084. MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  8085. #endif /* MA_NO_DECODING */
  8086. /************************************************************************************************************************************************************
  8087. Encoding
  8088. ========
  8089. Encoders do not perform any format conversion for you. If your target format does not support the format, and error will be returned.
  8090. ************************************************************************************************************************************************************/
  8091. #ifndef MA_NO_ENCODING
  8092. typedef struct ma_encoder ma_encoder;
  8093. typedef ma_result (* ma_encoder_write_proc) (ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten);
  8094. typedef ma_result (* ma_encoder_seek_proc) (ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin);
  8095. typedef ma_result (* ma_encoder_init_proc) (ma_encoder* pEncoder);
  8096. typedef void (* ma_encoder_uninit_proc) (ma_encoder* pEncoder);
  8097. typedef ma_result (* ma_encoder_write_pcm_frames_proc)(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten);
  8098. typedef struct
  8099. {
  8100. ma_encoding_format encodingFormat;
  8101. ma_format format;
  8102. ma_uint32 channels;
  8103. ma_uint32 sampleRate;
  8104. ma_allocation_callbacks allocationCallbacks;
  8105. } ma_encoder_config;
  8106. MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  8107. struct ma_encoder
  8108. {
  8109. ma_encoder_config config;
  8110. ma_encoder_write_proc onWrite;
  8111. ma_encoder_seek_proc onSeek;
  8112. ma_encoder_init_proc onInit;
  8113. ma_encoder_uninit_proc onUninit;
  8114. ma_encoder_write_pcm_frames_proc onWritePCMFrames;
  8115. void* pUserData;
  8116. void* pInternalEncoder;
  8117. union
  8118. {
  8119. struct
  8120. {
  8121. ma_vfs* pVFS;
  8122. ma_vfs_file file;
  8123. } vfs;
  8124. } data;
  8125. };
  8126. 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);
  8127. MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8128. MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8129. MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8130. MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  8131. MA_API void ma_encoder_uninit(ma_encoder* pEncoder);
  8132. MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten);
  8133. #endif /* MA_NO_ENCODING */
  8134. /************************************************************************************************************************************************************
  8135. Generation
  8136. ************************************************************************************************************************************************************/
  8137. #ifndef MA_NO_GENERATION
  8138. typedef enum
  8139. {
  8140. ma_waveform_type_sine,
  8141. ma_waveform_type_square,
  8142. ma_waveform_type_triangle,
  8143. ma_waveform_type_sawtooth
  8144. } ma_waveform_type;
  8145. typedef struct
  8146. {
  8147. ma_format format;
  8148. ma_uint32 channels;
  8149. ma_uint32 sampleRate;
  8150. ma_waveform_type type;
  8151. double amplitude;
  8152. double frequency;
  8153. } ma_waveform_config;
  8154. 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);
  8155. typedef struct
  8156. {
  8157. ma_data_source_base ds;
  8158. ma_waveform_config config;
  8159. double advance;
  8160. double time;
  8161. } ma_waveform;
  8162. MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform);
  8163. MA_API void ma_waveform_uninit(ma_waveform* pWaveform);
  8164. MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8165. MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex);
  8166. MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude);
  8167. MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency);
  8168. MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type);
  8169. MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate);
  8170. typedef struct
  8171. {
  8172. ma_format format;
  8173. ma_uint32 channels;
  8174. ma_uint32 sampleRate;
  8175. double dutyCycle;
  8176. double amplitude;
  8177. double frequency;
  8178. } ma_pulsewave_config;
  8179. MA_API ma_pulsewave_config ma_pulsewave_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double dutyCycle, double amplitude, double frequency);
  8180. typedef struct
  8181. {
  8182. ma_waveform waveform;
  8183. ma_pulsewave_config config;
  8184. } ma_pulsewave;
  8185. MA_API ma_result ma_pulsewave_init(const ma_pulsewave_config* pConfig, ma_pulsewave* pWaveform);
  8186. MA_API void ma_pulsewave_uninit(ma_pulsewave* pWaveform);
  8187. MA_API ma_result ma_pulsewave_read_pcm_frames(ma_pulsewave* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8188. MA_API ma_result ma_pulsewave_seek_to_pcm_frame(ma_pulsewave* pWaveform, ma_uint64 frameIndex);
  8189. MA_API ma_result ma_pulsewave_set_amplitude(ma_pulsewave* pWaveform, double amplitude);
  8190. MA_API ma_result ma_pulsewave_set_frequency(ma_pulsewave* pWaveform, double frequency);
  8191. MA_API ma_result ma_pulsewave_set_sample_rate(ma_pulsewave* pWaveform, ma_uint32 sampleRate);
  8192. MA_API ma_result ma_pulsewave_set_duty_cycle(ma_pulsewave* pWaveform, double dutyCycle);
  8193. typedef enum
  8194. {
  8195. ma_noise_type_white,
  8196. ma_noise_type_pink,
  8197. ma_noise_type_brownian
  8198. } ma_noise_type;
  8199. typedef struct
  8200. {
  8201. ma_format format;
  8202. ma_uint32 channels;
  8203. ma_noise_type type;
  8204. ma_int32 seed;
  8205. double amplitude;
  8206. ma_bool32 duplicateChannels;
  8207. } ma_noise_config;
  8208. MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude);
  8209. typedef struct
  8210. {
  8211. ma_data_source_base ds;
  8212. ma_noise_config config;
  8213. ma_lcg lcg;
  8214. union
  8215. {
  8216. struct
  8217. {
  8218. double** bin;
  8219. double* accumulation;
  8220. ma_uint32* counter;
  8221. } pink;
  8222. struct
  8223. {
  8224. double* accumulation;
  8225. } brownian;
  8226. } state;
  8227. /* Memory management. */
  8228. void* _pHeap;
  8229. ma_bool32 _ownsHeap;
  8230. } ma_noise;
  8231. MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes);
  8232. MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise);
  8233. MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise);
  8234. MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks);
  8235. MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8236. MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude);
  8237. MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed);
  8238. MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type);
  8239. #endif /* MA_NO_GENERATION */
  8240. /************************************************************************************************************************************************************
  8241. Resource Manager
  8242. ************************************************************************************************************************************************************/
  8243. /* The resource manager cannot be enabled if there is no decoder. */
  8244. #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_NO_DECODING)
  8245. #define MA_NO_RESOURCE_MANAGER
  8246. #endif
  8247. #ifndef MA_NO_RESOURCE_MANAGER
  8248. typedef struct ma_resource_manager ma_resource_manager;
  8249. typedef struct ma_resource_manager_data_buffer_node ma_resource_manager_data_buffer_node;
  8250. typedef struct ma_resource_manager_data_buffer ma_resource_manager_data_buffer;
  8251. typedef struct ma_resource_manager_data_stream ma_resource_manager_data_stream;
  8252. typedef struct ma_resource_manager_data_source ma_resource_manager_data_source;
  8253. typedef enum
  8254. {
  8255. 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. */
  8256. 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. */
  8257. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC = 0x00000004, /* When set, the resource manager will load the data source asynchronously. */
  8258. 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(). */
  8259. 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. */
  8260. } ma_resource_manager_data_source_flags;
  8261. /*
  8262. Pipeline notifications used by the resource manager. Made up of both an async notification and a fence, both of which are optional.
  8263. */
  8264. typedef struct
  8265. {
  8266. ma_async_notification* pNotification;
  8267. ma_fence* pFence;
  8268. } ma_resource_manager_pipeline_stage_notification;
  8269. typedef struct
  8270. {
  8271. ma_resource_manager_pipeline_stage_notification init; /* Initialization of the decoder. */
  8272. ma_resource_manager_pipeline_stage_notification done; /* Decoding fully completed. */
  8273. } ma_resource_manager_pipeline_notifications;
  8274. MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void);
  8275. /* BEGIN BACKWARDS COMPATIBILITY */
  8276. /* TODO: Remove this block in version 0.12. */
  8277. #if 1
  8278. #define ma_resource_manager_job ma_job
  8279. #define ma_resource_manager_job_init ma_job_init
  8280. #define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_FLAG_NON_BLOCKING MA_JOB_QUEUE_FLAG_NON_BLOCKING
  8281. #define ma_resource_manager_job_queue_config ma_job_queue_config
  8282. #define ma_resource_manager_job_queue_config_init ma_job_queue_config_init
  8283. #define ma_resource_manager_job_queue ma_job_queue
  8284. #define ma_resource_manager_job_queue_get_heap_size ma_job_queue_get_heap_size
  8285. #define ma_resource_manager_job_queue_init_preallocated ma_job_queue_init_preallocated
  8286. #define ma_resource_manager_job_queue_init ma_job_queue_init
  8287. #define ma_resource_manager_job_queue_uninit ma_job_queue_uninit
  8288. #define ma_resource_manager_job_queue_post ma_job_queue_post
  8289. #define ma_resource_manager_job_queue_next ma_job_queue_next
  8290. #endif
  8291. /* END BACKWARDS COMPATIBILITY */
  8292. /* 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. */
  8293. #ifndef MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT
  8294. #define MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT 64
  8295. #endif
  8296. typedef enum
  8297. {
  8298. /* Indicates ma_resource_manager_next_job() should not block. Only valid when the job thread count is 0. */
  8299. MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING = 0x00000001,
  8300. /* Disables any kind of multithreading. Implicitly enables MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING. */
  8301. MA_RESOURCE_MANAGER_FLAG_NO_THREADING = 0x00000002
  8302. } ma_resource_manager_flags;
  8303. typedef struct
  8304. {
  8305. const char* pFilePath;
  8306. const wchar_t* pFilePathW;
  8307. const ma_resource_manager_pipeline_notifications* pNotifications;
  8308. ma_uint64 initialSeekPointInPCMFrames;
  8309. ma_uint64 rangeBegInPCMFrames;
  8310. ma_uint64 rangeEndInPCMFrames;
  8311. ma_uint64 loopPointBegInPCMFrames;
  8312. ma_uint64 loopPointEndInPCMFrames;
  8313. ma_bool32 isLooping;
  8314. ma_uint32 flags;
  8315. } ma_resource_manager_data_source_config;
  8316. MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void);
  8317. typedef enum
  8318. {
  8319. ma_resource_manager_data_supply_type_unknown = 0, /* Used for determining whether or the data supply has been initialized. */
  8320. ma_resource_manager_data_supply_type_encoded, /* Data supply is an encoded buffer. Connector is ma_decoder. */
  8321. ma_resource_manager_data_supply_type_decoded, /* Data supply is a decoded buffer. Connector is ma_audio_buffer. */
  8322. ma_resource_manager_data_supply_type_decoded_paged /* Data supply is a linked list of decoded buffers. Connector is ma_paged_audio_buffer. */
  8323. } ma_resource_manager_data_supply_type;
  8324. typedef struct
  8325. {
  8326. MA_ATOMIC(4, ma_resource_manager_data_supply_type) type; /* Read and written from different threads so needs to be accessed atomically. */
  8327. union
  8328. {
  8329. struct
  8330. {
  8331. const void* pData;
  8332. size_t sizeInBytes;
  8333. } encoded;
  8334. struct
  8335. {
  8336. const void* pData;
  8337. ma_uint64 totalFrameCount;
  8338. ma_uint64 decodedFrameCount;
  8339. ma_format format;
  8340. ma_uint32 channels;
  8341. ma_uint32 sampleRate;
  8342. } decoded;
  8343. struct
  8344. {
  8345. ma_paged_audio_buffer_data data;
  8346. ma_uint64 decodedFrameCount;
  8347. ma_uint32 sampleRate;
  8348. } decodedPaged;
  8349. } backend;
  8350. } ma_resource_manager_data_supply;
  8351. struct ma_resource_manager_data_buffer_node
  8352. {
  8353. ma_uint32 hashedName32; /* The hashed name. This is the key. */
  8354. ma_uint32 refCount;
  8355. 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. */
  8356. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8357. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8358. 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_*()). */
  8359. ma_resource_manager_data_supply data;
  8360. ma_resource_manager_data_buffer_node* pParent;
  8361. ma_resource_manager_data_buffer_node* pChildLo;
  8362. ma_resource_manager_data_buffer_node* pChildHi;
  8363. };
  8364. struct ma_resource_manager_data_buffer
  8365. {
  8366. ma_data_source_base ds; /* Base data source. A data buffer is a data source. */
  8367. ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this buffer. */
  8368. ma_resource_manager_data_buffer_node* pNode; /* The data node. This is reference counted and is what supplies the data. */
  8369. ma_uint32 flags; /* The flags that were passed used to initialize the buffer. */
  8370. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8371. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8372. ma_uint64 seekTargetInPCMFrames; /* Only updated by the public API. Never written nor read from the job thread. */
  8373. ma_bool32 seekToCursorOnNextRead; /* On the next read we need to seek to the frame cursor. */
  8374. 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. */
  8375. MA_ATOMIC(4, ma_bool32) isLooping; /* Can be read and written by different threads at the same time. Must be used atomically. */
  8376. 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. */
  8377. union
  8378. {
  8379. ma_decoder decoder; /* Supply type is ma_resource_manager_data_supply_type_encoded */
  8380. ma_audio_buffer buffer; /* Supply type is ma_resource_manager_data_supply_type_decoded */
  8381. ma_paged_audio_buffer pagedBuffer; /* Supply type is ma_resource_manager_data_supply_type_decoded_paged */
  8382. } connector; /* Connects this object to the node's data supply. */
  8383. };
  8384. struct ma_resource_manager_data_stream
  8385. {
  8386. ma_data_source_base ds; /* Base data source. A data stream is a data source. */
  8387. ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this data stream. */
  8388. ma_uint32 flags; /* The flags that were passed used to initialize the stream. */
  8389. 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. */
  8390. ma_bool32 isDecoderInitialized; /* Required for determining whether or not the decoder should be uninitialized in MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM. */
  8391. ma_uint64 totalLengthInPCMFrames; /* This is calculated when first loaded by the MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM. */
  8392. ma_uint32 relativeCursor; /* The playback cursor, relative to the current page. Only ever accessed by the public API. Never accessed by the job thread. */
  8393. MA_ATOMIC(8, ma_uint64) absoluteCursor; /* The playback cursor, in absolute position starting from the start of the file. */
  8394. 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. */
  8395. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8396. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8397. /* Written by the public API, read by the job thread. */
  8398. 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. */
  8399. /* Written by the job thread, read by the public API. */
  8400. void* pPageData; /* Buffer containing the decoded data of each page. Allocated once at initialization time. */
  8401. MA_ATOMIC(4, ma_uint32) pageFrameCount[2]; /* The number of valid PCM frames in each page. Used to determine the last valid frame. */
  8402. /* Written and read by both the public API and the job thread. These must be atomic. */
  8403. 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. */
  8404. MA_ATOMIC(4, ma_bool32) isDecoderAtEnd; /* Whether or not the decoder has reached the end. */
  8405. 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. */
  8406. 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. */
  8407. };
  8408. struct ma_resource_manager_data_source
  8409. {
  8410. union
  8411. {
  8412. ma_resource_manager_data_buffer buffer;
  8413. ma_resource_manager_data_stream stream;
  8414. } backend; /* Must be the first item because we need the first item to be the data source callbacks for the buffer or stream. */
  8415. ma_uint32 flags; /* The flags that were passed in to ma_resource_manager_data_source_init(). */
  8416. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8417. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8418. };
  8419. typedef struct
  8420. {
  8421. ma_allocation_callbacks allocationCallbacks;
  8422. ma_log* pLog;
  8423. ma_format decodedFormat; /* The decoded format to use. Set to ma_format_unknown (default) to use the file's native format. */
  8424. ma_uint32 decodedChannels; /* The decoded channel count to use. Set to 0 (default) to use the file's native channel count. */
  8425. ma_uint32 decodedSampleRate; /* the decoded sample rate to use. Set to 0 (default) to use the file's native sample rate. */
  8426. ma_uint32 jobThreadCount; /* Set to 0 if you want to self-manage your job threads. Defaults to 1. */
  8427. size_t jobThreadStackSize;
  8428. 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. */
  8429. ma_uint32 flags;
  8430. ma_vfs* pVFS; /* Can be NULL in which case defaults will be used. */
  8431. ma_decoding_backend_vtable** ppCustomDecodingBackendVTables;
  8432. ma_uint32 customDecodingBackendCount;
  8433. void* pCustomDecodingBackendUserData;
  8434. } ma_resource_manager_config;
  8435. MA_API ma_resource_manager_config ma_resource_manager_config_init(void);
  8436. struct ma_resource_manager
  8437. {
  8438. ma_resource_manager_config config;
  8439. ma_resource_manager_data_buffer_node* pRootDataBufferNode; /* The root buffer in the binary tree. */
  8440. #ifndef MA_NO_THREADING
  8441. ma_mutex dataBufferBSTLock; /* For synchronizing access to the data buffer binary tree. */
  8442. ma_thread jobThreads[MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT]; /* The threads for executing jobs. */
  8443. #endif
  8444. ma_job_queue jobQueue; /* Multi-consumer, multi-producer job queue for managing jobs for asynchronous decoding and streaming. */
  8445. ma_default_vfs defaultVFS; /* Only used if a custom VFS is not specified. */
  8446. ma_log log; /* Only used if no log was specified in the config. */
  8447. };
  8448. /* Init. */
  8449. MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager);
  8450. MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager);
  8451. MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager);
  8452. /* Registration. */
  8453. MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags);
  8454. MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags);
  8455. 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. */
  8456. 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);
  8457. 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. */
  8458. 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);
  8459. MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath);
  8460. MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath);
  8461. MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName);
  8462. MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName);
  8463. /* Data Buffers. */
  8464. 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);
  8465. 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);
  8466. 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);
  8467. 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);
  8468. MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer);
  8469. 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);
  8470. MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex);
  8471. 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);
  8472. MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor);
  8473. MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength);
  8474. MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer);
  8475. MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping);
  8476. MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer);
  8477. MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames);
  8478. /* Data Streams. */
  8479. 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);
  8480. 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);
  8481. 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);
  8482. MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream);
  8483. 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);
  8484. MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex);
  8485. 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);
  8486. MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor);
  8487. MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength);
  8488. MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream);
  8489. MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping);
  8490. MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream);
  8491. MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames);
  8492. /* Data Sources. */
  8493. 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);
  8494. 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);
  8495. 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);
  8496. 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);
  8497. MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource);
  8498. 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);
  8499. MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex);
  8500. 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);
  8501. MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor);
  8502. MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength);
  8503. MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource);
  8504. MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping);
  8505. MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource);
  8506. MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames);
  8507. /* Job management. */
  8508. MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob);
  8509. MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager); /* Helper for posting a quit job. */
  8510. MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob);
  8511. 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. */
  8512. 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. */
  8513. #endif /* MA_NO_RESOURCE_MANAGER */
  8514. /************************************************************************************************************************************************************
  8515. Node Graph
  8516. ************************************************************************************************************************************************************/
  8517. #ifndef MA_NO_NODE_GRAPH
  8518. /* Must never exceed 254. */
  8519. #ifndef MA_MAX_NODE_BUS_COUNT
  8520. #define MA_MAX_NODE_BUS_COUNT 254
  8521. #endif
  8522. /* Used internally by miniaudio for memory management. Must never exceed MA_MAX_NODE_BUS_COUNT. */
  8523. #ifndef MA_MAX_NODE_LOCAL_BUS_COUNT
  8524. #define MA_MAX_NODE_LOCAL_BUS_COUNT 2
  8525. #endif
  8526. /* Use this when the bus count is determined by the node instance rather than the vtable. */
  8527. #define MA_NODE_BUS_COUNT_UNKNOWN 255
  8528. typedef struct ma_node_graph ma_node_graph;
  8529. typedef void ma_node;
  8530. /* Node flags. */
  8531. typedef enum
  8532. {
  8533. MA_NODE_FLAG_PASSTHROUGH = 0x00000001,
  8534. MA_NODE_FLAG_CONTINUOUS_PROCESSING = 0x00000002,
  8535. MA_NODE_FLAG_ALLOW_NULL_INPUT = 0x00000004,
  8536. MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES = 0x00000008,
  8537. MA_NODE_FLAG_SILENT_OUTPUT = 0x00000010
  8538. } ma_node_flags;
  8539. /* The playback state of a node. Either started or stopped. */
  8540. typedef enum
  8541. {
  8542. ma_node_state_started = 0,
  8543. ma_node_state_stopped = 1
  8544. } ma_node_state;
  8545. typedef struct
  8546. {
  8547. /*
  8548. Extended processing callback. This callback is used for effects that process input and output
  8549. at different rates (i.e. they perform resampling). This is similar to the simple version, only
  8550. they take two separate frame counts: one for input, and one for output.
  8551. On input, `pFrameCountOut` is equal to the capacity of the output buffer for each bus, whereas
  8552. `pFrameCountIn` will be equal to the number of PCM frames in each of the buffers in `ppFramesIn`.
  8553. On output, set `pFrameCountOut` to the number of PCM frames that were actually output and set
  8554. `pFrameCountIn` to the number of input frames that were consumed.
  8555. */
  8556. void (* onProcess)(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut);
  8557. /*
  8558. A callback for retrieving the number of a input frames that are required to output the
  8559. specified number of output frames. You would only want to implement this when the node performs
  8560. resampling. This is optional, even for nodes that perform resampling, but it does offer a
  8561. small reduction in latency as it allows miniaudio to calculate the exact number of input frames
  8562. to read at a time instead of having to estimate.
  8563. */
  8564. ma_result (* onGetRequiredInputFrameCount)(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount);
  8565. /*
  8566. The number of input buses. This is how many sub-buffers will be contained in the `ppFramesIn`
  8567. parameters of the callbacks above.
  8568. */
  8569. ma_uint8 inputBusCount;
  8570. /*
  8571. The number of output buses. This is how many sub-buffers will be contained in the `ppFramesOut`
  8572. parameters of the callbacks above.
  8573. */
  8574. ma_uint8 outputBusCount;
  8575. /*
  8576. Flags describing characteristics of the node. This is currently just a placeholder for some
  8577. ideas for later on.
  8578. */
  8579. ma_uint32 flags;
  8580. } ma_node_vtable;
  8581. typedef struct
  8582. {
  8583. const ma_node_vtable* vtable; /* Should never be null. Initialization of the node will fail if so. */
  8584. ma_node_state initialState; /* Defaults to ma_node_state_started. */
  8585. 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). */
  8586. 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). */
  8587. 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`. */
  8588. 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`. */
  8589. } ma_node_config;
  8590. MA_API ma_node_config ma_node_config_init(void);
  8591. /*
  8592. A node has multiple output buses. An output bus is attached to an input bus as an item in a linked
  8593. list. Think of the input bus as a linked list, with the output bus being an item in that list.
  8594. */
  8595. typedef struct ma_node_output_bus ma_node_output_bus;
  8596. struct ma_node_output_bus
  8597. {
  8598. /* Immutable. */
  8599. ma_node* pNode; /* The node that owns this output bus. The input node. Will be null for dummy head and tail nodes. */
  8600. ma_uint8 outputBusIndex; /* The index of the output bus on pNode that this output bus represents. */
  8601. ma_uint8 channels; /* The number of channels in the audio stream for this bus. */
  8602. /* Mutable via multiple threads. Must be used atomically. The weird ordering here is for packing reasons. */
  8603. 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. */
  8604. 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_*. */
  8605. MA_ATOMIC(4, ma_uint32) refCount; /* Reference count for some thread-safety when detaching. */
  8606. 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. */
  8607. MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */
  8608. MA_ATOMIC(4, float) volume; /* Linear. */
  8609. MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pNext; /* If null, it's the tail node or detached. */
  8610. MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pPrev; /* If null, it's the head node or detached. */
  8611. MA_ATOMIC(MA_SIZEOF_PTR, ma_node*) pInputNode; /* The node that this output bus is attached to. Required for detaching. */
  8612. };
  8613. /*
  8614. A node has multiple input buses. The output buses of a node are connecting to the input busses of
  8615. another. An input bus is essentially just a linked list of output buses.
  8616. */
  8617. typedef struct ma_node_input_bus ma_node_input_bus;
  8618. struct ma_node_input_bus
  8619. {
  8620. /* Mutable via multiple threads. */
  8621. ma_node_output_bus head; /* Dummy head node for simplifying some lock-free thread-safety stuff. */
  8622. 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. */
  8623. MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */
  8624. /* Set once at startup. */
  8625. ma_uint8 channels; /* The number of channels in the audio stream for this bus. */
  8626. };
  8627. typedef struct ma_node_base ma_node_base;
  8628. struct ma_node_base
  8629. {
  8630. /* These variables are set once at startup. */
  8631. ma_node_graph* pNodeGraph; /* The graph this node belongs to. */
  8632. const ma_node_vtable* vtable;
  8633. 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. */
  8634. ma_uint16 cachedDataCapInFramesPerBus; /* The capacity of the input data cache in frames, per bus. */
  8635. /* These variables are read and written only from the audio thread. */
  8636. ma_uint16 cachedFrameCountOut;
  8637. ma_uint16 cachedFrameCountIn;
  8638. ma_uint16 consumedFrameCountIn;
  8639. /* These variables are read and written between different threads. */
  8640. MA_ATOMIC(4, ma_node_state) state; /* When set to stopped, nothing will be read, regardless of the times in stateTimes. */
  8641. 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. */
  8642. 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()`. */
  8643. ma_uint32 inputBusCount;
  8644. ma_uint32 outputBusCount;
  8645. ma_node_input_bus* pInputBuses;
  8646. ma_node_output_bus* pOutputBuses;
  8647. /* Memory management. */
  8648. ma_node_input_bus _inputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT];
  8649. ma_node_output_bus _outputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT];
  8650. 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. */
  8651. ma_bool32 _ownsHeap; /* If set to true, the node owns the heap allocation and _pHeap will be freed in ma_node_uninit(). */
  8652. };
  8653. MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes);
  8654. MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode);
  8655. MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode);
  8656. MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8657. MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode);
  8658. MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode);
  8659. MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode);
  8660. MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex);
  8661. MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex);
  8662. MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex);
  8663. MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex);
  8664. MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode);
  8665. MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume);
  8666. MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex);
  8667. MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state);
  8668. MA_API ma_node_state ma_node_get_state(const ma_node* pNode);
  8669. MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime);
  8670. MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state);
  8671. MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime);
  8672. MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd);
  8673. MA_API ma_uint64 ma_node_get_time(const ma_node* pNode);
  8674. MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime);
  8675. typedef struct
  8676. {
  8677. ma_uint32 channels;
  8678. ma_uint16 nodeCacheCapInFrames;
  8679. } ma_node_graph_config;
  8680. MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels);
  8681. struct ma_node_graph
  8682. {
  8683. /* Immutable. */
  8684. 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. */
  8685. 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(). */
  8686. ma_uint16 nodeCacheCapInFrames;
  8687. /* Read and written by multiple threads. */
  8688. MA_ATOMIC(4, ma_bool32) isReading;
  8689. };
  8690. MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph);
  8691. MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks);
  8692. MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph);
  8693. MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8694. MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph);
  8695. MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph);
  8696. MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime);
  8697. /* Data source node. 0 input buses, 1 output bus. Used for reading from a data source. */
  8698. typedef struct
  8699. {
  8700. ma_node_config nodeConfig;
  8701. ma_data_source* pDataSource;
  8702. } ma_data_source_node_config;
  8703. MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource);
  8704. typedef struct
  8705. {
  8706. ma_node_base base;
  8707. ma_data_source* pDataSource;
  8708. } ma_data_source_node;
  8709. 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);
  8710. MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8711. MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping);
  8712. MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode);
  8713. /* Splitter Node. 1 input, many outputs. Used for splitting/copying a stream so it can be as input into two separate output nodes. */
  8714. typedef struct
  8715. {
  8716. ma_node_config nodeConfig;
  8717. ma_uint32 channels;
  8718. ma_uint32 outputBusCount;
  8719. } ma_splitter_node_config;
  8720. MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels);
  8721. typedef struct
  8722. {
  8723. ma_node_base base;
  8724. } ma_splitter_node;
  8725. 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);
  8726. MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8727. /*
  8728. Biquad Node
  8729. */
  8730. typedef struct
  8731. {
  8732. ma_node_config nodeConfig;
  8733. ma_biquad_config biquad;
  8734. } ma_biquad_node_config;
  8735. 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);
  8736. typedef struct
  8737. {
  8738. ma_node_base baseNode;
  8739. ma_biquad biquad;
  8740. } ma_biquad_node;
  8741. 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);
  8742. MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode);
  8743. MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8744. /*
  8745. Low Pass Filter Node
  8746. */
  8747. typedef struct
  8748. {
  8749. ma_node_config nodeConfig;
  8750. ma_lpf_config lpf;
  8751. } ma_lpf_node_config;
  8752. MA_API ma_lpf_node_config ma_lpf_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_lpf lpf;
  8757. } ma_lpf_node;
  8758. 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);
  8759. MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode);
  8760. MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8761. /*
  8762. High Pass Filter Node
  8763. */
  8764. typedef struct
  8765. {
  8766. ma_node_config nodeConfig;
  8767. ma_hpf_config hpf;
  8768. } ma_hpf_node_config;
  8769. MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8770. typedef struct
  8771. {
  8772. ma_node_base baseNode;
  8773. ma_hpf hpf;
  8774. } ma_hpf_node;
  8775. 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);
  8776. MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode);
  8777. MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8778. /*
  8779. Band Pass Filter Node
  8780. */
  8781. typedef struct
  8782. {
  8783. ma_node_config nodeConfig;
  8784. ma_bpf_config bpf;
  8785. } ma_bpf_node_config;
  8786. MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8787. typedef struct
  8788. {
  8789. ma_node_base baseNode;
  8790. ma_bpf bpf;
  8791. } ma_bpf_node;
  8792. 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);
  8793. MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode);
  8794. MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8795. /*
  8796. Notching Filter Node
  8797. */
  8798. typedef struct
  8799. {
  8800. ma_node_config nodeConfig;
  8801. ma_notch_config notch;
  8802. } ma_notch_node_config;
  8803. MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
  8804. typedef struct
  8805. {
  8806. ma_node_base baseNode;
  8807. ma_notch2 notch;
  8808. } ma_notch_node;
  8809. 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);
  8810. MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode);
  8811. MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8812. /*
  8813. Peaking Filter Node
  8814. */
  8815. typedef struct
  8816. {
  8817. ma_node_config nodeConfig;
  8818. ma_peak_config peak;
  8819. } ma_peak_node_config;
  8820. MA_API ma_peak_node_config ma_peak_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_peak2 peak;
  8825. } ma_peak_node;
  8826. 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);
  8827. MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode);
  8828. MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8829. /*
  8830. Low Shelf Filter Node
  8831. */
  8832. typedef struct
  8833. {
  8834. ma_node_config nodeConfig;
  8835. ma_loshelf_config loshelf;
  8836. } ma_loshelf_node_config;
  8837. MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8838. typedef struct
  8839. {
  8840. ma_node_base baseNode;
  8841. ma_loshelf2 loshelf;
  8842. } ma_loshelf_node;
  8843. 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);
  8844. MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode);
  8845. MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8846. /*
  8847. High Shelf Filter Node
  8848. */
  8849. typedef struct
  8850. {
  8851. ma_node_config nodeConfig;
  8852. ma_hishelf_config hishelf;
  8853. } ma_hishelf_node_config;
  8854. MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8855. typedef struct
  8856. {
  8857. ma_node_base baseNode;
  8858. ma_hishelf2 hishelf;
  8859. } ma_hishelf_node;
  8860. 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);
  8861. MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode);
  8862. MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8863. typedef struct
  8864. {
  8865. ma_node_config nodeConfig;
  8866. ma_delay_config delay;
  8867. } ma_delay_node_config;
  8868. MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
  8869. typedef struct
  8870. {
  8871. ma_node_base baseNode;
  8872. ma_delay delay;
  8873. } ma_delay_node;
  8874. 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);
  8875. MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8876. MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value);
  8877. MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode);
  8878. MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value);
  8879. MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode);
  8880. MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value);
  8881. MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode);
  8882. #endif /* MA_NO_NODE_GRAPH */
  8883. /* SECTION: miniaudio_engine.h */
  8884. /************************************************************************************************************************************************************
  8885. Engine
  8886. ************************************************************************************************************************************************************/
  8887. #if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH)
  8888. typedef struct ma_engine ma_engine;
  8889. typedef struct ma_sound ma_sound;
  8890. /* Sound flags. */
  8891. typedef enum
  8892. {
  8893. /* Resource manager flags. */
  8894. MA_SOUND_FLAG_STREAM = 0x00000001, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM */
  8895. MA_SOUND_FLAG_DECODE = 0x00000002, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE */
  8896. MA_SOUND_FLAG_ASYNC = 0x00000004, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC */
  8897. MA_SOUND_FLAG_WAIT_INIT = 0x00000008, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT */
  8898. MA_SOUND_FLAG_UNKNOWN_LENGTH = 0x00000010, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH */
  8899. /* ma_sound specific flags. */
  8900. 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. */
  8901. MA_SOUND_FLAG_NO_PITCH = 0x00002000, /* Disable pitch shifting with ma_sound_set_pitch() and ma_sound_group_set_pitch(). This is an optimization. */
  8902. MA_SOUND_FLAG_NO_SPATIALIZATION = 0x00004000 /* Disable spatialization. */
  8903. } ma_sound_flags;
  8904. #ifndef MA_ENGINE_MAX_LISTENERS
  8905. #define MA_ENGINE_MAX_LISTENERS 4
  8906. #endif
  8907. #define MA_LISTENER_INDEX_CLOSEST ((ma_uint8)-1)
  8908. typedef enum
  8909. {
  8910. ma_engine_node_type_sound,
  8911. ma_engine_node_type_group
  8912. } ma_engine_node_type;
  8913. typedef struct
  8914. {
  8915. ma_engine* pEngine;
  8916. ma_engine_node_type type;
  8917. ma_uint32 channelsIn;
  8918. ma_uint32 channelsOut;
  8919. ma_uint32 sampleRate; /* Only used when the type is set to ma_engine_node_type_sound. */
  8920. ma_uint32 volumeSmoothTimeInPCMFrames; /* The number of frames to smooth over volume changes. Defaults to 0 in which case no smoothing is used. */
  8921. ma_mono_expansion_mode monoExpansionMode;
  8922. ma_bool8 isPitchDisabled; /* Pitching can be explicitly disabled with MA_SOUND_FLAG_NO_PITCH to optimize processing. */
  8923. ma_bool8 isSpatializationDisabled; /* Spatialization can be explicitly disabled with MA_SOUND_FLAG_NO_SPATIALIZATION. */
  8924. 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. */
  8925. } ma_engine_node_config;
  8926. MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags);
  8927. /* Base node object for both ma_sound and ma_sound_group. */
  8928. typedef struct
  8929. {
  8930. ma_node_base baseNode; /* Must be the first member for compatiblity with the ma_node API. */
  8931. ma_engine* pEngine; /* A pointer to the engine. Set based on the value from the config. */
  8932. 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. */
  8933. ma_uint32 volumeSmoothTimeInPCMFrames;
  8934. ma_mono_expansion_mode monoExpansionMode;
  8935. ma_fader fader;
  8936. ma_linear_resampler resampler; /* For pitch shift. */
  8937. ma_spatializer spatializer;
  8938. ma_panner panner;
  8939. ma_gainer volumeGainer; /* This will only be used if volumeSmoothTimeInPCMFrames is > 0. */
  8940. ma_atomic_float volume; /* Defaults to 1. */
  8941. MA_ATOMIC(4, float) pitch;
  8942. 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. */
  8943. float oldDopplerPitch; /* For determining whether or not the resampler needs to be updated to take a new doppler pitch into account. */
  8944. 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. */
  8945. MA_ATOMIC(4, ma_bool32) isSpatializationDisabled; /* Set to false by default. When set to false, will not have spatialisation applied. */
  8946. 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. */
  8947. /* When setting a fade, it's not done immediately in ma_sound_set_fade(). It's deferred to the audio thread which means we need to store the settings here. */
  8948. struct
  8949. {
  8950. ma_atomic_float volumeBeg;
  8951. ma_atomic_float volumeEnd;
  8952. ma_atomic_uint64 fadeLengthInFrames; /* <-- Defaults to (~(ma_uint64)0) which is used to indicate that no fade should be applied. */
  8953. ma_atomic_uint64 absoluteGlobalTimeInFrames; /* <-- The time to start the fade. */
  8954. } fadeSettings;
  8955. /* Memory management. */
  8956. ma_bool8 _ownsHeap;
  8957. void* _pHeap;
  8958. } ma_engine_node;
  8959. MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes);
  8960. MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode);
  8961. MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode);
  8962. MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8963. #define MA_SOUND_SOURCE_CHANNEL_COUNT 0xFFFFFFFF
  8964. /* Callback for when a sound reaches the end. */
  8965. typedef void (* ma_sound_end_proc)(void* pUserData, ma_sound* pSound);
  8966. typedef struct
  8967. {
  8968. const char* pFilePath; /* Set this to load from the resource manager. */
  8969. const wchar_t* pFilePathW; /* Set this to load from the resource manager. */
  8970. ma_data_source* pDataSource; /* Set this to load from an existing data source. */
  8971. 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`. */
  8972. ma_uint32 initialAttachmentInputBusIndex; /* The index of the input bus of pInitialAttachment to attach the sound to. */
  8973. 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. */
  8974. 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). */
  8975. ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */
  8976. ma_uint32 flags; /* A combination of MA_SOUND_FLAG_* flags. */
  8977. ma_uint32 volumeSmoothTimeInPCMFrames; /* The number of frames to smooth over volume changes. Defaults to 0 in which case no smoothing is used. */
  8978. ma_uint64 initialSeekPointInPCMFrames; /* Initializes the sound such that it's seeked to this location by default. */
  8979. ma_uint64 rangeBegInPCMFrames;
  8980. ma_uint64 rangeEndInPCMFrames;
  8981. ma_uint64 loopPointBegInPCMFrames;
  8982. ma_uint64 loopPointEndInPCMFrames;
  8983. ma_bool32 isLooping;
  8984. 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_*(). */
  8985. void* pEndCallbackUserData;
  8986. #ifndef MA_NO_RESOURCE_MANAGER
  8987. ma_resource_manager_pipeline_notifications initNotifications;
  8988. #endif
  8989. ma_fence* pDoneFence; /* Deprecated. Use initNotifications instead. Released when the resource manager has finished decoding the entire sound. Not used with streams. */
  8990. } ma_sound_config;
  8991. MA_API ma_sound_config ma_sound_config_init(void); /* Deprecated. Will be removed in version 0.12. Use ma_sound_config_2() instead. */
  8992. 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. */
  8993. struct ma_sound
  8994. {
  8995. ma_engine_node engineNode; /* Must be the first member for compatibility with the ma_node API. */
  8996. ma_data_source* pDataSource;
  8997. 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. */
  8998. MA_ATOMIC(4, ma_bool32) atEnd;
  8999. ma_sound_end_proc endCallback;
  9000. void* pEndCallbackUserData;
  9001. ma_bool8 ownsDataSource;
  9002. /*
  9003. We're declaring a resource manager data source object here to save us a malloc when loading a
  9004. sound via the resource manager, which I *think* will be the most common scenario.
  9005. */
  9006. #ifndef MA_NO_RESOURCE_MANAGER
  9007. ma_resource_manager_data_source* pResourceManagerDataSource;
  9008. #endif
  9009. };
  9010. /* Structure specifically for sounds played with ma_engine_play_sound(). Making this a separate structure to reduce overhead. */
  9011. typedef struct ma_sound_inlined ma_sound_inlined;
  9012. struct ma_sound_inlined
  9013. {
  9014. ma_sound sound;
  9015. ma_sound_inlined* pNext;
  9016. ma_sound_inlined* pPrev;
  9017. };
  9018. /* A sound group is just a sound. */
  9019. typedef ma_sound_config ma_sound_group_config;
  9020. typedef ma_sound ma_sound_group;
  9021. 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. */
  9022. 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. */
  9023. typedef void (* ma_engine_process_proc)(void* pUserData, float* pFramesOut, ma_uint64 frameCount);
  9024. typedef struct
  9025. {
  9026. #if !defined(MA_NO_RESOURCE_MANAGER)
  9027. ma_resource_manager* pResourceManager; /* Can be null in which case a resource manager will be created for you. */
  9028. #endif
  9029. #if !defined(MA_NO_DEVICE_IO)
  9030. ma_context* pContext;
  9031. ma_device* pDevice; /* If set, the caller is responsible for calling ma_engine_data_callback() in the device's data callback. */
  9032. ma_device_id* pPlaybackDeviceID; /* The ID of the playback device to use with the default listener. */
  9033. ma_device_data_proc dataCallback; /* Can be null. Can be used to provide a custom device data callback. */
  9034. ma_device_notification_proc notificationCallback;
  9035. #endif
  9036. ma_log* pLog; /* When set to NULL, will use the context's log. */
  9037. ma_uint32 listenerCount; /* Must be between 1 and MA_ENGINE_MAX_LISTENERS. */
  9038. 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. */
  9039. ma_uint32 sampleRate; /* The sample rate. When set to 0 will use the native channel count of the device. */
  9040. 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.*/
  9041. ma_uint32 periodSizeInMilliseconds; /* Used if periodSizeInFrames is unset. */
  9042. ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. If set to 0, will use gainSmoothTimeInMilliseconds. */
  9043. ma_uint32 gainSmoothTimeInMilliseconds; /* When set to 0, gainSmoothTimeInFrames will be used. If both are set to 0, a default value will be used. */
  9044. 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). */
  9045. ma_allocation_callbacks allocationCallbacks;
  9046. 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(). */
  9047. 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. */
  9048. ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */
  9049. 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. */
  9050. ma_engine_process_proc onProcess; /* Fired at the end of each call to ma_engine_read_pcm_frames(). For engine's that manage their own internal device (the default configuration), this will be fired from the audio thread, and you do not need to call ma_engine_read_pcm_frames() manually in order to trigger this. */
  9051. void* pProcessUserData; /* User data that's passed into onProcess. */
  9052. } ma_engine_config;
  9053. MA_API ma_engine_config ma_engine_config_init(void);
  9054. struct ma_engine
  9055. {
  9056. 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. */
  9057. #if !defined(MA_NO_RESOURCE_MANAGER)
  9058. ma_resource_manager* pResourceManager;
  9059. #endif
  9060. #if !defined(MA_NO_DEVICE_IO)
  9061. ma_device* pDevice; /* Optionally set via the config, otherwise allocated by the engine in ma_engine_init(). */
  9062. #endif
  9063. ma_log* pLog;
  9064. ma_uint32 sampleRate;
  9065. ma_uint32 listenerCount;
  9066. ma_spatializer_listener listeners[MA_ENGINE_MAX_LISTENERS];
  9067. ma_allocation_callbacks allocationCallbacks;
  9068. ma_bool8 ownsResourceManager;
  9069. ma_bool8 ownsDevice;
  9070. ma_spinlock inlinedSoundLock; /* For synchronizing access so the inlined sound list. */
  9071. ma_sound_inlined* pInlinedSoundHead; /* The first inlined sound. Inlined sounds are tracked in a linked list. */
  9072. MA_ATOMIC(4, ma_uint32) inlinedSoundCount; /* The total number of allocated inlined sound objects. Used for debugging. */
  9073. ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. */
  9074. ma_uint32 defaultVolumeSmoothTimeInPCMFrames;
  9075. ma_mono_expansion_mode monoExpansionMode;
  9076. ma_engine_process_proc onProcess;
  9077. void* pProcessUserData;
  9078. };
  9079. MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine);
  9080. MA_API void ma_engine_uninit(ma_engine* pEngine);
  9081. MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  9082. MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine);
  9083. #if !defined(MA_NO_RESOURCE_MANAGER)
  9084. MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine);
  9085. #endif
  9086. MA_API ma_device* ma_engine_get_device(ma_engine* pEngine);
  9087. MA_API ma_log* ma_engine_get_log(ma_engine* pEngine);
  9088. MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine);
  9089. MA_API ma_uint64 ma_engine_get_time_in_pcm_frames(const ma_engine* pEngine);
  9090. MA_API ma_uint64 ma_engine_get_time_in_milliseconds(const ma_engine* pEngine);
  9091. MA_API ma_result ma_engine_set_time_in_pcm_frames(ma_engine* pEngine, ma_uint64 globalTime);
  9092. MA_API ma_result ma_engine_set_time_in_milliseconds(ma_engine* pEngine, ma_uint64 globalTime);
  9093. 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. */
  9094. 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. */
  9095. MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine);
  9096. MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine);
  9097. MA_API ma_result ma_engine_start(ma_engine* pEngine);
  9098. MA_API ma_result ma_engine_stop(ma_engine* pEngine);
  9099. MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume);
  9100. MA_API float ma_engine_get_volume(ma_engine* pEngine);
  9101. MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB);
  9102. MA_API float ma_engine_get_gain_db(ma_engine* pEngine);
  9103. MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine);
  9104. MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ);
  9105. MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9106. MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9107. MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9108. MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9109. MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9110. MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9111. MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  9112. MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  9113. MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  9114. MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9115. MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled);
  9116. MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex);
  9117. #ifndef MA_NO_RESOURCE_MANAGER
  9118. MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex);
  9119. MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup); /* Fire and forget. */
  9120. #endif
  9121. #ifndef MA_NO_RESOURCE_MANAGER
  9122. 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);
  9123. 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);
  9124. 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);
  9125. #endif
  9126. 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);
  9127. MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound);
  9128. MA_API void ma_sound_uninit(ma_sound* pSound);
  9129. MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound);
  9130. MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound);
  9131. MA_API ma_result ma_sound_start(ma_sound* pSound);
  9132. MA_API ma_result ma_sound_stop(ma_sound* pSound);
  9133. MA_API ma_result ma_sound_stop_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 fadeLengthInFrames); /* Will overwrite any scheduled stop and fade. */
  9134. MA_API ma_result ma_sound_stop_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 fadeLengthInFrames); /* Will overwrite any scheduled stop and fade. */
  9135. MA_API void ma_sound_set_volume(ma_sound* pSound, float volume);
  9136. MA_API float ma_sound_get_volume(const ma_sound* pSound);
  9137. MA_API void ma_sound_set_pan(ma_sound* pSound, float pan);
  9138. MA_API float ma_sound_get_pan(const ma_sound* pSound);
  9139. MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode);
  9140. MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound);
  9141. MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch);
  9142. MA_API float ma_sound_get_pitch(const ma_sound* pSound);
  9143. MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled);
  9144. MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound);
  9145. MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex);
  9146. MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound);
  9147. MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound);
  9148. MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound);
  9149. MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z);
  9150. MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound);
  9151. MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z);
  9152. MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound);
  9153. MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z);
  9154. MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound);
  9155. MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel);
  9156. MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound);
  9157. MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning);
  9158. MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound);
  9159. MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff);
  9160. MA_API float ma_sound_get_rolloff(const ma_sound* pSound);
  9161. MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain);
  9162. MA_API float ma_sound_get_min_gain(const ma_sound* pSound);
  9163. MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain);
  9164. MA_API float ma_sound_get_max_gain(const ma_sound* pSound);
  9165. MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance);
  9166. MA_API float ma_sound_get_min_distance(const ma_sound* pSound);
  9167. MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance);
  9168. MA_API float ma_sound_get_max_distance(const ma_sound* pSound);
  9169. MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  9170. MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  9171. MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor);
  9172. MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound);
  9173. MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor);
  9174. MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound);
  9175. MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames);
  9176. MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds);
  9177. MA_API void ma_sound_set_fade_start_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames, ma_uint64 absoluteGlobalTimeInFrames);
  9178. MA_API void ma_sound_set_fade_start_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9179. MA_API float ma_sound_get_current_fade_volume(const ma_sound* pSound);
  9180. MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames);
  9181. MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9182. MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames);
  9183. MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9184. MA_API void ma_sound_set_stop_time_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInFrames, ma_uint64 fadeLengthInFrames);
  9185. MA_API void ma_sound_set_stop_time_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInMilliseconds, ma_uint64 fadeLengthInMilliseconds);
  9186. MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound);
  9187. MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound);
  9188. MA_API ma_uint64 ma_sound_get_time_in_milliseconds(const ma_sound* pSound);
  9189. MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping);
  9190. MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound);
  9191. MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound);
  9192. 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(). */
  9193. 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);
  9194. MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor);
  9195. MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength);
  9196. MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor);
  9197. MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength);
  9198. MA_API ma_result ma_sound_set_end_callback(ma_sound* pSound, ma_sound_end_proc callback, void* pUserData);
  9199. MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup);
  9200. MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup);
  9201. MA_API void ma_sound_group_uninit(ma_sound_group* pGroup);
  9202. MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup);
  9203. MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup);
  9204. MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup);
  9205. MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume);
  9206. MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup);
  9207. MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan);
  9208. MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup);
  9209. MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode);
  9210. MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup);
  9211. MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch);
  9212. MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup);
  9213. MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled);
  9214. MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup);
  9215. MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex);
  9216. MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup);
  9217. MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup);
  9218. MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup);
  9219. MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z);
  9220. MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup);
  9221. MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z);
  9222. MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup);
  9223. MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z);
  9224. MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup);
  9225. MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel);
  9226. MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup);
  9227. MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning);
  9228. MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup);
  9229. MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff);
  9230. MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup);
  9231. MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain);
  9232. MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup);
  9233. MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain);
  9234. MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup);
  9235. MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance);
  9236. MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup);
  9237. MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance);
  9238. MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup);
  9239. MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  9240. MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  9241. MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor);
  9242. MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup);
  9243. MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor);
  9244. MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup);
  9245. MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames);
  9246. MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds);
  9247. MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup);
  9248. MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames);
  9249. MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9250. MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames);
  9251. MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds);
  9252. MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup);
  9253. MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup);
  9254. #endif /* MA_NO_ENGINE */
  9255. /* END SECTION: miniaudio_engine.h */
  9256. #ifdef __cplusplus
  9257. }
  9258. #endif
  9259. #endif /* miniaudio_h */
  9260. /*
  9261. This is for preventing greying out of the implementation section.
  9262. */
  9263. #if defined(Q_CREATOR_RUN) || defined(__INTELLISENSE__) || defined(__CDT_PARSER__)
  9264. #define MINIAUDIO_IMPLEMENTATION
  9265. #endif
  9266. /************************************************************************************************************************************************************
  9267. *************************************************************************************************************************************************************
  9268. IMPLEMENTATION
  9269. *************************************************************************************************************************************************************
  9270. ************************************************************************************************************************************************************/
  9271. #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
  9272. #ifndef miniaudio_c
  9273. #define miniaudio_c
  9274. #include <assert.h>
  9275. #include <limits.h> /* For INT_MAX */
  9276. #include <math.h> /* sin(), etc. */
  9277. #include <stdlib.h> /* For malloc(), free(), wcstombs(). */
  9278. #include <string.h> /* For memset() */
  9279. #include <stdarg.h>
  9280. #include <stdio.h>
  9281. #if !defined(_MSC_VER) && !defined(__DMC__)
  9282. #include <strings.h> /* For strcasecmp(). */
  9283. #include <wchar.h> /* For wcslen(), wcsrtombs() */
  9284. #endif
  9285. #ifdef _MSC_VER
  9286. #include <float.h> /* For _controlfp_s constants */
  9287. #endif
  9288. #if defined(MA_WIN32)
  9289. #include <windows.h>
  9290. /*
  9291. There's a possibility that WIN32_LEAN_AND_MEAN has been defined which will exclude some symbols
  9292. such as STGM_READ and CLSCTL_ALL. We need to check these and define them ourselves if they're
  9293. unavailable.
  9294. */
  9295. #ifndef STGM_READ
  9296. #define STGM_READ 0x00000000L
  9297. #endif
  9298. #ifndef CLSCTX_ALL
  9299. #define CLSCTX_ALL 23
  9300. #endif
  9301. /* IUnknown is used by both the WASAPI and DirectSound backends. It easier to just declare our version here. */
  9302. typedef struct ma_IUnknown ma_IUnknown;
  9303. #endif
  9304. #if !defined(MA_WIN32)
  9305. #include <sched.h>
  9306. #include <sys/time.h> /* select() (used for ma_sleep()). */
  9307. #include <pthread.h>
  9308. #endif
  9309. #ifdef MA_NX
  9310. #include <time.h> /* For nanosleep() */
  9311. #endif
  9312. #include <sys/stat.h> /* For fstat(), etc. */
  9313. #ifdef MA_EMSCRIPTEN
  9314. #include <emscripten/emscripten.h>
  9315. #endif
  9316. /* Architecture Detection */
  9317. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9318. #ifdef _WIN32
  9319. #ifdef _WIN64
  9320. #define MA_64BIT
  9321. #else
  9322. #define MA_32BIT
  9323. #endif
  9324. #endif
  9325. #endif
  9326. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9327. #ifdef __GNUC__
  9328. #ifdef __LP64__
  9329. #define MA_64BIT
  9330. #else
  9331. #define MA_32BIT
  9332. #endif
  9333. #endif
  9334. #endif
  9335. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9336. #include <stdint.h>
  9337. #if INTPTR_MAX == INT64_MAX
  9338. #define MA_64BIT
  9339. #else
  9340. #define MA_32BIT
  9341. #endif
  9342. #endif
  9343. #if defined(__arm__) || defined(_M_ARM)
  9344. #define MA_ARM32
  9345. #endif
  9346. #if defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  9347. #define MA_ARM64
  9348. #endif
  9349. #if defined(__x86_64__) || defined(_M_X64)
  9350. #define MA_X64
  9351. #elif defined(__i386) || defined(_M_IX86)
  9352. #define MA_X86
  9353. #elif defined(MA_ARM32) || defined(MA_ARM64)
  9354. #define MA_ARM
  9355. #endif
  9356. /* Intrinsics Support */
  9357. #if (defined(MA_X64) || defined(MA_X86)) && !defined(__COSMOPOLITAN__)
  9358. #if defined(_MSC_VER) && !defined(__clang__)
  9359. /* MSVC. */
  9360. #if _MSC_VER >= 1400 && !defined(MA_NO_SSE2) /* 2005 */
  9361. #define MA_SUPPORT_SSE2
  9362. #endif
  9363. /*#if _MSC_VER >= 1600 && !defined(MA_NO_AVX)*/ /* 2010 */
  9364. /* #define MA_SUPPORT_AVX*/
  9365. /*#endif*/
  9366. #if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) /* 2012 */
  9367. #define MA_SUPPORT_AVX2
  9368. #endif
  9369. #else
  9370. /* Assume GNUC-style. */
  9371. #if defined(__SSE2__) && !defined(MA_NO_SSE2)
  9372. #define MA_SUPPORT_SSE2
  9373. #endif
  9374. /*#if defined(__AVX__) && !defined(MA_NO_AVX)*/
  9375. /* #define MA_SUPPORT_AVX*/
  9376. /*#endif*/
  9377. #if defined(__AVX2__) && !defined(MA_NO_AVX2)
  9378. #define MA_SUPPORT_AVX2
  9379. #endif
  9380. #endif
  9381. /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
  9382. #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  9383. #if !defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && __has_include(<emmintrin.h>)
  9384. #define MA_SUPPORT_SSE2
  9385. #endif
  9386. /*#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include(<immintrin.h>)*/
  9387. /* #define MA_SUPPORT_AVX*/
  9388. /*#endif*/
  9389. #if !defined(MA_SUPPORT_AVX2) && !defined(MA_NO_AVX2) && __has_include(<immintrin.h>)
  9390. #define MA_SUPPORT_AVX2
  9391. #endif
  9392. #endif
  9393. #if defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX)
  9394. #include <immintrin.h>
  9395. #elif defined(MA_SUPPORT_SSE2)
  9396. #include <emmintrin.h>
  9397. #endif
  9398. #endif
  9399. #if defined(MA_ARM)
  9400. #if !defined(MA_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  9401. #define MA_SUPPORT_NEON
  9402. #include <arm_neon.h>
  9403. #endif
  9404. #endif
  9405. /* Begin globally disabled warnings. */
  9406. #if defined(_MSC_VER)
  9407. #pragma warning(push)
  9408. #pragma warning(disable:4752) /* found Intel(R) Advanced Vector Extensions; consider using /arch:AVX */
  9409. #pragma warning(disable:4049) /* compiler limit : terminating line number emission */
  9410. #endif
  9411. #if defined(MA_X64) || defined(MA_X86)
  9412. #if defined(_MSC_VER) && !defined(__clang__)
  9413. #if _MSC_VER >= 1400
  9414. #include <intrin.h>
  9415. static MA_INLINE void ma_cpuid(int info[4], int fid)
  9416. {
  9417. __cpuid(info, fid);
  9418. }
  9419. #else
  9420. #define MA_NO_CPUID
  9421. #endif
  9422. #if _MSC_VER >= 1600 && (defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219)
  9423. static MA_INLINE unsigned __int64 ma_xgetbv(int reg)
  9424. {
  9425. return _xgetbv(reg);
  9426. }
  9427. #else
  9428. #define MA_NO_XGETBV
  9429. #endif
  9430. #elif (defined(__GNUC__) || defined(__clang__)) && !defined(MA_ANDROID)
  9431. static MA_INLINE void ma_cpuid(int info[4], int fid)
  9432. {
  9433. /*
  9434. 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
  9435. 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
  9436. supporting different assembly dialects.
  9437. What's basically happening is that we're saving and restoring the ebx register manually.
  9438. */
  9439. #if defined(MA_X86) && defined(__PIC__)
  9440. __asm__ __volatile__ (
  9441. "xchg{l} {%%}ebx, %k1;"
  9442. "cpuid;"
  9443. "xchg{l} {%%}ebx, %k1;"
  9444. : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  9445. );
  9446. #else
  9447. __asm__ __volatile__ (
  9448. "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  9449. );
  9450. #endif
  9451. }
  9452. static MA_INLINE ma_uint64 ma_xgetbv(int reg)
  9453. {
  9454. unsigned int hi;
  9455. unsigned int lo;
  9456. __asm__ __volatile__ (
  9457. "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg)
  9458. );
  9459. return ((ma_uint64)hi << 32) | (ma_uint64)lo;
  9460. }
  9461. #else
  9462. #define MA_NO_CPUID
  9463. #define MA_NO_XGETBV
  9464. #endif
  9465. #else
  9466. #define MA_NO_CPUID
  9467. #define MA_NO_XGETBV
  9468. #endif
  9469. static MA_INLINE ma_bool32 ma_has_sse2(void)
  9470. {
  9471. #if defined(MA_SUPPORT_SSE2)
  9472. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_SSE2)
  9473. #if defined(MA_X64)
  9474. return MA_TRUE; /* 64-bit targets always support SSE2. */
  9475. #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  9476. return MA_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
  9477. #else
  9478. #if defined(MA_NO_CPUID)
  9479. return MA_FALSE;
  9480. #else
  9481. int info[4];
  9482. ma_cpuid(info, 1);
  9483. return (info[3] & (1 << 26)) != 0;
  9484. #endif
  9485. #endif
  9486. #else
  9487. return MA_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
  9488. #endif
  9489. #else
  9490. return MA_FALSE; /* No compiler support. */
  9491. #endif
  9492. }
  9493. #if 0
  9494. static MA_INLINE ma_bool32 ma_has_avx()
  9495. {
  9496. #if defined(MA_SUPPORT_AVX)
  9497. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX)
  9498. #if defined(_AVX_) || defined(__AVX__)
  9499. return MA_TRUE; /* If the compiler is allowed to freely generate AVX code we can assume support. */
  9500. #else
  9501. /* AVX requires both CPU and OS support. */
  9502. #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
  9503. return MA_FALSE;
  9504. #else
  9505. int info[4];
  9506. ma_cpuid(info, 1);
  9507. if (((info[2] & (1 << 27)) != 0) && ((info[2] & (1 << 28)) != 0)) {
  9508. ma_uint64 xrc = ma_xgetbv(0);
  9509. if ((xrc & 0x06) == 0x06) {
  9510. return MA_TRUE;
  9511. } else {
  9512. return MA_FALSE;
  9513. }
  9514. } else {
  9515. return MA_FALSE;
  9516. }
  9517. #endif
  9518. #endif
  9519. #else
  9520. return MA_FALSE; /* AVX is only supported on x86 and x64 architectures. */
  9521. #endif
  9522. #else
  9523. return MA_FALSE; /* No compiler support. */
  9524. #endif
  9525. }
  9526. #endif
  9527. static MA_INLINE ma_bool32 ma_has_avx2(void)
  9528. {
  9529. #if defined(MA_SUPPORT_AVX2)
  9530. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX2)
  9531. #if defined(_AVX2_) || defined(__AVX2__)
  9532. return MA_TRUE; /* If the compiler is allowed to freely generate AVX2 code we can assume support. */
  9533. #else
  9534. /* AVX2 requires both CPU and OS support. */
  9535. #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
  9536. return MA_FALSE;
  9537. #else
  9538. int info1[4];
  9539. int info7[4];
  9540. ma_cpuid(info1, 1);
  9541. ma_cpuid(info7, 7);
  9542. if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 5)) != 0)) {
  9543. ma_uint64 xrc = ma_xgetbv(0);
  9544. if ((xrc & 0x06) == 0x06) {
  9545. return MA_TRUE;
  9546. } else {
  9547. return MA_FALSE;
  9548. }
  9549. } else {
  9550. return MA_FALSE;
  9551. }
  9552. #endif
  9553. #endif
  9554. #else
  9555. return MA_FALSE; /* AVX2 is only supported on x86 and x64 architectures. */
  9556. #endif
  9557. #else
  9558. return MA_FALSE; /* No compiler support. */
  9559. #endif
  9560. }
  9561. static MA_INLINE ma_bool32 ma_has_neon(void)
  9562. {
  9563. #if defined(MA_SUPPORT_NEON)
  9564. #if defined(MA_ARM) && !defined(MA_NO_NEON)
  9565. #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  9566. return MA_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
  9567. #else
  9568. /* TODO: Runtime check. */
  9569. return MA_FALSE;
  9570. #endif
  9571. #else
  9572. return MA_FALSE; /* NEON is only supported on ARM architectures. */
  9573. #endif
  9574. #else
  9575. return MA_FALSE; /* No compiler support. */
  9576. #endif
  9577. }
  9578. #if defined(__has_builtin)
  9579. #define MA_COMPILER_HAS_BUILTIN(x) __has_builtin(x)
  9580. #else
  9581. #define MA_COMPILER_HAS_BUILTIN(x) 0
  9582. #endif
  9583. #ifndef MA_ASSUME
  9584. #if MA_COMPILER_HAS_BUILTIN(__builtin_assume)
  9585. #define MA_ASSUME(x) __builtin_assume(x)
  9586. #elif MA_COMPILER_HAS_BUILTIN(__builtin_unreachable)
  9587. #define MA_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while (0)
  9588. #elif defined(_MSC_VER)
  9589. #define MA_ASSUME(x) __assume(x)
  9590. #else
  9591. #define MA_ASSUME(x) (void)(x)
  9592. #endif
  9593. #endif
  9594. #ifndef MA_RESTRICT
  9595. #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
  9596. #define MA_RESTRICT __restrict
  9597. #else
  9598. #define MA_RESTRICT
  9599. #endif
  9600. #endif
  9601. #if defined(_MSC_VER) && _MSC_VER >= 1400
  9602. #define MA_HAS_BYTESWAP16_INTRINSIC
  9603. #define MA_HAS_BYTESWAP32_INTRINSIC
  9604. #define MA_HAS_BYTESWAP64_INTRINSIC
  9605. #elif defined(__clang__)
  9606. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap16)
  9607. #define MA_HAS_BYTESWAP16_INTRINSIC
  9608. #endif
  9609. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap32)
  9610. #define MA_HAS_BYTESWAP32_INTRINSIC
  9611. #endif
  9612. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap64)
  9613. #define MA_HAS_BYTESWAP64_INTRINSIC
  9614. #endif
  9615. #elif defined(__GNUC__)
  9616. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  9617. #define MA_HAS_BYTESWAP32_INTRINSIC
  9618. #define MA_HAS_BYTESWAP64_INTRINSIC
  9619. #endif
  9620. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  9621. #define MA_HAS_BYTESWAP16_INTRINSIC
  9622. #endif
  9623. #endif
  9624. static MA_INLINE ma_bool32 ma_is_little_endian(void)
  9625. {
  9626. #if defined(MA_X86) || defined(MA_X64)
  9627. return MA_TRUE;
  9628. #else
  9629. int n = 1;
  9630. return (*(char*)&n) == 1;
  9631. #endif
  9632. }
  9633. static MA_INLINE ma_bool32 ma_is_big_endian(void)
  9634. {
  9635. return !ma_is_little_endian();
  9636. }
  9637. static MA_INLINE ma_uint32 ma_swap_endian_uint32(ma_uint32 n)
  9638. {
  9639. #ifdef MA_HAS_BYTESWAP32_INTRINSIC
  9640. #if defined(_MSC_VER)
  9641. return _byteswap_ulong(n);
  9642. #elif defined(__GNUC__) || defined(__clang__)
  9643. #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. */
  9644. /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
  9645. ma_uint32 r;
  9646. __asm__ __volatile__ (
  9647. #if defined(MA_64BIT)
  9648. "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! */
  9649. #else
  9650. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  9651. #endif
  9652. );
  9653. return r;
  9654. #else
  9655. return __builtin_bswap32(n);
  9656. #endif
  9657. #else
  9658. #error "This compiler does not support the byte swap intrinsic."
  9659. #endif
  9660. #else
  9661. return ((n & 0xFF000000) >> 24) |
  9662. ((n & 0x00FF0000) >> 8) |
  9663. ((n & 0x0000FF00) << 8) |
  9664. ((n & 0x000000FF) << 24);
  9665. #endif
  9666. }
  9667. #if !defined(MA_EMSCRIPTEN)
  9668. #ifdef MA_WIN32
  9669. static void ma_sleep__win32(ma_uint32 milliseconds)
  9670. {
  9671. Sleep((DWORD)milliseconds);
  9672. }
  9673. #endif
  9674. #ifdef MA_POSIX
  9675. static void ma_sleep__posix(ma_uint32 milliseconds)
  9676. {
  9677. #ifdef MA_EMSCRIPTEN
  9678. (void)milliseconds;
  9679. MA_ASSERT(MA_FALSE); /* The Emscripten build should never sleep. */
  9680. #else
  9681. #if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L) || defined(MA_NX)
  9682. struct timespec ts;
  9683. ts.tv_sec = milliseconds / 1000;
  9684. ts.tv_nsec = milliseconds % 1000 * 1000000;
  9685. nanosleep(&ts, NULL);
  9686. #else
  9687. struct timeval tv;
  9688. tv.tv_sec = milliseconds / 1000;
  9689. tv.tv_usec = milliseconds % 1000 * 1000;
  9690. select(0, NULL, NULL, NULL, &tv);
  9691. #endif
  9692. #endif
  9693. }
  9694. #endif
  9695. static MA_INLINE void ma_sleep(ma_uint32 milliseconds)
  9696. {
  9697. #ifdef MA_WIN32
  9698. ma_sleep__win32(milliseconds);
  9699. #endif
  9700. #ifdef MA_POSIX
  9701. ma_sleep__posix(milliseconds);
  9702. #endif
  9703. }
  9704. #endif
  9705. static MA_INLINE void ma_yield(void)
  9706. {
  9707. #if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
  9708. /* x86/x64 */
  9709. #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)) && !defined(__clang__)
  9710. #if _MSC_VER >= 1400
  9711. _mm_pause();
  9712. #else
  9713. #if defined(__DMC__)
  9714. /* Digital Mars does not recognize the PAUSE opcode. Fall back to NOP. */
  9715. __asm nop;
  9716. #else
  9717. __asm pause;
  9718. #endif
  9719. #endif
  9720. #else
  9721. __asm__ __volatile__ ("pause");
  9722. #endif
  9723. #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__)
  9724. /* ARM */
  9725. #if defined(_MSC_VER)
  9726. /* 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. */
  9727. __yield();
  9728. #else
  9729. __asm__ __volatile__ ("yield"); /* ARMv6K/ARMv6T2 and above. */
  9730. #endif
  9731. #else
  9732. /* Unknown or unsupported architecture. No-op. */
  9733. #endif
  9734. }
  9735. #define MA_MM_DENORMALS_ZERO_MASK 0x0040
  9736. #define MA_MM_FLUSH_ZERO_MASK 0x8000
  9737. static MA_INLINE unsigned int ma_disable_denormals(void)
  9738. {
  9739. unsigned int prevState;
  9740. #if defined(_MSC_VER)
  9741. {
  9742. /*
  9743. Older versions of Visual Studio don't support the "safe" versions of _controlfp_s(). I don't
  9744. know which version of Visual Studio first added support for _controlfp_s(), but I do know
  9745. that VC6 lacks support. _MSC_VER = 1200 is VC6, but if you get compilation errors on older
  9746. versions of Visual Studio, let me know and I'll make the necessary adjustment.
  9747. */
  9748. #if _MSC_VER <= 1200
  9749. {
  9750. prevState = _statusfp();
  9751. _controlfp(prevState | _DN_FLUSH, _MCW_DN);
  9752. }
  9753. #else
  9754. {
  9755. unsigned int unused;
  9756. _controlfp_s(&prevState, 0, 0);
  9757. _controlfp_s(&unused, prevState | _DN_FLUSH, _MCW_DN);
  9758. }
  9759. #endif
  9760. }
  9761. #elif defined(MA_X86) || defined(MA_X64)
  9762. {
  9763. #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__) || defined(__COSMOPOLITAN__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */
  9764. {
  9765. prevState = _mm_getcsr();
  9766. _mm_setcsr(prevState | MA_MM_DENORMALS_ZERO_MASK | MA_MM_FLUSH_ZERO_MASK);
  9767. }
  9768. #else
  9769. {
  9770. /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */
  9771. prevState = 0;
  9772. }
  9773. #endif
  9774. }
  9775. #else
  9776. {
  9777. /* Unknown or unsupported architecture. No-op. */
  9778. prevState = 0;
  9779. }
  9780. #endif
  9781. return prevState;
  9782. }
  9783. static MA_INLINE void ma_restore_denormals(unsigned int prevState)
  9784. {
  9785. #if defined(_MSC_VER)
  9786. {
  9787. /* Older versions of Visual Studio do not support _controlfp_s(). See ma_disable_denormals(). */
  9788. #if _MSC_VER <= 1200
  9789. {
  9790. _controlfp(prevState, _MCW_DN);
  9791. }
  9792. #else
  9793. {
  9794. unsigned int unused;
  9795. _controlfp_s(&unused, prevState, _MCW_DN);
  9796. }
  9797. #endif
  9798. }
  9799. #elif defined(MA_X86) || defined(MA_X64)
  9800. {
  9801. #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__) || defined(__COSMOPOLITAN__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */
  9802. {
  9803. _mm_setcsr(prevState);
  9804. }
  9805. #else
  9806. {
  9807. /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */
  9808. (void)prevState;
  9809. }
  9810. #endif
  9811. }
  9812. #else
  9813. {
  9814. /* Unknown or unsupported architecture. No-op. */
  9815. (void)prevState;
  9816. }
  9817. #endif
  9818. }
  9819. #ifdef MA_ANDROID
  9820. #include <sys/system_properties.h>
  9821. int ma_android_sdk_version()
  9822. {
  9823. char sdkVersion[PROP_VALUE_MAX + 1] = {0, };
  9824. if (__system_property_get("ro.build.version.sdk", sdkVersion)) {
  9825. return atoi(sdkVersion);
  9826. }
  9827. return 0;
  9828. }
  9829. #endif
  9830. #ifndef MA_COINIT_VALUE
  9831. #define MA_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED */
  9832. #endif
  9833. #ifndef MA_FLT_MAX
  9834. #ifdef FLT_MAX
  9835. #define MA_FLT_MAX FLT_MAX
  9836. #else
  9837. #define MA_FLT_MAX 3.402823466e+38F
  9838. #endif
  9839. #endif
  9840. #ifndef MA_PI
  9841. #define MA_PI 3.14159265358979323846264f
  9842. #endif
  9843. #ifndef MA_PI_D
  9844. #define MA_PI_D 3.14159265358979323846264
  9845. #endif
  9846. #ifndef MA_TAU
  9847. #define MA_TAU 6.28318530717958647693f
  9848. #endif
  9849. #ifndef MA_TAU_D
  9850. #define MA_TAU_D 6.28318530717958647693
  9851. #endif
  9852. /* The default format when ma_format_unknown (0) is requested when initializing a device. */
  9853. #ifndef MA_DEFAULT_FORMAT
  9854. #define MA_DEFAULT_FORMAT ma_format_f32
  9855. #endif
  9856. /* The default channel count to use when 0 is used when initializing a device. */
  9857. #ifndef MA_DEFAULT_CHANNELS
  9858. #define MA_DEFAULT_CHANNELS 2
  9859. #endif
  9860. /* The default sample rate to use when 0 is used when initializing a device. */
  9861. #ifndef MA_DEFAULT_SAMPLE_RATE
  9862. #define MA_DEFAULT_SAMPLE_RATE 48000
  9863. #endif
  9864. /* Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. */
  9865. #ifndef MA_DEFAULT_PERIODS
  9866. #define MA_DEFAULT_PERIODS 3
  9867. #endif
  9868. /* The default period size in milliseconds for low latency mode. */
  9869. #ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY
  9870. #define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY 10
  9871. #endif
  9872. /* The default buffer size in milliseconds for conservative mode. */
  9873. #ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE
  9874. #define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE 100
  9875. #endif
  9876. /* The default LPF filter order for linear resampling. Note that this is clamped to MA_MAX_FILTER_ORDER. */
  9877. #ifndef MA_DEFAULT_RESAMPLER_LPF_ORDER
  9878. #if MA_MAX_FILTER_ORDER >= 4
  9879. #define MA_DEFAULT_RESAMPLER_LPF_ORDER 4
  9880. #else
  9881. #define MA_DEFAULT_RESAMPLER_LPF_ORDER MA_MAX_FILTER_ORDER
  9882. #endif
  9883. #endif
  9884. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  9885. #pragma GCC diagnostic push
  9886. #pragma GCC diagnostic ignored "-Wunused-variable"
  9887. #endif
  9888. /* Standard sample rates, in order of priority. */
  9889. static ma_uint32 g_maStandardSampleRatePriorities[] = {
  9890. (ma_uint32)ma_standard_sample_rate_48000,
  9891. (ma_uint32)ma_standard_sample_rate_44100,
  9892. (ma_uint32)ma_standard_sample_rate_32000,
  9893. (ma_uint32)ma_standard_sample_rate_24000,
  9894. (ma_uint32)ma_standard_sample_rate_22050,
  9895. (ma_uint32)ma_standard_sample_rate_88200,
  9896. (ma_uint32)ma_standard_sample_rate_96000,
  9897. (ma_uint32)ma_standard_sample_rate_176400,
  9898. (ma_uint32)ma_standard_sample_rate_192000,
  9899. (ma_uint32)ma_standard_sample_rate_16000,
  9900. (ma_uint32)ma_standard_sample_rate_11025,
  9901. (ma_uint32)ma_standard_sample_rate_8000,
  9902. (ma_uint32)ma_standard_sample_rate_352800,
  9903. (ma_uint32)ma_standard_sample_rate_384000
  9904. };
  9905. static MA_INLINE ma_bool32 ma_is_standard_sample_rate(ma_uint32 sampleRate)
  9906. {
  9907. ma_uint32 iSampleRate;
  9908. for (iSampleRate = 0; iSampleRate < sizeof(g_maStandardSampleRatePriorities) / sizeof(g_maStandardSampleRatePriorities[0]); iSampleRate += 1) {
  9909. if (g_maStandardSampleRatePriorities[iSampleRate] == sampleRate) {
  9910. return MA_TRUE;
  9911. }
  9912. }
  9913. /* Getting here means the sample rate is not supported. */
  9914. return MA_FALSE;
  9915. }
  9916. static ma_format g_maFormatPriorities[] = {
  9917. ma_format_s16, /* Most common */
  9918. ma_format_f32,
  9919. /*ma_format_s24_32,*/ /* Clean alignment */
  9920. ma_format_s32,
  9921. ma_format_s24, /* Unclean alignment */
  9922. ma_format_u8 /* Low quality */
  9923. };
  9924. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  9925. #pragma GCC diagnostic pop
  9926. #endif
  9927. MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
  9928. {
  9929. if (pMajor) {
  9930. *pMajor = MA_VERSION_MAJOR;
  9931. }
  9932. if (pMinor) {
  9933. *pMinor = MA_VERSION_MINOR;
  9934. }
  9935. if (pRevision) {
  9936. *pRevision = MA_VERSION_REVISION;
  9937. }
  9938. }
  9939. MA_API const char* ma_version_string(void)
  9940. {
  9941. return MA_VERSION_STRING;
  9942. }
  9943. /******************************************************************************
  9944. Standard Library Stuff
  9945. ******************************************************************************/
  9946. #ifndef MA_ASSERT
  9947. #define MA_ASSERT(condition) assert(condition)
  9948. #endif
  9949. #ifndef MA_MALLOC
  9950. #define MA_MALLOC(sz) malloc((sz))
  9951. #endif
  9952. #ifndef MA_REALLOC
  9953. #define MA_REALLOC(p, sz) realloc((p), (sz))
  9954. #endif
  9955. #ifndef MA_FREE
  9956. #define MA_FREE(p) free((p))
  9957. #endif
  9958. static MA_INLINE void ma_zero_memory_default(void* p, size_t sz)
  9959. {
  9960. if (p == NULL) {
  9961. MA_ASSERT(sz == 0); /* If this is triggered there's an error with the calling code. */
  9962. return;
  9963. }
  9964. if (sz > 0) {
  9965. memset(p, 0, sz);
  9966. }
  9967. }
  9968. #ifndef MA_ZERO_MEMORY
  9969. #define MA_ZERO_MEMORY(p, sz) ma_zero_memory_default((p), (sz))
  9970. #endif
  9971. #ifndef MA_COPY_MEMORY
  9972. #define MA_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  9973. #endif
  9974. #ifndef MA_MOVE_MEMORY
  9975. #define MA_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz))
  9976. #endif
  9977. #define MA_ZERO_OBJECT(p) MA_ZERO_MEMORY((p), sizeof(*(p)))
  9978. #define ma_countof(x) (sizeof(x) / sizeof(x[0]))
  9979. #define ma_max(x, y) (((x) > (y)) ? (x) : (y))
  9980. #define ma_min(x, y) (((x) < (y)) ? (x) : (y))
  9981. #define ma_abs(x) (((x) > 0) ? (x) : -(x))
  9982. #define ma_clamp(x, lo, hi) (ma_max(lo, ma_min(x, hi)))
  9983. #define ma_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset))
  9984. #define ma_align(x, a) (((x) + ((a)-1)) & ~((a)-1))
  9985. #define ma_align_64(x) ma_align(x, 8)
  9986. #define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels))
  9987. static MA_INLINE double ma_sind(double x)
  9988. {
  9989. /* TODO: Implement custom sin(x). */
  9990. return sin(x);
  9991. }
  9992. static MA_INLINE double ma_expd(double x)
  9993. {
  9994. /* TODO: Implement custom exp(x). */
  9995. return exp(x);
  9996. }
  9997. static MA_INLINE double ma_logd(double x)
  9998. {
  9999. /* TODO: Implement custom log(x). */
  10000. return log(x);
  10001. }
  10002. static MA_INLINE double ma_powd(double x, double y)
  10003. {
  10004. /* TODO: Implement custom pow(x, y). */
  10005. return pow(x, y);
  10006. }
  10007. static MA_INLINE double ma_sqrtd(double x)
  10008. {
  10009. /* TODO: Implement custom sqrt(x). */
  10010. return sqrt(x);
  10011. }
  10012. static MA_INLINE float ma_rsqrtf(float x)
  10013. {
  10014. #if defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && (defined(MA_X64) || (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__))
  10015. {
  10016. /*
  10017. For SSE we can use RSQRTSS.
  10018. This Stack Overflow post suggests that compilers don't necessarily generate optimal code
  10019. when using intrinsics:
  10020. https://web.archive.org/web/20221211012522/https://stackoverflow.com/questions/32687079/getting-fewest-instructions-for-rsqrtss-wrapper
  10021. I'm going to do something similar here, but a bit simpler.
  10022. */
  10023. #if defined(__GNUC__) || defined(__clang__)
  10024. {
  10025. float result;
  10026. __asm__ __volatile__("rsqrtss %1, %0" : "=x"(result) : "x"(x));
  10027. return result;
  10028. }
  10029. #else
  10030. {
  10031. return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ps1(x)));
  10032. }
  10033. #endif
  10034. }
  10035. #else
  10036. {
  10037. return 1 / (float)ma_sqrtd(x);
  10038. }
  10039. #endif
  10040. }
  10041. static MA_INLINE float ma_sinf(float x)
  10042. {
  10043. return (float)ma_sind((float)x);
  10044. }
  10045. static MA_INLINE double ma_cosd(double x)
  10046. {
  10047. return ma_sind((MA_PI_D*0.5) - x);
  10048. }
  10049. static MA_INLINE float ma_cosf(float x)
  10050. {
  10051. return (float)ma_cosd((float)x);
  10052. }
  10053. static MA_INLINE double ma_log10d(double x)
  10054. {
  10055. return ma_logd(x) * 0.43429448190325182765;
  10056. }
  10057. static MA_INLINE float ma_powf(float x, float y)
  10058. {
  10059. return (float)ma_powd((double)x, (double)y);
  10060. }
  10061. static MA_INLINE float ma_log10f(float x)
  10062. {
  10063. return (float)ma_log10d((double)x);
  10064. }
  10065. static MA_INLINE double ma_degrees_to_radians(double degrees)
  10066. {
  10067. return degrees * 0.01745329252;
  10068. }
  10069. static MA_INLINE double ma_radians_to_degrees(double radians)
  10070. {
  10071. return radians * 57.295779512896;
  10072. }
  10073. static MA_INLINE float ma_degrees_to_radians_f(float degrees)
  10074. {
  10075. return degrees * 0.01745329252f;
  10076. }
  10077. static MA_INLINE float ma_radians_to_degrees_f(float radians)
  10078. {
  10079. return radians * 57.295779512896f;
  10080. }
  10081. /*
  10082. Return Values:
  10083. 0: Success
  10084. 22: EINVAL
  10085. 34: ERANGE
  10086. Not using symbolic constants for errors because I want to avoid #including errno.h
  10087. These are marked as no-inline because of some bad code generation by Clang. None of these functions
  10088. are used in any performance-critical code within miniaudio.
  10089. */
  10090. MA_API MA_NO_INLINE int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src)
  10091. {
  10092. size_t i;
  10093. if (dst == 0) {
  10094. return 22;
  10095. }
  10096. if (dstSizeInBytes == 0) {
  10097. return 34;
  10098. }
  10099. if (src == 0) {
  10100. dst[0] = '\0';
  10101. return 22;
  10102. }
  10103. for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) {
  10104. dst[i] = src[i];
  10105. }
  10106. if (i < dstSizeInBytes) {
  10107. dst[i] = '\0';
  10108. return 0;
  10109. }
  10110. dst[0] = '\0';
  10111. return 34;
  10112. }
  10113. MA_API MA_NO_INLINE int ma_wcscpy_s(wchar_t* dst, size_t dstCap, const wchar_t* src)
  10114. {
  10115. size_t i;
  10116. if (dst == 0) {
  10117. return 22;
  10118. }
  10119. if (dstCap == 0) {
  10120. return 34;
  10121. }
  10122. if (src == 0) {
  10123. dst[0] = '\0';
  10124. return 22;
  10125. }
  10126. for (i = 0; i < dstCap && src[i] != '\0'; ++i) {
  10127. dst[i] = src[i];
  10128. }
  10129. if (i < dstCap) {
  10130. dst[i] = '\0';
  10131. return 0;
  10132. }
  10133. dst[0] = '\0';
  10134. return 34;
  10135. }
  10136. MA_API MA_NO_INLINE int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
  10137. {
  10138. size_t maxcount;
  10139. size_t i;
  10140. if (dst == 0) {
  10141. return 22;
  10142. }
  10143. if (dstSizeInBytes == 0) {
  10144. return 34;
  10145. }
  10146. if (src == 0) {
  10147. dst[0] = '\0';
  10148. return 22;
  10149. }
  10150. maxcount = count;
  10151. if (count == ((size_t)-1) || count >= dstSizeInBytes) { /* -1 = _TRUNCATE */
  10152. maxcount = dstSizeInBytes - 1;
  10153. }
  10154. for (i = 0; i < maxcount && src[i] != '\0'; ++i) {
  10155. dst[i] = src[i];
  10156. }
  10157. if (src[i] == '\0' || i == count || count == ((size_t)-1)) {
  10158. dst[i] = '\0';
  10159. return 0;
  10160. }
  10161. dst[0] = '\0';
  10162. return 34;
  10163. }
  10164. MA_API MA_NO_INLINE int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src)
  10165. {
  10166. char* dstorig;
  10167. if (dst == 0) {
  10168. return 22;
  10169. }
  10170. if (dstSizeInBytes == 0) {
  10171. return 34;
  10172. }
  10173. if (src == 0) {
  10174. dst[0] = '\0';
  10175. return 22;
  10176. }
  10177. dstorig = dst;
  10178. while (dstSizeInBytes > 0 && dst[0] != '\0') {
  10179. dst += 1;
  10180. dstSizeInBytes -= 1;
  10181. }
  10182. if (dstSizeInBytes == 0) {
  10183. return 22; /* Unterminated. */
  10184. }
  10185. while (dstSizeInBytes > 0 && src[0] != '\0') {
  10186. *dst++ = *src++;
  10187. dstSizeInBytes -= 1;
  10188. }
  10189. if (dstSizeInBytes > 0) {
  10190. dst[0] = '\0';
  10191. } else {
  10192. dstorig[0] = '\0';
  10193. return 34;
  10194. }
  10195. return 0;
  10196. }
  10197. MA_API MA_NO_INLINE int ma_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
  10198. {
  10199. char* dstorig;
  10200. if (dst == 0) {
  10201. return 22;
  10202. }
  10203. if (dstSizeInBytes == 0) {
  10204. return 34;
  10205. }
  10206. if (src == 0) {
  10207. return 22;
  10208. }
  10209. dstorig = dst;
  10210. while (dstSizeInBytes > 0 && dst[0] != '\0') {
  10211. dst += 1;
  10212. dstSizeInBytes -= 1;
  10213. }
  10214. if (dstSizeInBytes == 0) {
  10215. return 22; /* Unterminated. */
  10216. }
  10217. if (count == ((size_t)-1)) { /* _TRUNCATE */
  10218. count = dstSizeInBytes - 1;
  10219. }
  10220. while (dstSizeInBytes > 0 && src[0] != '\0' && count > 0) {
  10221. *dst++ = *src++;
  10222. dstSizeInBytes -= 1;
  10223. count -= 1;
  10224. }
  10225. if (dstSizeInBytes > 0) {
  10226. dst[0] = '\0';
  10227. } else {
  10228. dstorig[0] = '\0';
  10229. return 34;
  10230. }
  10231. return 0;
  10232. }
  10233. MA_API MA_NO_INLINE int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix)
  10234. {
  10235. int sign;
  10236. unsigned int valueU;
  10237. char* dstEnd;
  10238. if (dst == NULL || dstSizeInBytes == 0) {
  10239. return 22;
  10240. }
  10241. if (radix < 2 || radix > 36) {
  10242. dst[0] = '\0';
  10243. return 22;
  10244. }
  10245. sign = (value < 0 && radix == 10) ? -1 : 1; /* The negative sign is only used when the base is 10. */
  10246. if (value < 0) {
  10247. valueU = -value;
  10248. } else {
  10249. valueU = value;
  10250. }
  10251. dstEnd = dst;
  10252. do
  10253. {
  10254. int remainder = valueU % radix;
  10255. if (remainder > 9) {
  10256. *dstEnd = (char)((remainder - 10) + 'a');
  10257. } else {
  10258. *dstEnd = (char)(remainder + '0');
  10259. }
  10260. dstEnd += 1;
  10261. dstSizeInBytes -= 1;
  10262. valueU /= radix;
  10263. } while (dstSizeInBytes > 0 && valueU > 0);
  10264. if (dstSizeInBytes == 0) {
  10265. dst[0] = '\0';
  10266. return 22; /* Ran out of room in the output buffer. */
  10267. }
  10268. if (sign < 0) {
  10269. *dstEnd++ = '-';
  10270. dstSizeInBytes -= 1;
  10271. }
  10272. if (dstSizeInBytes == 0) {
  10273. dst[0] = '\0';
  10274. return 22; /* Ran out of room in the output buffer. */
  10275. }
  10276. *dstEnd = '\0';
  10277. /* At this point the string will be reversed. */
  10278. dstEnd -= 1;
  10279. while (dst < dstEnd) {
  10280. char temp = *dst;
  10281. *dst = *dstEnd;
  10282. *dstEnd = temp;
  10283. dst += 1;
  10284. dstEnd -= 1;
  10285. }
  10286. return 0;
  10287. }
  10288. MA_API MA_NO_INLINE int ma_strcmp(const char* str1, const char* str2)
  10289. {
  10290. if (str1 == str2) return 0;
  10291. /* These checks differ from the standard implementation. It's not important, but I prefer it just for sanity. */
  10292. if (str1 == NULL) return -1;
  10293. if (str2 == NULL) return 1;
  10294. for (;;) {
  10295. if (str1[0] == '\0') {
  10296. break;
  10297. }
  10298. if (str1[0] != str2[0]) {
  10299. break;
  10300. }
  10301. str1 += 1;
  10302. str2 += 1;
  10303. }
  10304. return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0];
  10305. }
  10306. MA_API MA_NO_INLINE int ma_strappend(char* dst, size_t dstSize, const char* srcA, const char* srcB)
  10307. {
  10308. int result;
  10309. result = ma_strncpy_s(dst, dstSize, srcA, (size_t)-1);
  10310. if (result != 0) {
  10311. return result;
  10312. }
  10313. result = ma_strncat_s(dst, dstSize, srcB, (size_t)-1);
  10314. if (result != 0) {
  10315. return result;
  10316. }
  10317. return result;
  10318. }
  10319. MA_API MA_NO_INLINE char* ma_copy_string(const char* src, const ma_allocation_callbacks* pAllocationCallbacks)
  10320. {
  10321. size_t sz;
  10322. char* dst;
  10323. if (src == NULL) {
  10324. return NULL;
  10325. }
  10326. sz = strlen(src)+1;
  10327. dst = (char*)ma_malloc(sz, pAllocationCallbacks);
  10328. if (dst == NULL) {
  10329. return NULL;
  10330. }
  10331. ma_strcpy_s(dst, sz, src);
  10332. return dst;
  10333. }
  10334. MA_API MA_NO_INLINE wchar_t* ma_copy_string_w(const wchar_t* src, const ma_allocation_callbacks* pAllocationCallbacks)
  10335. {
  10336. size_t sz = wcslen(src)+1;
  10337. wchar_t* dst = (wchar_t*)ma_malloc(sz * sizeof(*dst), pAllocationCallbacks);
  10338. if (dst == NULL) {
  10339. return NULL;
  10340. }
  10341. ma_wcscpy_s(dst, sz, src);
  10342. return dst;
  10343. }
  10344. #include <errno.h>
  10345. static ma_result ma_result_from_errno(int e)
  10346. {
  10347. if (e == 0) {
  10348. return MA_SUCCESS;
  10349. }
  10350. #ifdef EPERM
  10351. else if (e == EPERM) { return MA_INVALID_OPERATION; }
  10352. #endif
  10353. #ifdef ENOENT
  10354. else if (e == ENOENT) { return MA_DOES_NOT_EXIST; }
  10355. #endif
  10356. #ifdef ESRCH
  10357. else if (e == ESRCH) { return MA_DOES_NOT_EXIST; }
  10358. #endif
  10359. #ifdef EINTR
  10360. else if (e == EINTR) { return MA_INTERRUPT; }
  10361. #endif
  10362. #ifdef EIO
  10363. else if (e == EIO) { return MA_IO_ERROR; }
  10364. #endif
  10365. #ifdef ENXIO
  10366. else if (e == ENXIO) { return MA_DOES_NOT_EXIST; }
  10367. #endif
  10368. #ifdef E2BIG
  10369. else if (e == E2BIG) { return MA_INVALID_ARGS; }
  10370. #endif
  10371. #ifdef ENOEXEC
  10372. else if (e == ENOEXEC) { return MA_INVALID_FILE; }
  10373. #endif
  10374. #ifdef EBADF
  10375. else if (e == EBADF) { return MA_INVALID_FILE; }
  10376. #endif
  10377. #ifdef ECHILD
  10378. else if (e == ECHILD) { return MA_ERROR; }
  10379. #endif
  10380. #ifdef EAGAIN
  10381. else if (e == EAGAIN) { return MA_UNAVAILABLE; }
  10382. #endif
  10383. #ifdef ENOMEM
  10384. else if (e == ENOMEM) { return MA_OUT_OF_MEMORY; }
  10385. #endif
  10386. #ifdef EACCES
  10387. else if (e == EACCES) { return MA_ACCESS_DENIED; }
  10388. #endif
  10389. #ifdef EFAULT
  10390. else if (e == EFAULT) { return MA_BAD_ADDRESS; }
  10391. #endif
  10392. #ifdef ENOTBLK
  10393. else if (e == ENOTBLK) { return MA_ERROR; }
  10394. #endif
  10395. #ifdef EBUSY
  10396. else if (e == EBUSY) { return MA_BUSY; }
  10397. #endif
  10398. #ifdef EEXIST
  10399. else if (e == EEXIST) { return MA_ALREADY_EXISTS; }
  10400. #endif
  10401. #ifdef EXDEV
  10402. else if (e == EXDEV) { return MA_ERROR; }
  10403. #endif
  10404. #ifdef ENODEV
  10405. else if (e == ENODEV) { return MA_DOES_NOT_EXIST; }
  10406. #endif
  10407. #ifdef ENOTDIR
  10408. else if (e == ENOTDIR) { return MA_NOT_DIRECTORY; }
  10409. #endif
  10410. #ifdef EISDIR
  10411. else if (e == EISDIR) { return MA_IS_DIRECTORY; }
  10412. #endif
  10413. #ifdef EINVAL
  10414. else if (e == EINVAL) { return MA_INVALID_ARGS; }
  10415. #endif
  10416. #ifdef ENFILE
  10417. else if (e == ENFILE) { return MA_TOO_MANY_OPEN_FILES; }
  10418. #endif
  10419. #ifdef EMFILE
  10420. else if (e == EMFILE) { return MA_TOO_MANY_OPEN_FILES; }
  10421. #endif
  10422. #ifdef ENOTTY
  10423. else if (e == ENOTTY) { return MA_INVALID_OPERATION; }
  10424. #endif
  10425. #ifdef ETXTBSY
  10426. else if (e == ETXTBSY) { return MA_BUSY; }
  10427. #endif
  10428. #ifdef EFBIG
  10429. else if (e == EFBIG) { return MA_TOO_BIG; }
  10430. #endif
  10431. #ifdef ENOSPC
  10432. else if (e == ENOSPC) { return MA_NO_SPACE; }
  10433. #endif
  10434. #ifdef ESPIPE
  10435. else if (e == ESPIPE) { return MA_BAD_SEEK; }
  10436. #endif
  10437. #ifdef EROFS
  10438. else if (e == EROFS) { return MA_ACCESS_DENIED; }
  10439. #endif
  10440. #ifdef EMLINK
  10441. else if (e == EMLINK) { return MA_TOO_MANY_LINKS; }
  10442. #endif
  10443. #ifdef EPIPE
  10444. else if (e == EPIPE) { return MA_BAD_PIPE; }
  10445. #endif
  10446. #ifdef EDOM
  10447. else if (e == EDOM) { return MA_OUT_OF_RANGE; }
  10448. #endif
  10449. #ifdef ERANGE
  10450. else if (e == ERANGE) { return MA_OUT_OF_RANGE; }
  10451. #endif
  10452. #ifdef EDEADLK
  10453. else if (e == EDEADLK) { return MA_DEADLOCK; }
  10454. #endif
  10455. #ifdef ENAMETOOLONG
  10456. else if (e == ENAMETOOLONG) { return MA_PATH_TOO_LONG; }
  10457. #endif
  10458. #ifdef ENOLCK
  10459. else if (e == ENOLCK) { return MA_ERROR; }
  10460. #endif
  10461. #ifdef ENOSYS
  10462. else if (e == ENOSYS) { return MA_NOT_IMPLEMENTED; }
  10463. #endif
  10464. #ifdef ENOTEMPTY
  10465. else if (e == ENOTEMPTY) { return MA_DIRECTORY_NOT_EMPTY; }
  10466. #endif
  10467. #ifdef ELOOP
  10468. else if (e == ELOOP) { return MA_TOO_MANY_LINKS; }
  10469. #endif
  10470. #ifdef ENOMSG
  10471. else if (e == ENOMSG) { return MA_NO_MESSAGE; }
  10472. #endif
  10473. #ifdef EIDRM
  10474. else if (e == EIDRM) { return MA_ERROR; }
  10475. #endif
  10476. #ifdef ECHRNG
  10477. else if (e == ECHRNG) { return MA_ERROR; }
  10478. #endif
  10479. #ifdef EL2NSYNC
  10480. else if (e == EL2NSYNC) { return MA_ERROR; }
  10481. #endif
  10482. #ifdef EL3HLT
  10483. else if (e == EL3HLT) { return MA_ERROR; }
  10484. #endif
  10485. #ifdef EL3RST
  10486. else if (e == EL3RST) { return MA_ERROR; }
  10487. #endif
  10488. #ifdef ELNRNG
  10489. else if (e == ELNRNG) { return MA_OUT_OF_RANGE; }
  10490. #endif
  10491. #ifdef EUNATCH
  10492. else if (e == EUNATCH) { return MA_ERROR; }
  10493. #endif
  10494. #ifdef ENOCSI
  10495. else if (e == ENOCSI) { return MA_ERROR; }
  10496. #endif
  10497. #ifdef EL2HLT
  10498. else if (e == EL2HLT) { return MA_ERROR; }
  10499. #endif
  10500. #ifdef EBADE
  10501. else if (e == EBADE) { return MA_ERROR; }
  10502. #endif
  10503. #ifdef EBADR
  10504. else if (e == EBADR) { return MA_ERROR; }
  10505. #endif
  10506. #ifdef EXFULL
  10507. else if (e == EXFULL) { return MA_ERROR; }
  10508. #endif
  10509. #ifdef ENOANO
  10510. else if (e == ENOANO) { return MA_ERROR; }
  10511. #endif
  10512. #ifdef EBADRQC
  10513. else if (e == EBADRQC) { return MA_ERROR; }
  10514. #endif
  10515. #ifdef EBADSLT
  10516. else if (e == EBADSLT) { return MA_ERROR; }
  10517. #endif
  10518. #ifdef EBFONT
  10519. else if (e == EBFONT) { return MA_INVALID_FILE; }
  10520. #endif
  10521. #ifdef ENOSTR
  10522. else if (e == ENOSTR) { return MA_ERROR; }
  10523. #endif
  10524. #ifdef ENODATA
  10525. else if (e == ENODATA) { return MA_NO_DATA_AVAILABLE; }
  10526. #endif
  10527. #ifdef ETIME
  10528. else if (e == ETIME) { return MA_TIMEOUT; }
  10529. #endif
  10530. #ifdef ENOSR
  10531. else if (e == ENOSR) { return MA_NO_DATA_AVAILABLE; }
  10532. #endif
  10533. #ifdef ENONET
  10534. else if (e == ENONET) { return MA_NO_NETWORK; }
  10535. #endif
  10536. #ifdef ENOPKG
  10537. else if (e == ENOPKG) { return MA_ERROR; }
  10538. #endif
  10539. #ifdef EREMOTE
  10540. else if (e == EREMOTE) { return MA_ERROR; }
  10541. #endif
  10542. #ifdef ENOLINK
  10543. else if (e == ENOLINK) { return MA_ERROR; }
  10544. #endif
  10545. #ifdef EADV
  10546. else if (e == EADV) { return MA_ERROR; }
  10547. #endif
  10548. #ifdef ESRMNT
  10549. else if (e == ESRMNT) { return MA_ERROR; }
  10550. #endif
  10551. #ifdef ECOMM
  10552. else if (e == ECOMM) { return MA_ERROR; }
  10553. #endif
  10554. #ifdef EPROTO
  10555. else if (e == EPROTO) { return MA_ERROR; }
  10556. #endif
  10557. #ifdef EMULTIHOP
  10558. else if (e == EMULTIHOP) { return MA_ERROR; }
  10559. #endif
  10560. #ifdef EDOTDOT
  10561. else if (e == EDOTDOT) { return MA_ERROR; }
  10562. #endif
  10563. #ifdef EBADMSG
  10564. else if (e == EBADMSG) { return MA_BAD_MESSAGE; }
  10565. #endif
  10566. #ifdef EOVERFLOW
  10567. else if (e == EOVERFLOW) { return MA_TOO_BIG; }
  10568. #endif
  10569. #ifdef ENOTUNIQ
  10570. else if (e == ENOTUNIQ) { return MA_NOT_UNIQUE; }
  10571. #endif
  10572. #ifdef EBADFD
  10573. else if (e == EBADFD) { return MA_ERROR; }
  10574. #endif
  10575. #ifdef EREMCHG
  10576. else if (e == EREMCHG) { return MA_ERROR; }
  10577. #endif
  10578. #ifdef ELIBACC
  10579. else if (e == ELIBACC) { return MA_ACCESS_DENIED; }
  10580. #endif
  10581. #ifdef ELIBBAD
  10582. else if (e == ELIBBAD) { return MA_INVALID_FILE; }
  10583. #endif
  10584. #ifdef ELIBSCN
  10585. else if (e == ELIBSCN) { return MA_INVALID_FILE; }
  10586. #endif
  10587. #ifdef ELIBMAX
  10588. else if (e == ELIBMAX) { return MA_ERROR; }
  10589. #endif
  10590. #ifdef ELIBEXEC
  10591. else if (e == ELIBEXEC) { return MA_ERROR; }
  10592. #endif
  10593. #ifdef EILSEQ
  10594. else if (e == EILSEQ) { return MA_INVALID_DATA; }
  10595. #endif
  10596. #ifdef ERESTART
  10597. else if (e == ERESTART) { return MA_ERROR; }
  10598. #endif
  10599. #ifdef ESTRPIPE
  10600. else if (e == ESTRPIPE) { return MA_ERROR; }
  10601. #endif
  10602. #ifdef EUSERS
  10603. else if (e == EUSERS) { return MA_ERROR; }
  10604. #endif
  10605. #ifdef ENOTSOCK
  10606. else if (e == ENOTSOCK) { return MA_NOT_SOCKET; }
  10607. #endif
  10608. #ifdef EDESTADDRREQ
  10609. else if (e == EDESTADDRREQ) { return MA_NO_ADDRESS; }
  10610. #endif
  10611. #ifdef EMSGSIZE
  10612. else if (e == EMSGSIZE) { return MA_TOO_BIG; }
  10613. #endif
  10614. #ifdef EPROTOTYPE
  10615. else if (e == EPROTOTYPE) { return MA_BAD_PROTOCOL; }
  10616. #endif
  10617. #ifdef ENOPROTOOPT
  10618. else if (e == ENOPROTOOPT) { return MA_PROTOCOL_UNAVAILABLE; }
  10619. #endif
  10620. #ifdef EPROTONOSUPPORT
  10621. else if (e == EPROTONOSUPPORT) { return MA_PROTOCOL_NOT_SUPPORTED; }
  10622. #endif
  10623. #ifdef ESOCKTNOSUPPORT
  10624. else if (e == ESOCKTNOSUPPORT) { return MA_SOCKET_NOT_SUPPORTED; }
  10625. #endif
  10626. #ifdef EOPNOTSUPP
  10627. else if (e == EOPNOTSUPP) { return MA_INVALID_OPERATION; }
  10628. #endif
  10629. #ifdef EPFNOSUPPORT
  10630. else if (e == EPFNOSUPPORT) { return MA_PROTOCOL_FAMILY_NOT_SUPPORTED; }
  10631. #endif
  10632. #ifdef EAFNOSUPPORT
  10633. else if (e == EAFNOSUPPORT) { return MA_ADDRESS_FAMILY_NOT_SUPPORTED; }
  10634. #endif
  10635. #ifdef EADDRINUSE
  10636. else if (e == EADDRINUSE) { return MA_ALREADY_IN_USE; }
  10637. #endif
  10638. #ifdef EADDRNOTAVAIL
  10639. else if (e == EADDRNOTAVAIL) { return MA_ERROR; }
  10640. #endif
  10641. #ifdef ENETDOWN
  10642. else if (e == ENETDOWN) { return MA_NO_NETWORK; }
  10643. #endif
  10644. #ifdef ENETUNREACH
  10645. else if (e == ENETUNREACH) { return MA_NO_NETWORK; }
  10646. #endif
  10647. #ifdef ENETRESET
  10648. else if (e == ENETRESET) { return MA_NO_NETWORK; }
  10649. #endif
  10650. #ifdef ECONNABORTED
  10651. else if (e == ECONNABORTED) { return MA_NO_NETWORK; }
  10652. #endif
  10653. #ifdef ECONNRESET
  10654. else if (e == ECONNRESET) { return MA_CONNECTION_RESET; }
  10655. #endif
  10656. #ifdef ENOBUFS
  10657. else if (e == ENOBUFS) { return MA_NO_SPACE; }
  10658. #endif
  10659. #ifdef EISCONN
  10660. else if (e == EISCONN) { return MA_ALREADY_CONNECTED; }
  10661. #endif
  10662. #ifdef ENOTCONN
  10663. else if (e == ENOTCONN) { return MA_NOT_CONNECTED; }
  10664. #endif
  10665. #ifdef ESHUTDOWN
  10666. else if (e == ESHUTDOWN) { return MA_ERROR; }
  10667. #endif
  10668. #ifdef ETOOMANYREFS
  10669. else if (e == ETOOMANYREFS) { return MA_ERROR; }
  10670. #endif
  10671. #ifdef ETIMEDOUT
  10672. else if (e == ETIMEDOUT) { return MA_TIMEOUT; }
  10673. #endif
  10674. #ifdef ECONNREFUSED
  10675. else if (e == ECONNREFUSED) { return MA_CONNECTION_REFUSED; }
  10676. #endif
  10677. #ifdef EHOSTDOWN
  10678. else if (e == EHOSTDOWN) { return MA_NO_HOST; }
  10679. #endif
  10680. #ifdef EHOSTUNREACH
  10681. else if (e == EHOSTUNREACH) { return MA_NO_HOST; }
  10682. #endif
  10683. #ifdef EALREADY
  10684. else if (e == EALREADY) { return MA_IN_PROGRESS; }
  10685. #endif
  10686. #ifdef EINPROGRESS
  10687. else if (e == EINPROGRESS) { return MA_IN_PROGRESS; }
  10688. #endif
  10689. #ifdef ESTALE
  10690. else if (e == ESTALE) { return MA_INVALID_FILE; }
  10691. #endif
  10692. #ifdef EUCLEAN
  10693. else if (e == EUCLEAN) { return MA_ERROR; }
  10694. #endif
  10695. #ifdef ENOTNAM
  10696. else if (e == ENOTNAM) { return MA_ERROR; }
  10697. #endif
  10698. #ifdef ENAVAIL
  10699. else if (e == ENAVAIL) { return MA_ERROR; }
  10700. #endif
  10701. #ifdef EISNAM
  10702. else if (e == EISNAM) { return MA_ERROR; }
  10703. #endif
  10704. #ifdef EREMOTEIO
  10705. else if (e == EREMOTEIO) { return MA_IO_ERROR; }
  10706. #endif
  10707. #ifdef EDQUOT
  10708. else if (e == EDQUOT) { return MA_NO_SPACE; }
  10709. #endif
  10710. #ifdef ENOMEDIUM
  10711. else if (e == ENOMEDIUM) { return MA_DOES_NOT_EXIST; }
  10712. #endif
  10713. #ifdef EMEDIUMTYPE
  10714. else if (e == EMEDIUMTYPE) { return MA_ERROR; }
  10715. #endif
  10716. #ifdef ECANCELED
  10717. else if (e == ECANCELED) { return MA_CANCELLED; }
  10718. #endif
  10719. #ifdef ENOKEY
  10720. else if (e == ENOKEY) { return MA_ERROR; }
  10721. #endif
  10722. #ifdef EKEYEXPIRED
  10723. else if (e == EKEYEXPIRED) { return MA_ERROR; }
  10724. #endif
  10725. #ifdef EKEYREVOKED
  10726. else if (e == EKEYREVOKED) { return MA_ERROR; }
  10727. #endif
  10728. #ifdef EKEYREJECTED
  10729. else if (e == EKEYREJECTED) { return MA_ERROR; }
  10730. #endif
  10731. #ifdef EOWNERDEAD
  10732. else if (e == EOWNERDEAD) { return MA_ERROR; }
  10733. #endif
  10734. #ifdef ENOTRECOVERABLE
  10735. else if (e == ENOTRECOVERABLE) { return MA_ERROR; }
  10736. #endif
  10737. #ifdef ERFKILL
  10738. else if (e == ERFKILL) { return MA_ERROR; }
  10739. #endif
  10740. #ifdef EHWPOISON
  10741. else if (e == EHWPOISON) { return MA_ERROR; }
  10742. #endif
  10743. else {
  10744. return MA_ERROR;
  10745. }
  10746. }
  10747. MA_API ma_result ma_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  10748. {
  10749. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10750. errno_t err;
  10751. #endif
  10752. if (ppFile != NULL) {
  10753. *ppFile = NULL; /* Safety. */
  10754. }
  10755. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  10756. return MA_INVALID_ARGS;
  10757. }
  10758. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10759. err = fopen_s(ppFile, pFilePath, pOpenMode);
  10760. if (err != 0) {
  10761. return ma_result_from_errno(err);
  10762. }
  10763. #else
  10764. #if defined(_WIN32) || defined(__APPLE__)
  10765. *ppFile = fopen(pFilePath, pOpenMode);
  10766. #else
  10767. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  10768. *ppFile = fopen64(pFilePath, pOpenMode);
  10769. #else
  10770. *ppFile = fopen(pFilePath, pOpenMode);
  10771. #endif
  10772. #endif
  10773. if (*ppFile == NULL) {
  10774. ma_result result = ma_result_from_errno(errno);
  10775. if (result == MA_SUCCESS) {
  10776. result = MA_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
  10777. }
  10778. return result;
  10779. }
  10780. #endif
  10781. return MA_SUCCESS;
  10782. }
  10783. /*
  10784. _wfopen() isn't always available in all compilation environments.
  10785. * Windows only.
  10786. * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
  10787. * MinGW-64 (both 32- and 64-bit) seems to support it.
  10788. * MinGW wraps it in !defined(__STRICT_ANSI__).
  10789. * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
  10790. This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
  10791. fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
  10792. */
  10793. #if defined(_WIN32)
  10794. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  10795. #define MA_HAS_WFOPEN
  10796. #endif
  10797. #endif
  10798. MA_API ma_result ma_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const ma_allocation_callbacks* pAllocationCallbacks)
  10799. {
  10800. if (ppFile != NULL) {
  10801. *ppFile = NULL; /* Safety. */
  10802. }
  10803. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  10804. return MA_INVALID_ARGS;
  10805. }
  10806. #if defined(MA_HAS_WFOPEN)
  10807. {
  10808. /* Use _wfopen() on Windows. */
  10809. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10810. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  10811. if (err != 0) {
  10812. return ma_result_from_errno(err);
  10813. }
  10814. #else
  10815. *ppFile = _wfopen(pFilePath, pOpenMode);
  10816. if (*ppFile == NULL) {
  10817. return ma_result_from_errno(errno);
  10818. }
  10819. #endif
  10820. (void)pAllocationCallbacks;
  10821. }
  10822. #else
  10823. /*
  10824. Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can
  10825. 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
  10826. 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.
  10827. */
  10828. {
  10829. mbstate_t mbs;
  10830. size_t lenMB;
  10831. const wchar_t* pFilePathTemp = pFilePath;
  10832. char* pFilePathMB = NULL;
  10833. char pOpenModeMB[32] = {0};
  10834. /* Get the length first. */
  10835. MA_ZERO_OBJECT(&mbs);
  10836. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  10837. if (lenMB == (size_t)-1) {
  10838. return ma_result_from_errno(errno);
  10839. }
  10840. pFilePathMB = (char*)ma_malloc(lenMB + 1, pAllocationCallbacks);
  10841. if (pFilePathMB == NULL) {
  10842. return MA_OUT_OF_MEMORY;
  10843. }
  10844. pFilePathTemp = pFilePath;
  10845. MA_ZERO_OBJECT(&mbs);
  10846. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  10847. /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
  10848. {
  10849. size_t i = 0;
  10850. for (;;) {
  10851. if (pOpenMode[i] == 0) {
  10852. pOpenModeMB[i] = '\0';
  10853. break;
  10854. }
  10855. pOpenModeMB[i] = (char)pOpenMode[i];
  10856. i += 1;
  10857. }
  10858. }
  10859. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  10860. ma_free(pFilePathMB, pAllocationCallbacks);
  10861. }
  10862. if (*ppFile == NULL) {
  10863. return MA_ERROR;
  10864. }
  10865. #endif
  10866. return MA_SUCCESS;
  10867. }
  10868. static MA_INLINE void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes)
  10869. {
  10870. #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
  10871. MA_COPY_MEMORY(dst, src, (size_t)sizeInBytes);
  10872. #else
  10873. while (sizeInBytes > 0) {
  10874. ma_uint64 bytesToCopyNow = sizeInBytes;
  10875. if (bytesToCopyNow > MA_SIZE_MAX) {
  10876. bytesToCopyNow = MA_SIZE_MAX;
  10877. }
  10878. MA_COPY_MEMORY(dst, src, (size_t)bytesToCopyNow); /* Safe cast to size_t. */
  10879. sizeInBytes -= bytesToCopyNow;
  10880. dst = ( void*)(( ma_uint8*)dst + bytesToCopyNow);
  10881. src = (const void*)((const ma_uint8*)src + bytesToCopyNow);
  10882. }
  10883. #endif
  10884. }
  10885. static MA_INLINE void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes)
  10886. {
  10887. #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
  10888. MA_ZERO_MEMORY(dst, (size_t)sizeInBytes);
  10889. #else
  10890. while (sizeInBytes > 0) {
  10891. ma_uint64 bytesToZeroNow = sizeInBytes;
  10892. if (bytesToZeroNow > MA_SIZE_MAX) {
  10893. bytesToZeroNow = MA_SIZE_MAX;
  10894. }
  10895. MA_ZERO_MEMORY(dst, (size_t)bytesToZeroNow); /* Safe cast to size_t. */
  10896. sizeInBytes -= bytesToZeroNow;
  10897. dst = (void*)((ma_uint8*)dst + bytesToZeroNow);
  10898. }
  10899. #endif
  10900. }
  10901. /* Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */
  10902. static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x)
  10903. {
  10904. x--;
  10905. x |= x >> 1;
  10906. x |= x >> 2;
  10907. x |= x >> 4;
  10908. x |= x >> 8;
  10909. x |= x >> 16;
  10910. x++;
  10911. return x;
  10912. }
  10913. static MA_INLINE unsigned int ma_prev_power_of_2(unsigned int x)
  10914. {
  10915. return ma_next_power_of_2(x) >> 1;
  10916. }
  10917. static MA_INLINE unsigned int ma_round_to_power_of_2(unsigned int x)
  10918. {
  10919. unsigned int prev = ma_prev_power_of_2(x);
  10920. unsigned int next = ma_next_power_of_2(x);
  10921. if ((next - x) > (x - prev)) {
  10922. return prev;
  10923. } else {
  10924. return next;
  10925. }
  10926. }
  10927. static MA_INLINE unsigned int ma_count_set_bits(unsigned int x)
  10928. {
  10929. unsigned int count = 0;
  10930. while (x != 0) {
  10931. if (x & 1) {
  10932. count += 1;
  10933. }
  10934. x = x >> 1;
  10935. }
  10936. return count;
  10937. }
  10938. /**************************************************************************************************************************************************************
  10939. Allocation Callbacks
  10940. **************************************************************************************************************************************************************/
  10941. static void* ma__malloc_default(size_t sz, void* pUserData)
  10942. {
  10943. (void)pUserData;
  10944. return MA_MALLOC(sz);
  10945. }
  10946. static void* ma__realloc_default(void* p, size_t sz, void* pUserData)
  10947. {
  10948. (void)pUserData;
  10949. return MA_REALLOC(p, sz);
  10950. }
  10951. static void ma__free_default(void* p, void* pUserData)
  10952. {
  10953. (void)pUserData;
  10954. MA_FREE(p);
  10955. }
  10956. static ma_allocation_callbacks ma_allocation_callbacks_init_default(void)
  10957. {
  10958. ma_allocation_callbacks callbacks;
  10959. callbacks.pUserData = NULL;
  10960. callbacks.onMalloc = ma__malloc_default;
  10961. callbacks.onRealloc = ma__realloc_default;
  10962. callbacks.onFree = ma__free_default;
  10963. return callbacks;
  10964. }
  10965. static ma_result ma_allocation_callbacks_init_copy(ma_allocation_callbacks* pDst, const ma_allocation_callbacks* pSrc)
  10966. {
  10967. if (pDst == NULL) {
  10968. return MA_INVALID_ARGS;
  10969. }
  10970. if (pSrc == NULL) {
  10971. *pDst = ma_allocation_callbacks_init_default();
  10972. } else {
  10973. if (pSrc->pUserData == NULL && pSrc->onFree == NULL && pSrc->onMalloc == NULL && pSrc->onRealloc == NULL) {
  10974. *pDst = ma_allocation_callbacks_init_default();
  10975. } else {
  10976. if (pSrc->onFree == NULL || (pSrc->onMalloc == NULL && pSrc->onRealloc == NULL)) {
  10977. return MA_INVALID_ARGS; /* Invalid allocation callbacks. */
  10978. } else {
  10979. *pDst = *pSrc;
  10980. }
  10981. }
  10982. }
  10983. return MA_SUCCESS;
  10984. }
  10985. /**************************************************************************************************************************************************************
  10986. Logging
  10987. **************************************************************************************************************************************************************/
  10988. MA_API const char* ma_log_level_to_string(ma_uint32 logLevel)
  10989. {
  10990. switch (logLevel)
  10991. {
  10992. case MA_LOG_LEVEL_DEBUG: return "DEBUG";
  10993. case MA_LOG_LEVEL_INFO: return "INFO";
  10994. case MA_LOG_LEVEL_WARNING: return "WARNING";
  10995. case MA_LOG_LEVEL_ERROR: return "ERROR";
  10996. default: return "ERROR";
  10997. }
  10998. }
  10999. #if defined(MA_DEBUG_OUTPUT)
  11000. #if defined(MA_ANDROID)
  11001. #include <android/log.h>
  11002. #endif
  11003. /* Customize this to use a specific tag in __android_log_print() for debug output messages. */
  11004. #ifndef MA_ANDROID_LOG_TAG
  11005. #define MA_ANDROID_LOG_TAG "miniaudio"
  11006. #endif
  11007. void ma_log_callback_debug(void* pUserData, ma_uint32 level, const char* pMessage)
  11008. {
  11009. (void)pUserData;
  11010. /* Special handling for some platforms. */
  11011. #if defined(MA_ANDROID)
  11012. {
  11013. /* Android. */
  11014. __android_log_print(ANDROID_LOG_DEBUG, MA_ANDROID_LOG_TAG, "%s: %s", ma_log_level_to_string(level), pMessage);
  11015. }
  11016. #else
  11017. {
  11018. /* Everything else. */
  11019. printf("%s: %s", ma_log_level_to_string(level), pMessage);
  11020. }
  11021. #endif
  11022. }
  11023. #endif
  11024. MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData)
  11025. {
  11026. ma_log_callback callback;
  11027. MA_ZERO_OBJECT(&callback);
  11028. callback.onLog = onLog;
  11029. callback.pUserData = pUserData;
  11030. return callback;
  11031. }
  11032. MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog)
  11033. {
  11034. if (pLog == NULL) {
  11035. return MA_INVALID_ARGS;
  11036. }
  11037. MA_ZERO_OBJECT(pLog);
  11038. ma_allocation_callbacks_init_copy(&pLog->allocationCallbacks, pAllocationCallbacks);
  11039. /* We need a mutex for thread safety. */
  11040. #ifndef MA_NO_THREADING
  11041. {
  11042. ma_result result = ma_mutex_init(&pLog->lock);
  11043. if (result != MA_SUCCESS) {
  11044. return result;
  11045. }
  11046. }
  11047. #endif
  11048. /* If we're using debug output, enable it. */
  11049. #if defined(MA_DEBUG_OUTPUT)
  11050. {
  11051. ma_log_register_callback(pLog, ma_log_callback_init(ma_log_callback_debug, NULL)); /* Doesn't really matter if this fails. */
  11052. }
  11053. #endif
  11054. return MA_SUCCESS;
  11055. }
  11056. MA_API void ma_log_uninit(ma_log* pLog)
  11057. {
  11058. if (pLog == NULL) {
  11059. return;
  11060. }
  11061. #ifndef MA_NO_THREADING
  11062. ma_mutex_uninit(&pLog->lock);
  11063. #endif
  11064. }
  11065. static void ma_log_lock(ma_log* pLog)
  11066. {
  11067. #ifndef MA_NO_THREADING
  11068. ma_mutex_lock(&pLog->lock);
  11069. #else
  11070. (void)pLog;
  11071. #endif
  11072. }
  11073. static void ma_log_unlock(ma_log* pLog)
  11074. {
  11075. #ifndef MA_NO_THREADING
  11076. ma_mutex_unlock(&pLog->lock);
  11077. #else
  11078. (void)pLog;
  11079. #endif
  11080. }
  11081. MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback)
  11082. {
  11083. ma_result result = MA_SUCCESS;
  11084. if (pLog == NULL || callback.onLog == NULL) {
  11085. return MA_INVALID_ARGS;
  11086. }
  11087. ma_log_lock(pLog);
  11088. {
  11089. if (pLog->callbackCount == ma_countof(pLog->callbacks)) {
  11090. result = MA_OUT_OF_MEMORY; /* Reached the maximum allowed log callbacks. */
  11091. } else {
  11092. pLog->callbacks[pLog->callbackCount] = callback;
  11093. pLog->callbackCount += 1;
  11094. }
  11095. }
  11096. ma_log_unlock(pLog);
  11097. return result;
  11098. }
  11099. MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback)
  11100. {
  11101. if (pLog == NULL) {
  11102. return MA_INVALID_ARGS;
  11103. }
  11104. ma_log_lock(pLog);
  11105. {
  11106. ma_uint32 iLog;
  11107. for (iLog = 0; iLog < pLog->callbackCount; ) {
  11108. if (pLog->callbacks[iLog].onLog == callback.onLog) {
  11109. /* Found. Move everything down a slot. */
  11110. ma_uint32 jLog;
  11111. for (jLog = iLog; jLog < pLog->callbackCount-1; jLog += 1) {
  11112. pLog->callbacks[jLog] = pLog->callbacks[jLog + 1];
  11113. }
  11114. pLog->callbackCount -= 1;
  11115. } else {
  11116. /* Not found. */
  11117. iLog += 1;
  11118. }
  11119. }
  11120. }
  11121. ma_log_unlock(pLog);
  11122. return MA_SUCCESS;
  11123. }
  11124. MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage)
  11125. {
  11126. if (pLog == NULL || pMessage == NULL) {
  11127. return MA_INVALID_ARGS;
  11128. }
  11129. ma_log_lock(pLog);
  11130. {
  11131. ma_uint32 iLog;
  11132. for (iLog = 0; iLog < pLog->callbackCount; iLog += 1) {
  11133. if (pLog->callbacks[iLog].onLog) {
  11134. pLog->callbacks[iLog].onLog(pLog->callbacks[iLog].pUserData, level, pMessage);
  11135. }
  11136. }
  11137. }
  11138. ma_log_unlock(pLog);
  11139. return MA_SUCCESS;
  11140. }
  11141. /*
  11142. 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
  11143. logging function, I'm happy to keep this simple. In the VC6 build we can implement this in terms of _vsnprintf().
  11144. */
  11145. #if defined(_MSC_VER) && _MSC_VER < 1900
  11146. static int ma_vscprintf(const ma_allocation_callbacks* pAllocationCallbacks, const char* format, va_list args)
  11147. {
  11148. #if _MSC_VER > 1200
  11149. return _vscprintf(format, args);
  11150. #else
  11151. int result;
  11152. char* pTempBuffer = NULL;
  11153. size_t tempBufferCap = 1024;
  11154. if (format == NULL) {
  11155. errno = EINVAL;
  11156. return -1;
  11157. }
  11158. for (;;) {
  11159. char* pNewTempBuffer = (char*)ma_realloc(pTempBuffer, tempBufferCap, pAllocationCallbacks);
  11160. if (pNewTempBuffer == NULL) {
  11161. ma_free(pTempBuffer, pAllocationCallbacks);
  11162. errno = ENOMEM;
  11163. return -1; /* Out of memory. */
  11164. }
  11165. pTempBuffer = pNewTempBuffer;
  11166. result = _vsnprintf(pTempBuffer, tempBufferCap, format, args);
  11167. ma_free(pTempBuffer, NULL);
  11168. if (result != -1) {
  11169. break; /* Got it. */
  11170. }
  11171. /* 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. */
  11172. tempBufferCap *= 2;
  11173. }
  11174. return result;
  11175. #endif
  11176. }
  11177. #endif
  11178. MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args)
  11179. {
  11180. if (pLog == NULL || pFormat == NULL) {
  11181. return MA_INVALID_ARGS;
  11182. }
  11183. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || ((!defined(_MSC_VER) || _MSC_VER >= 1900) && !defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS)) || (defined(__cplusplus) && __cplusplus >= 201103L)
  11184. {
  11185. ma_result result;
  11186. int length;
  11187. char pFormattedMessageStack[1024];
  11188. char* pFormattedMessageHeap = NULL;
  11189. /* First try formatting into our fixed sized stack allocated buffer. If this is too small we'll fallback to a heap allocation. */
  11190. length = vsnprintf(pFormattedMessageStack, sizeof(pFormattedMessageStack), pFormat, args);
  11191. if (length < 0) {
  11192. return MA_INVALID_OPERATION; /* An error occurred when trying to convert the buffer. */
  11193. }
  11194. if ((size_t)length < sizeof(pFormattedMessageStack)) {
  11195. /* The string was written to the stack. */
  11196. result = ma_log_post(pLog, level, pFormattedMessageStack);
  11197. } else {
  11198. /* The stack buffer was too small, try the heap. */
  11199. pFormattedMessageHeap = (char*)ma_malloc(length + 1, &pLog->allocationCallbacks);
  11200. if (pFormattedMessageHeap == NULL) {
  11201. return MA_OUT_OF_MEMORY;
  11202. }
  11203. length = vsnprintf(pFormattedMessageHeap, length + 1, pFormat, args);
  11204. if (length < 0) {
  11205. ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks);
  11206. return MA_INVALID_OPERATION;
  11207. }
  11208. result = ma_log_post(pLog, level, pFormattedMessageHeap);
  11209. ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks);
  11210. }
  11211. return result;
  11212. }
  11213. #else
  11214. {
  11215. /*
  11216. 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
  11217. 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
  11218. a fixed sized stack allocated buffer.
  11219. */
  11220. #if defined(_MSC_VER) && _MSC_VER >= 1200 /* 1200 = VC6 */
  11221. {
  11222. ma_result result;
  11223. int formattedLen;
  11224. char* pFormattedMessage = NULL;
  11225. va_list args2;
  11226. #if _MSC_VER >= 1800
  11227. {
  11228. va_copy(args2, args);
  11229. }
  11230. #else
  11231. {
  11232. args2 = args;
  11233. }
  11234. #endif
  11235. formattedLen = ma_vscprintf(&pLog->allocationCallbacks, pFormat, args2);
  11236. va_end(args2);
  11237. if (formattedLen <= 0) {
  11238. return MA_INVALID_OPERATION;
  11239. }
  11240. pFormattedMessage = (char*)ma_malloc(formattedLen + 1, &pLog->allocationCallbacks);
  11241. if (pFormattedMessage == NULL) {
  11242. return MA_OUT_OF_MEMORY;
  11243. }
  11244. /* We'll get errors on newer versions of Visual Studio if we try to use vsprintf(). */
  11245. #if _MSC_VER >= 1400 /* 1400 = Visual Studio 2005 */
  11246. {
  11247. vsprintf_s(pFormattedMessage, formattedLen + 1, pFormat, args);
  11248. }
  11249. #else
  11250. {
  11251. vsprintf(pFormattedMessage, pFormat, args);
  11252. }
  11253. #endif
  11254. result = ma_log_post(pLog, level, pFormattedMessage);
  11255. ma_free(pFormattedMessage, &pLog->allocationCallbacks);
  11256. return result;
  11257. }
  11258. #else
  11259. {
  11260. /* Can't do anything because we don't have a safe way of to emulate vsnprintf() without a manual solution. */
  11261. (void)level;
  11262. (void)args;
  11263. return MA_INVALID_OPERATION;
  11264. }
  11265. #endif
  11266. }
  11267. #endif
  11268. }
  11269. MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...)
  11270. {
  11271. ma_result result;
  11272. va_list args;
  11273. if (pLog == NULL || pFormat == NULL) {
  11274. return MA_INVALID_ARGS;
  11275. }
  11276. va_start(args, pFormat);
  11277. {
  11278. result = ma_log_postv(pLog, level, pFormat, args);
  11279. }
  11280. va_end(args);
  11281. return result;
  11282. }
  11283. static MA_INLINE ma_uint8 ma_clip_u8(ma_int32 x)
  11284. {
  11285. return (ma_uint8)(ma_clamp(x, -128, 127) + 128);
  11286. }
  11287. static MA_INLINE ma_int16 ma_clip_s16(ma_int32 x)
  11288. {
  11289. return (ma_int16)ma_clamp(x, -32768, 32767);
  11290. }
  11291. static MA_INLINE ma_int64 ma_clip_s24(ma_int64 x)
  11292. {
  11293. return (ma_int64)ma_clamp(x, -8388608, 8388607);
  11294. }
  11295. static MA_INLINE ma_int32 ma_clip_s32(ma_int64 x)
  11296. {
  11297. /* This dance is to silence warnings with -std=c89. A good compiler should be able to optimize this away. */
  11298. ma_int64 clipMin;
  11299. ma_int64 clipMax;
  11300. clipMin = -((ma_int64)2147483647 + 1);
  11301. clipMax = (ma_int64)2147483647;
  11302. return (ma_int32)ma_clamp(x, clipMin, clipMax);
  11303. }
  11304. static MA_INLINE float ma_clip_f32(float x)
  11305. {
  11306. if (x < -1) return -1;
  11307. if (x > +1) return +1;
  11308. return x;
  11309. }
  11310. static MA_INLINE float ma_mix_f32(float x, float y, float a)
  11311. {
  11312. return x*(1-a) + y*a;
  11313. }
  11314. static MA_INLINE float ma_mix_f32_fast(float x, float y, float a)
  11315. {
  11316. float r0 = (y - x);
  11317. float r1 = r0*a;
  11318. return x + r1;
  11319. /*return x + (y - x)*a;*/
  11320. }
  11321. #if defined(MA_SUPPORT_SSE2)
  11322. static MA_INLINE __m128 ma_mix_f32_fast__sse2(__m128 x, __m128 y, __m128 a)
  11323. {
  11324. return _mm_add_ps(x, _mm_mul_ps(_mm_sub_ps(y, x), a));
  11325. }
  11326. #endif
  11327. #if defined(MA_SUPPORT_AVX2)
  11328. static MA_INLINE __m256 ma_mix_f32_fast__avx2(__m256 x, __m256 y, __m256 a)
  11329. {
  11330. return _mm256_add_ps(x, _mm256_mul_ps(_mm256_sub_ps(y, x), a));
  11331. }
  11332. #endif
  11333. #if defined(MA_SUPPORT_NEON)
  11334. static MA_INLINE float32x4_t ma_mix_f32_fast__neon(float32x4_t x, float32x4_t y, float32x4_t a)
  11335. {
  11336. return vaddq_f32(x, vmulq_f32(vsubq_f32(y, x), a));
  11337. }
  11338. #endif
  11339. static MA_INLINE double ma_mix_f64(double x, double y, double a)
  11340. {
  11341. return x*(1-a) + y*a;
  11342. }
  11343. static MA_INLINE double ma_mix_f64_fast(double x, double y, double a)
  11344. {
  11345. return x + (y - x)*a;
  11346. }
  11347. static MA_INLINE float ma_scale_to_range_f32(float x, float lo, float hi)
  11348. {
  11349. return lo + x*(hi-lo);
  11350. }
  11351. /*
  11352. Greatest common factor using Euclid's algorithm iteratively.
  11353. */
  11354. static MA_INLINE ma_uint32 ma_gcf_u32(ma_uint32 a, ma_uint32 b)
  11355. {
  11356. for (;;) {
  11357. if (b == 0) {
  11358. break;
  11359. } else {
  11360. ma_uint32 t = a;
  11361. a = b;
  11362. b = t % a;
  11363. }
  11364. }
  11365. return a;
  11366. }
  11367. static ma_uint32 ma_ffs_32(ma_uint32 x)
  11368. {
  11369. ma_uint32 i;
  11370. /* Just a naive implementation just to get things working for now. Will optimize this later. */
  11371. for (i = 0; i < 32; i += 1) {
  11372. if ((x & (1 << i)) != 0) {
  11373. return i;
  11374. }
  11375. }
  11376. return i;
  11377. }
  11378. static MA_INLINE ma_int16 ma_float_to_fixed_16(float x)
  11379. {
  11380. return (ma_int16)(x * (1 << 8));
  11381. }
  11382. /*
  11383. Random Number Generation
  11384. miniaudio uses the LCG random number generation algorithm. This is good enough for audio.
  11385. Note that miniaudio's global LCG implementation uses global state which is _not_ thread-local. When this is called across
  11386. multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough for
  11387. miniaudio's purposes.
  11388. */
  11389. #ifndef MA_DEFAULT_LCG_SEED
  11390. #define MA_DEFAULT_LCG_SEED 4321
  11391. #endif
  11392. #define MA_LCG_M 2147483647
  11393. #define MA_LCG_A 48271
  11394. #define MA_LCG_C 0
  11395. static ma_lcg g_maLCG = {MA_DEFAULT_LCG_SEED}; /* Non-zero initial seed. Use ma_seed() to use an explicit seed. */
  11396. static MA_INLINE void ma_lcg_seed(ma_lcg* pLCG, ma_int32 seed)
  11397. {
  11398. MA_ASSERT(pLCG != NULL);
  11399. pLCG->state = seed;
  11400. }
  11401. static MA_INLINE ma_int32 ma_lcg_rand_s32(ma_lcg* pLCG)
  11402. {
  11403. pLCG->state = (MA_LCG_A * pLCG->state + MA_LCG_C) % MA_LCG_M;
  11404. return pLCG->state;
  11405. }
  11406. static MA_INLINE ma_uint32 ma_lcg_rand_u32(ma_lcg* pLCG)
  11407. {
  11408. return (ma_uint32)ma_lcg_rand_s32(pLCG);
  11409. }
  11410. static MA_INLINE ma_int16 ma_lcg_rand_s16(ma_lcg* pLCG)
  11411. {
  11412. return (ma_int16)(ma_lcg_rand_s32(pLCG) & 0xFFFF);
  11413. }
  11414. static MA_INLINE double ma_lcg_rand_f64(ma_lcg* pLCG)
  11415. {
  11416. return ma_lcg_rand_s32(pLCG) / (double)0x7FFFFFFF;
  11417. }
  11418. static MA_INLINE float ma_lcg_rand_f32(ma_lcg* pLCG)
  11419. {
  11420. return (float)ma_lcg_rand_f64(pLCG);
  11421. }
  11422. static MA_INLINE float ma_lcg_rand_range_f32(ma_lcg* pLCG, float lo, float hi)
  11423. {
  11424. return ma_scale_to_range_f32(ma_lcg_rand_f32(pLCG), lo, hi);
  11425. }
  11426. static MA_INLINE ma_int32 ma_lcg_rand_range_s32(ma_lcg* pLCG, ma_int32 lo, ma_int32 hi)
  11427. {
  11428. if (lo == hi) {
  11429. return lo;
  11430. }
  11431. return lo + ma_lcg_rand_u32(pLCG) / (0xFFFFFFFF / (hi - lo + 1) + 1);
  11432. }
  11433. static MA_INLINE void ma_seed(ma_int32 seed)
  11434. {
  11435. ma_lcg_seed(&g_maLCG, seed);
  11436. }
  11437. static MA_INLINE ma_int32 ma_rand_s32(void)
  11438. {
  11439. return ma_lcg_rand_s32(&g_maLCG);
  11440. }
  11441. static MA_INLINE ma_uint32 ma_rand_u32(void)
  11442. {
  11443. return ma_lcg_rand_u32(&g_maLCG);
  11444. }
  11445. static MA_INLINE double ma_rand_f64(void)
  11446. {
  11447. return ma_lcg_rand_f64(&g_maLCG);
  11448. }
  11449. static MA_INLINE float ma_rand_f32(void)
  11450. {
  11451. return ma_lcg_rand_f32(&g_maLCG);
  11452. }
  11453. static MA_INLINE float ma_rand_range_f32(float lo, float hi)
  11454. {
  11455. return ma_lcg_rand_range_f32(&g_maLCG, lo, hi);
  11456. }
  11457. static MA_INLINE ma_int32 ma_rand_range_s32(ma_int32 lo, ma_int32 hi)
  11458. {
  11459. return ma_lcg_rand_range_s32(&g_maLCG, lo, hi);
  11460. }
  11461. static MA_INLINE float ma_dither_f32_rectangle(float ditherMin, float ditherMax)
  11462. {
  11463. return ma_rand_range_f32(ditherMin, ditherMax);
  11464. }
  11465. static MA_INLINE float ma_dither_f32_triangle(float ditherMin, float ditherMax)
  11466. {
  11467. float a = ma_rand_range_f32(ditherMin, 0);
  11468. float b = ma_rand_range_f32(0, ditherMax);
  11469. return a + b;
  11470. }
  11471. static MA_INLINE float ma_dither_f32(ma_dither_mode ditherMode, float ditherMin, float ditherMax)
  11472. {
  11473. if (ditherMode == ma_dither_mode_rectangle) {
  11474. return ma_dither_f32_rectangle(ditherMin, ditherMax);
  11475. }
  11476. if (ditherMode == ma_dither_mode_triangle) {
  11477. return ma_dither_f32_triangle(ditherMin, ditherMax);
  11478. }
  11479. return 0;
  11480. }
  11481. static MA_INLINE ma_int32 ma_dither_s32(ma_dither_mode ditherMode, ma_int32 ditherMin, ma_int32 ditherMax)
  11482. {
  11483. if (ditherMode == ma_dither_mode_rectangle) {
  11484. ma_int32 a = ma_rand_range_s32(ditherMin, ditherMax);
  11485. return a;
  11486. }
  11487. if (ditherMode == ma_dither_mode_triangle) {
  11488. ma_int32 a = ma_rand_range_s32(ditherMin, 0);
  11489. ma_int32 b = ma_rand_range_s32(0, ditherMax);
  11490. return a + b;
  11491. }
  11492. return 0;
  11493. }
  11494. /**************************************************************************************************************************************************************
  11495. Atomics
  11496. **************************************************************************************************************************************************************/
  11497. /* ma_atomic.h begin */
  11498. #ifndef ma_atomic_h
  11499. #if defined(__cplusplus)
  11500. extern "C" {
  11501. #endif
  11502. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  11503. #pragma GCC diagnostic push
  11504. #pragma GCC diagnostic ignored "-Wlong-long"
  11505. #if defined(__clang__)
  11506. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  11507. #endif
  11508. #endif
  11509. typedef int ma_atomic_memory_order;
  11510. #define MA_ATOMIC_HAS_8
  11511. #define MA_ATOMIC_HAS_16
  11512. #define MA_ATOMIC_HAS_32
  11513. #define MA_ATOMIC_HAS_64
  11514. #if (defined(_MSC_VER) ) || defined(__WATCOMC__) || defined(__DMC__)
  11515. #define MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, intrin, ma_atomicType, msvcType) \
  11516. ma_atomicType result; \
  11517. switch (order) \
  11518. { \
  11519. case ma_atomic_memory_order_relaxed: \
  11520. { \
  11521. result = (ma_atomicType)intrin##_nf((volatile msvcType*)dst, (msvcType)src); \
  11522. } break; \
  11523. case ma_atomic_memory_order_consume: \
  11524. case ma_atomic_memory_order_acquire: \
  11525. { \
  11526. result = (ma_atomicType)intrin##_acq((volatile msvcType*)dst, (msvcType)src); \
  11527. } break; \
  11528. case ma_atomic_memory_order_release: \
  11529. { \
  11530. result = (ma_atomicType)intrin##_rel((volatile msvcType*)dst, (msvcType)src); \
  11531. } break; \
  11532. case ma_atomic_memory_order_acq_rel: \
  11533. case ma_atomic_memory_order_seq_cst: \
  11534. default: \
  11535. { \
  11536. result = (ma_atomicType)intrin((volatile msvcType*)dst, (msvcType)src); \
  11537. } break; \
  11538. } \
  11539. return result;
  11540. #define MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, expected, desired, order, intrin, ma_atomicType, msvcType) \
  11541. ma_atomicType result; \
  11542. switch (order) \
  11543. { \
  11544. case ma_atomic_memory_order_relaxed: \
  11545. { \
  11546. result = (ma_atomicType)intrin##_nf((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11547. } break; \
  11548. case ma_atomic_memory_order_consume: \
  11549. case ma_atomic_memory_order_acquire: \
  11550. { \
  11551. result = (ma_atomicType)intrin##_acq((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11552. } break; \
  11553. case ma_atomic_memory_order_release: \
  11554. { \
  11555. result = (ma_atomicType)intrin##_rel((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11556. } break; \
  11557. case ma_atomic_memory_order_acq_rel: \
  11558. case ma_atomic_memory_order_seq_cst: \
  11559. default: \
  11560. { \
  11561. result = (ma_atomicType)intrin((volatile msvcType*)ptr, (msvcType)expected, (msvcType)desired); \
  11562. } break; \
  11563. } \
  11564. return result;
  11565. #define ma_atomic_memory_order_relaxed 0
  11566. #define ma_atomic_memory_order_consume 1
  11567. #define ma_atomic_memory_order_acquire 2
  11568. #define ma_atomic_memory_order_release 3
  11569. #define ma_atomic_memory_order_acq_rel 4
  11570. #define ma_atomic_memory_order_seq_cst 5
  11571. #if _MSC_VER < 1600 && defined(MA_X86)
  11572. #define MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY
  11573. #endif
  11574. #if _MSC_VER < 1600
  11575. #undef MA_ATOMIC_HAS_8
  11576. #undef MA_ATOMIC_HAS_16
  11577. #endif
  11578. #if !defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11579. #include <intrin.h>
  11580. #endif
  11581. #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11582. #if defined(MA_ATOMIC_HAS_8)
  11583. static MA_INLINE ma_uint8 __stdcall ma_atomic_compare_and_swap_8(volatile ma_uint8* dst, ma_uint8 expected, ma_uint8 desired)
  11584. {
  11585. ma_uint8 result = 0;
  11586. __asm {
  11587. mov ecx, dst
  11588. mov al, expected
  11589. mov dl, desired
  11590. lock cmpxchg [ecx], dl
  11591. mov result, al
  11592. }
  11593. return result;
  11594. }
  11595. #endif
  11596. #if defined(MA_ATOMIC_HAS_16)
  11597. static MA_INLINE ma_uint16 __stdcall ma_atomic_compare_and_swap_16(volatile ma_uint16* dst, ma_uint16 expected, ma_uint16 desired)
  11598. {
  11599. ma_uint16 result = 0;
  11600. __asm {
  11601. mov ecx, dst
  11602. mov ax, expected
  11603. mov dx, desired
  11604. lock cmpxchg [ecx], dx
  11605. mov result, ax
  11606. }
  11607. return result;
  11608. }
  11609. #endif
  11610. #if defined(MA_ATOMIC_HAS_32)
  11611. static MA_INLINE ma_uint32 __stdcall ma_atomic_compare_and_swap_32(volatile ma_uint32* dst, ma_uint32 expected, ma_uint32 desired)
  11612. {
  11613. ma_uint32 result = 0;
  11614. __asm {
  11615. mov ecx, dst
  11616. mov eax, expected
  11617. mov edx, desired
  11618. lock cmpxchg [ecx], edx
  11619. mov result, eax
  11620. }
  11621. return result;
  11622. }
  11623. #endif
  11624. #if defined(MA_ATOMIC_HAS_64)
  11625. static MA_INLINE ma_uint64 __stdcall ma_atomic_compare_and_swap_64(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired)
  11626. {
  11627. ma_uint32 resultEAX = 0;
  11628. ma_uint32 resultEDX = 0;
  11629. __asm {
  11630. mov esi, dst
  11631. mov eax, dword ptr expected
  11632. mov edx, dword ptr expected + 4
  11633. mov ebx, dword ptr desired
  11634. mov ecx, dword ptr desired + 4
  11635. lock cmpxchg8b qword ptr [esi]
  11636. mov resultEAX, eax
  11637. mov resultEDX, edx
  11638. }
  11639. return ((ma_uint64)resultEDX << 32) | resultEAX;
  11640. }
  11641. #endif
  11642. #else
  11643. #if defined(MA_ATOMIC_HAS_8)
  11644. #define ma_atomic_compare_and_swap_8( dst, expected, desired) (ma_uint8 )_InterlockedCompareExchange8((volatile char*)dst, (char)desired, (char)expected)
  11645. #endif
  11646. #if defined(MA_ATOMIC_HAS_16)
  11647. #define ma_atomic_compare_and_swap_16(dst, expected, desired) (ma_uint16)_InterlockedCompareExchange16((volatile short*)dst, (short)desired, (short)expected)
  11648. #endif
  11649. #if defined(MA_ATOMIC_HAS_32)
  11650. #define ma_atomic_compare_and_swap_32(dst, expected, desired) (ma_uint32)_InterlockedCompareExchange((volatile long*)dst, (long)desired, (long)expected)
  11651. #endif
  11652. #if defined(MA_ATOMIC_HAS_64)
  11653. #define ma_atomic_compare_and_swap_64(dst, expected, desired) (ma_uint64)_InterlockedCompareExchange64((volatile ma_int64*)dst, (ma_int64)desired, (ma_int64)expected)
  11654. #endif
  11655. #endif
  11656. #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11657. #if defined(MA_ATOMIC_HAS_8)
  11658. static MA_INLINE ma_uint8 __stdcall ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  11659. {
  11660. ma_uint8 result = 0;
  11661. (void)order;
  11662. __asm {
  11663. mov ecx, dst
  11664. mov al, src
  11665. lock xchg [ecx], al
  11666. mov result, al
  11667. }
  11668. return result;
  11669. }
  11670. #endif
  11671. #if defined(MA_ATOMIC_HAS_16)
  11672. static MA_INLINE ma_uint16 __stdcall ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  11673. {
  11674. ma_uint16 result = 0;
  11675. (void)order;
  11676. __asm {
  11677. mov ecx, dst
  11678. mov ax, src
  11679. lock xchg [ecx], ax
  11680. mov result, ax
  11681. }
  11682. return result;
  11683. }
  11684. #endif
  11685. #if defined(MA_ATOMIC_HAS_32)
  11686. static MA_INLINE ma_uint32 __stdcall ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  11687. {
  11688. ma_uint32 result = 0;
  11689. (void)order;
  11690. __asm {
  11691. mov ecx, dst
  11692. mov eax, src
  11693. lock xchg [ecx], eax
  11694. mov result, eax
  11695. }
  11696. return result;
  11697. }
  11698. #endif
  11699. #else
  11700. #if defined(MA_ATOMIC_HAS_8)
  11701. static MA_INLINE ma_uint8 __stdcall ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  11702. {
  11703. #if defined(MA_ARM)
  11704. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange8, ma_uint8, char);
  11705. #else
  11706. (void)order;
  11707. return (ma_uint8)_InterlockedExchange8((volatile char*)dst, (char)src);
  11708. #endif
  11709. }
  11710. #endif
  11711. #if defined(MA_ATOMIC_HAS_16)
  11712. static MA_INLINE ma_uint16 __stdcall ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  11713. {
  11714. #if defined(MA_ARM)
  11715. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange16, ma_uint16, short);
  11716. #else
  11717. (void)order;
  11718. return (ma_uint16)_InterlockedExchange16((volatile short*)dst, (short)src);
  11719. #endif
  11720. }
  11721. #endif
  11722. #if defined(MA_ATOMIC_HAS_32)
  11723. static MA_INLINE ma_uint32 __stdcall ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  11724. {
  11725. #if defined(MA_ARM)
  11726. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange, ma_uint32, long);
  11727. #else
  11728. (void)order;
  11729. return (ma_uint32)_InterlockedExchange((volatile long*)dst, (long)src);
  11730. #endif
  11731. }
  11732. #endif
  11733. #if defined(MA_ATOMIC_HAS_64) && defined(MA_64BIT)
  11734. static MA_INLINE ma_uint64 __stdcall ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  11735. {
  11736. #if defined(MA_ARM)
  11737. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchange64, ma_uint64, long long);
  11738. #else
  11739. (void)order;
  11740. return (ma_uint64)_InterlockedExchange64((volatile long long*)dst, (long long)src);
  11741. #endif
  11742. }
  11743. #else
  11744. #endif
  11745. #endif
  11746. #if defined(MA_ATOMIC_HAS_64) && !defined(MA_64BIT)
  11747. static MA_INLINE ma_uint64 __stdcall ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  11748. {
  11749. ma_uint64 oldValue;
  11750. do {
  11751. oldValue = *dst;
  11752. } while (ma_atomic_compare_and_swap_64(dst, oldValue, src) != oldValue);
  11753. (void)order;
  11754. return oldValue;
  11755. }
  11756. #endif
  11757. #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11758. #if defined(MA_ATOMIC_HAS_8)
  11759. static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  11760. {
  11761. ma_uint8 result = 0;
  11762. (void)order;
  11763. __asm {
  11764. mov ecx, dst
  11765. mov al, src
  11766. lock xadd [ecx], al
  11767. mov result, al
  11768. }
  11769. return result;
  11770. }
  11771. #endif
  11772. #if defined(MA_ATOMIC_HAS_16)
  11773. static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  11774. {
  11775. ma_uint16 result = 0;
  11776. (void)order;
  11777. __asm {
  11778. mov ecx, dst
  11779. mov ax, src
  11780. lock xadd [ecx], ax
  11781. mov result, ax
  11782. }
  11783. return result;
  11784. }
  11785. #endif
  11786. #if defined(MA_ATOMIC_HAS_32)
  11787. static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  11788. {
  11789. ma_uint32 result = 0;
  11790. (void)order;
  11791. __asm {
  11792. mov ecx, dst
  11793. mov eax, src
  11794. lock xadd [ecx], eax
  11795. mov result, eax
  11796. }
  11797. return result;
  11798. }
  11799. #endif
  11800. #else
  11801. #if defined(MA_ATOMIC_HAS_8)
  11802. static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  11803. {
  11804. #if defined(MA_ARM)
  11805. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd8, ma_uint8, char);
  11806. #else
  11807. (void)order;
  11808. return (ma_uint8)_InterlockedExchangeAdd8((volatile char*)dst, (char)src);
  11809. #endif
  11810. }
  11811. #endif
  11812. #if defined(MA_ATOMIC_HAS_16)
  11813. static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  11814. {
  11815. #if defined(MA_ARM)
  11816. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd16, ma_uint16, short);
  11817. #else
  11818. (void)order;
  11819. return (ma_uint16)_InterlockedExchangeAdd16((volatile short*)dst, (short)src);
  11820. #endif
  11821. }
  11822. #endif
  11823. #if defined(MA_ATOMIC_HAS_32)
  11824. static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  11825. {
  11826. #if defined(MA_ARM)
  11827. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd, ma_uint32, long);
  11828. #else
  11829. (void)order;
  11830. return (ma_uint32)_InterlockedExchangeAdd((volatile long*)dst, (long)src);
  11831. #endif
  11832. }
  11833. #endif
  11834. #if defined(MA_ATOMIC_HAS_64) && defined(MA_64BIT)
  11835. static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  11836. {
  11837. #if defined(MA_ARM)
  11838. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedExchangeAdd64, ma_uint64, long long);
  11839. #else
  11840. (void)order;
  11841. return (ma_uint64)_InterlockedExchangeAdd64((volatile long long*)dst, (long long)src);
  11842. #endif
  11843. }
  11844. #else
  11845. #endif
  11846. #endif
  11847. #if defined(MA_ATOMIC_HAS_64) && !defined(MA_64BIT)
  11848. static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  11849. {
  11850. ma_uint64 oldValue;
  11851. ma_uint64 newValue;
  11852. do {
  11853. oldValue = *dst;
  11854. newValue = oldValue + src;
  11855. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11856. (void)order;
  11857. return oldValue;
  11858. }
  11859. #endif
  11860. #if defined(MA_ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11861. static MA_INLINE void __stdcall ma_atomic_thread_fence(ma_atomic_memory_order order)
  11862. {
  11863. (void)order;
  11864. __asm {
  11865. lock add [esp], 0
  11866. }
  11867. }
  11868. #else
  11869. #if defined(MA_X64)
  11870. #define ma_atomic_thread_fence(order) __faststorefence(), (void)order
  11871. #elif defined(MA_ARM64)
  11872. #define ma_atomic_thread_fence(order) __dmb(_ARM64_BARRIER_ISH), (void)order
  11873. #else
  11874. static MA_INLINE void ma_atomic_thread_fence(ma_atomic_memory_order order)
  11875. {
  11876. volatile ma_uint32 barrier = 0;
  11877. ma_atomic_fetch_add_explicit_32(&barrier, 0, order);
  11878. }
  11879. #endif
  11880. #endif
  11881. #define ma_atomic_compiler_fence() ma_atomic_thread_fence(ma_atomic_memory_order_seq_cst)
  11882. #define ma_atomic_signal_fence(order) ma_atomic_thread_fence(order)
  11883. #if defined(MA_ATOMIC_HAS_8)
  11884. static MA_INLINE ma_uint8 ma_atomic_load_explicit_8(volatile const ma_uint8* ptr, ma_atomic_memory_order order)
  11885. {
  11886. #if defined(MA_ARM)
  11887. MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange8, ma_uint8, char);
  11888. #else
  11889. (void)order;
  11890. return ma_atomic_compare_and_swap_8((volatile ma_uint8*)ptr, 0, 0);
  11891. #endif
  11892. }
  11893. #endif
  11894. #if defined(MA_ATOMIC_HAS_16)
  11895. static MA_INLINE ma_uint16 ma_atomic_load_explicit_16(volatile const ma_uint16* ptr, ma_atomic_memory_order order)
  11896. {
  11897. #if defined(MA_ARM)
  11898. MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange16, ma_uint16, short);
  11899. #else
  11900. (void)order;
  11901. return ma_atomic_compare_and_swap_16((volatile ma_uint16*)ptr, 0, 0);
  11902. #endif
  11903. }
  11904. #endif
  11905. #if defined(MA_ATOMIC_HAS_32)
  11906. static MA_INLINE ma_uint32 ma_atomic_load_explicit_32(volatile const ma_uint32* ptr, ma_atomic_memory_order order)
  11907. {
  11908. #if defined(MA_ARM)
  11909. MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange, ma_uint32, long);
  11910. #else
  11911. (void)order;
  11912. return ma_atomic_compare_and_swap_32((volatile ma_uint32*)ptr, 0, 0);
  11913. #endif
  11914. }
  11915. #endif
  11916. #if defined(MA_ATOMIC_HAS_64)
  11917. static MA_INLINE ma_uint64 ma_atomic_load_explicit_64(volatile const ma_uint64* ptr, ma_atomic_memory_order order)
  11918. {
  11919. #if defined(MA_ARM)
  11920. MA_ATOMIC_MSVC_ARM_INTRINSIC_COMPARE_EXCHANGE(ptr, 0, 0, order, _InterlockedCompareExchange64, ma_uint64, long long);
  11921. #else
  11922. (void)order;
  11923. return ma_atomic_compare_and_swap_64((volatile ma_uint64*)ptr, 0, 0);
  11924. #endif
  11925. }
  11926. #endif
  11927. #if defined(MA_ATOMIC_HAS_8)
  11928. #define ma_atomic_store_explicit_8( dst, src, order) (void)ma_atomic_exchange_explicit_8 (dst, src, order)
  11929. #endif
  11930. #if defined(MA_ATOMIC_HAS_16)
  11931. #define ma_atomic_store_explicit_16(dst, src, order) (void)ma_atomic_exchange_explicit_16(dst, src, order)
  11932. #endif
  11933. #if defined(MA_ATOMIC_HAS_32)
  11934. #define ma_atomic_store_explicit_32(dst, src, order) (void)ma_atomic_exchange_explicit_32(dst, src, order)
  11935. #endif
  11936. #if defined(MA_ATOMIC_HAS_64)
  11937. #define ma_atomic_store_explicit_64(dst, src, order) (void)ma_atomic_exchange_explicit_64(dst, src, order)
  11938. #endif
  11939. #if defined(MA_ATOMIC_HAS_8)
  11940. static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_sub_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  11941. {
  11942. ma_uint8 oldValue;
  11943. ma_uint8 newValue;
  11944. do {
  11945. oldValue = *dst;
  11946. newValue = (ma_uint8)(oldValue - src);
  11947. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  11948. (void)order;
  11949. return oldValue;
  11950. }
  11951. #endif
  11952. #if defined(MA_ATOMIC_HAS_16)
  11953. static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_sub_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  11954. {
  11955. ma_uint16 oldValue;
  11956. ma_uint16 newValue;
  11957. do {
  11958. oldValue = *dst;
  11959. newValue = (ma_uint16)(oldValue - src);
  11960. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  11961. (void)order;
  11962. return oldValue;
  11963. }
  11964. #endif
  11965. #if defined(MA_ATOMIC_HAS_32)
  11966. static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_sub_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  11967. {
  11968. ma_uint32 oldValue;
  11969. ma_uint32 newValue;
  11970. do {
  11971. oldValue = *dst;
  11972. newValue = oldValue - src;
  11973. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  11974. (void)order;
  11975. return oldValue;
  11976. }
  11977. #endif
  11978. #if defined(MA_ATOMIC_HAS_64)
  11979. static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_sub_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  11980. {
  11981. ma_uint64 oldValue;
  11982. ma_uint64 newValue;
  11983. do {
  11984. oldValue = *dst;
  11985. newValue = oldValue - src;
  11986. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11987. (void)order;
  11988. return oldValue;
  11989. }
  11990. #endif
  11991. #if defined(MA_ATOMIC_HAS_8)
  11992. static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_and_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  11993. {
  11994. #if defined(MA_ARM)
  11995. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd8, ma_uint8, char);
  11996. #else
  11997. ma_uint8 oldValue;
  11998. ma_uint8 newValue;
  11999. do {
  12000. oldValue = *dst;
  12001. newValue = (ma_uint8)(oldValue & src);
  12002. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12003. (void)order;
  12004. return oldValue;
  12005. #endif
  12006. }
  12007. #endif
  12008. #if defined(MA_ATOMIC_HAS_16)
  12009. static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_and_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12010. {
  12011. #if defined(MA_ARM)
  12012. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd16, ma_uint16, short);
  12013. #else
  12014. ma_uint16 oldValue;
  12015. ma_uint16 newValue;
  12016. do {
  12017. oldValue = *dst;
  12018. newValue = (ma_uint16)(oldValue & src);
  12019. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12020. (void)order;
  12021. return oldValue;
  12022. #endif
  12023. }
  12024. #endif
  12025. #if defined(MA_ATOMIC_HAS_32)
  12026. static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_and_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12027. {
  12028. #if defined(MA_ARM)
  12029. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd, ma_uint32, long);
  12030. #else
  12031. ma_uint32 oldValue;
  12032. ma_uint32 newValue;
  12033. do {
  12034. oldValue = *dst;
  12035. newValue = oldValue & src;
  12036. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12037. (void)order;
  12038. return oldValue;
  12039. #endif
  12040. }
  12041. #endif
  12042. #if defined(MA_ATOMIC_HAS_64)
  12043. static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_and_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12044. {
  12045. #if defined(MA_ARM)
  12046. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedAnd64, ma_uint64, long long);
  12047. #else
  12048. ma_uint64 oldValue;
  12049. ma_uint64 newValue;
  12050. do {
  12051. oldValue = *dst;
  12052. newValue = oldValue & src;
  12053. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12054. (void)order;
  12055. return oldValue;
  12056. #endif
  12057. }
  12058. #endif
  12059. #if defined(MA_ATOMIC_HAS_8)
  12060. static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_xor_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12061. {
  12062. #if defined(MA_ARM)
  12063. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor8, ma_uint8, char);
  12064. #else
  12065. ma_uint8 oldValue;
  12066. ma_uint8 newValue;
  12067. do {
  12068. oldValue = *dst;
  12069. newValue = (ma_uint8)(oldValue ^ src);
  12070. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12071. (void)order;
  12072. return oldValue;
  12073. #endif
  12074. }
  12075. #endif
  12076. #if defined(MA_ATOMIC_HAS_16)
  12077. static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_xor_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12078. {
  12079. #if defined(MA_ARM)
  12080. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor16, ma_uint16, short);
  12081. #else
  12082. ma_uint16 oldValue;
  12083. ma_uint16 newValue;
  12084. do {
  12085. oldValue = *dst;
  12086. newValue = (ma_uint16)(oldValue ^ src);
  12087. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12088. (void)order;
  12089. return oldValue;
  12090. #endif
  12091. }
  12092. #endif
  12093. #if defined(MA_ATOMIC_HAS_32)
  12094. static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_xor_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12095. {
  12096. #if defined(MA_ARM)
  12097. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor, ma_uint32, long);
  12098. #else
  12099. ma_uint32 oldValue;
  12100. ma_uint32 newValue;
  12101. do {
  12102. oldValue = *dst;
  12103. newValue = oldValue ^ src;
  12104. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12105. (void)order;
  12106. return oldValue;
  12107. #endif
  12108. }
  12109. #endif
  12110. #if defined(MA_ATOMIC_HAS_64)
  12111. static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_xor_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12112. {
  12113. #if defined(MA_ARM)
  12114. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedXor64, ma_uint64, long long);
  12115. #else
  12116. ma_uint64 oldValue;
  12117. ma_uint64 newValue;
  12118. do {
  12119. oldValue = *dst;
  12120. newValue = oldValue ^ src;
  12121. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12122. (void)order;
  12123. return oldValue;
  12124. #endif
  12125. }
  12126. #endif
  12127. #if defined(MA_ATOMIC_HAS_8)
  12128. static MA_INLINE ma_uint8 __stdcall ma_atomic_fetch_or_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12129. {
  12130. #if defined(MA_ARM)
  12131. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr8, ma_uint8, char);
  12132. #else
  12133. ma_uint8 oldValue;
  12134. ma_uint8 newValue;
  12135. do {
  12136. oldValue = *dst;
  12137. newValue = (ma_uint8)(oldValue | src);
  12138. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12139. (void)order;
  12140. return oldValue;
  12141. #endif
  12142. }
  12143. #endif
  12144. #if defined(MA_ATOMIC_HAS_16)
  12145. static MA_INLINE ma_uint16 __stdcall ma_atomic_fetch_or_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12146. {
  12147. #if defined(MA_ARM)
  12148. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr16, ma_uint16, short);
  12149. #else
  12150. ma_uint16 oldValue;
  12151. ma_uint16 newValue;
  12152. do {
  12153. oldValue = *dst;
  12154. newValue = (ma_uint16)(oldValue | src);
  12155. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12156. (void)order;
  12157. return oldValue;
  12158. #endif
  12159. }
  12160. #endif
  12161. #if defined(MA_ATOMIC_HAS_32)
  12162. static MA_INLINE ma_uint32 __stdcall ma_atomic_fetch_or_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12163. {
  12164. #if defined(MA_ARM)
  12165. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr, ma_uint32, long);
  12166. #else
  12167. ma_uint32 oldValue;
  12168. ma_uint32 newValue;
  12169. do {
  12170. oldValue = *dst;
  12171. newValue = oldValue | src;
  12172. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12173. (void)order;
  12174. return oldValue;
  12175. #endif
  12176. }
  12177. #endif
  12178. #if defined(MA_ATOMIC_HAS_64)
  12179. static MA_INLINE ma_uint64 __stdcall ma_atomic_fetch_or_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12180. {
  12181. #if defined(MA_ARM)
  12182. MA_ATOMIC_MSVC_ARM_INTRINSIC(dst, src, order, _InterlockedOr64, ma_uint64, long long);
  12183. #else
  12184. ma_uint64 oldValue;
  12185. ma_uint64 newValue;
  12186. do {
  12187. oldValue = *dst;
  12188. newValue = oldValue | src;
  12189. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12190. (void)order;
  12191. return oldValue;
  12192. #endif
  12193. }
  12194. #endif
  12195. #if defined(MA_ATOMIC_HAS_8)
  12196. #define ma_atomic_test_and_set_explicit_8( dst, order) ma_atomic_exchange_explicit_8 (dst, 1, order)
  12197. #endif
  12198. #if defined(MA_ATOMIC_HAS_16)
  12199. #define ma_atomic_test_and_set_explicit_16(dst, order) ma_atomic_exchange_explicit_16(dst, 1, order)
  12200. #endif
  12201. #if defined(MA_ATOMIC_HAS_32)
  12202. #define ma_atomic_test_and_set_explicit_32(dst, order) ma_atomic_exchange_explicit_32(dst, 1, order)
  12203. #endif
  12204. #if defined(MA_ATOMIC_HAS_64)
  12205. #define ma_atomic_test_and_set_explicit_64(dst, order) ma_atomic_exchange_explicit_64(dst, 1, order)
  12206. #endif
  12207. #if defined(MA_ATOMIC_HAS_8)
  12208. #define ma_atomic_clear_explicit_8( dst, order) ma_atomic_store_explicit_8 (dst, 0, order)
  12209. #endif
  12210. #if defined(MA_ATOMIC_HAS_16)
  12211. #define ma_atomic_clear_explicit_16(dst, order) ma_atomic_store_explicit_16(dst, 0, order)
  12212. #endif
  12213. #if defined(MA_ATOMIC_HAS_32)
  12214. #define ma_atomic_clear_explicit_32(dst, order) ma_atomic_store_explicit_32(dst, 0, order)
  12215. #endif
  12216. #if defined(MA_ATOMIC_HAS_64)
  12217. #define ma_atomic_clear_explicit_64(dst, order) ma_atomic_store_explicit_64(dst, 0, order)
  12218. #endif
  12219. #if defined(MA_ATOMIC_HAS_8)
  12220. typedef ma_uint8 ma_atomic_flag;
  12221. #define ma_atomic_flag_test_and_set_explicit(ptr, order) (ma_bool32)ma_atomic_test_and_set_explicit_8(ptr, order)
  12222. #define ma_atomic_flag_clear_explicit(ptr, order) ma_atomic_clear_explicit_8(ptr, order)
  12223. #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_8(ptr, order)
  12224. #else
  12225. typedef ma_uint32 ma_atomic_flag;
  12226. #define ma_atomic_flag_test_and_set_explicit(ptr, order) (ma_bool32)ma_atomic_test_and_set_explicit_32(ptr, order)
  12227. #define ma_atomic_flag_clear_explicit(ptr, order) ma_atomic_clear_explicit_32(ptr, order)
  12228. #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_32(ptr, order)
  12229. #endif
  12230. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  12231. #define MA_ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE
  12232. #define MA_ATOMIC_HAS_NATIVE_IS_LOCK_FREE
  12233. #define ma_atomic_memory_order_relaxed __ATOMIC_RELAXED
  12234. #define ma_atomic_memory_order_consume __ATOMIC_CONSUME
  12235. #define ma_atomic_memory_order_acquire __ATOMIC_ACQUIRE
  12236. #define ma_atomic_memory_order_release __ATOMIC_RELEASE
  12237. #define ma_atomic_memory_order_acq_rel __ATOMIC_ACQ_REL
  12238. #define ma_atomic_memory_order_seq_cst __ATOMIC_SEQ_CST
  12239. #define ma_atomic_compiler_fence() __asm__ __volatile__("":::"memory")
  12240. #define ma_atomic_thread_fence(order) __atomic_thread_fence(order)
  12241. #define ma_atomic_signal_fence(order) __atomic_signal_fence(order)
  12242. #define ma_atomic_is_lock_free_8(ptr) __atomic_is_lock_free(1, ptr)
  12243. #define ma_atomic_is_lock_free_16(ptr) __atomic_is_lock_free(2, ptr)
  12244. #define ma_atomic_is_lock_free_32(ptr) __atomic_is_lock_free(4, ptr)
  12245. #define ma_atomic_is_lock_free_64(ptr) __atomic_is_lock_free(8, ptr)
  12246. #define ma_atomic_test_and_set_explicit_8( dst, order) __atomic_exchange_n(dst, 1, order)
  12247. #define ma_atomic_test_and_set_explicit_16(dst, order) __atomic_exchange_n(dst, 1, order)
  12248. #define ma_atomic_test_and_set_explicit_32(dst, order) __atomic_exchange_n(dst, 1, order)
  12249. #define ma_atomic_test_and_set_explicit_64(dst, order) __atomic_exchange_n(dst, 1, order)
  12250. #define ma_atomic_clear_explicit_8( dst, order) __atomic_store_n(dst, 0, order)
  12251. #define ma_atomic_clear_explicit_16(dst, order) __atomic_store_n(dst, 0, order)
  12252. #define ma_atomic_clear_explicit_32(dst, order) __atomic_store_n(dst, 0, order)
  12253. #define ma_atomic_clear_explicit_64(dst, order) __atomic_store_n(dst, 0, order)
  12254. #define ma_atomic_store_explicit_8( dst, src, order) __atomic_store_n(dst, src, order)
  12255. #define ma_atomic_store_explicit_16(dst, src, order) __atomic_store_n(dst, src, order)
  12256. #define ma_atomic_store_explicit_32(dst, src, order) __atomic_store_n(dst, src, order)
  12257. #define ma_atomic_store_explicit_64(dst, src, order) __atomic_store_n(dst, src, order)
  12258. #define ma_atomic_load_explicit_8( dst, order) __atomic_load_n(dst, order)
  12259. #define ma_atomic_load_explicit_16(dst, order) __atomic_load_n(dst, order)
  12260. #define ma_atomic_load_explicit_32(dst, order) __atomic_load_n(dst, order)
  12261. #define ma_atomic_load_explicit_64(dst, order) __atomic_load_n(dst, order)
  12262. #define ma_atomic_exchange_explicit_8( dst, src, order) __atomic_exchange_n(dst, src, order)
  12263. #define ma_atomic_exchange_explicit_16(dst, src, order) __atomic_exchange_n(dst, src, order)
  12264. #define ma_atomic_exchange_explicit_32(dst, src, order) __atomic_exchange_n(dst, src, order)
  12265. #define ma_atomic_exchange_explicit_64(dst, src, order) __atomic_exchange_n(dst, src, order)
  12266. #define ma_atomic_compare_exchange_strong_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12267. #define ma_atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12268. #define ma_atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12269. #define ma_atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  12270. #define ma_atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12271. #define ma_atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12272. #define ma_atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12273. #define ma_atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  12274. #define ma_atomic_fetch_add_explicit_8( dst, src, order) __atomic_fetch_add(dst, src, order)
  12275. #define ma_atomic_fetch_add_explicit_16(dst, src, order) __atomic_fetch_add(dst, src, order)
  12276. #define ma_atomic_fetch_add_explicit_32(dst, src, order) __atomic_fetch_add(dst, src, order)
  12277. #define ma_atomic_fetch_add_explicit_64(dst, src, order) __atomic_fetch_add(dst, src, order)
  12278. #define ma_atomic_fetch_sub_explicit_8( dst, src, order) __atomic_fetch_sub(dst, src, order)
  12279. #define ma_atomic_fetch_sub_explicit_16(dst, src, order) __atomic_fetch_sub(dst, src, order)
  12280. #define ma_atomic_fetch_sub_explicit_32(dst, src, order) __atomic_fetch_sub(dst, src, order)
  12281. #define ma_atomic_fetch_sub_explicit_64(dst, src, order) __atomic_fetch_sub(dst, src, order)
  12282. #define ma_atomic_fetch_or_explicit_8( dst, src, order) __atomic_fetch_or(dst, src, order)
  12283. #define ma_atomic_fetch_or_explicit_16(dst, src, order) __atomic_fetch_or(dst, src, order)
  12284. #define ma_atomic_fetch_or_explicit_32(dst, src, order) __atomic_fetch_or(dst, src, order)
  12285. #define ma_atomic_fetch_or_explicit_64(dst, src, order) __atomic_fetch_or(dst, src, order)
  12286. #define ma_atomic_fetch_xor_explicit_8( dst, src, order) __atomic_fetch_xor(dst, src, order)
  12287. #define ma_atomic_fetch_xor_explicit_16(dst, src, order) __atomic_fetch_xor(dst, src, order)
  12288. #define ma_atomic_fetch_xor_explicit_32(dst, src, order) __atomic_fetch_xor(dst, src, order)
  12289. #define ma_atomic_fetch_xor_explicit_64(dst, src, order) __atomic_fetch_xor(dst, src, order)
  12290. #define ma_atomic_fetch_and_explicit_8( dst, src, order) __atomic_fetch_and(dst, src, order)
  12291. #define ma_atomic_fetch_and_explicit_16(dst, src, order) __atomic_fetch_and(dst, src, order)
  12292. #define ma_atomic_fetch_and_explicit_32(dst, src, order) __atomic_fetch_and(dst, src, order)
  12293. #define ma_atomic_fetch_and_explicit_64(dst, src, order) __atomic_fetch_and(dst, src, order)
  12294. static MA_INLINE ma_uint8 ma_atomic_compare_and_swap_8(volatile ma_uint8* dst, ma_uint8 expected, ma_uint8 desired)
  12295. {
  12296. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12297. return expected;
  12298. }
  12299. static MA_INLINE ma_uint16 ma_atomic_compare_and_swap_16(volatile ma_uint16* dst, ma_uint16 expected, ma_uint16 desired)
  12300. {
  12301. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12302. return expected;
  12303. }
  12304. static MA_INLINE ma_uint32 ma_atomic_compare_and_swap_32(volatile ma_uint32* dst, ma_uint32 expected, ma_uint32 desired)
  12305. {
  12306. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12307. return expected;
  12308. }
  12309. static MA_INLINE ma_uint64 ma_atomic_compare_and_swap_64(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired)
  12310. {
  12311. __atomic_compare_exchange_n(dst, &expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
  12312. return expected;
  12313. }
  12314. typedef ma_uint8 ma_atomic_flag;
  12315. #define ma_atomic_flag_test_and_set_explicit(dst, order) (ma_bool32)__atomic_test_and_set(dst, order)
  12316. #define ma_atomic_flag_clear_explicit(dst, order) __atomic_clear(dst, order)
  12317. #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_8(ptr, order)
  12318. #else
  12319. #define ma_atomic_memory_order_relaxed 1
  12320. #define ma_atomic_memory_order_consume 2
  12321. #define ma_atomic_memory_order_acquire 3
  12322. #define ma_atomic_memory_order_release 4
  12323. #define ma_atomic_memory_order_acq_rel 5
  12324. #define ma_atomic_memory_order_seq_cst 6
  12325. #define ma_atomic_compiler_fence() __asm__ __volatile__("":::"memory")
  12326. #if defined(__GNUC__)
  12327. #define ma_atomic_thread_fence(order) __sync_synchronize(), (void)order
  12328. static MA_INLINE ma_uint8 ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12329. {
  12330. if (order > ma_atomic_memory_order_acquire) {
  12331. __sync_synchronize();
  12332. }
  12333. return __sync_lock_test_and_set(dst, src);
  12334. }
  12335. static MA_INLINE ma_uint16 ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12336. {
  12337. ma_uint16 oldValue;
  12338. do {
  12339. oldValue = *dst;
  12340. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  12341. (void)order;
  12342. return oldValue;
  12343. }
  12344. static MA_INLINE ma_uint32 ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12345. {
  12346. ma_uint32 oldValue;
  12347. do {
  12348. oldValue = *dst;
  12349. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  12350. (void)order;
  12351. return oldValue;
  12352. }
  12353. static MA_INLINE ma_uint64 ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12354. {
  12355. ma_uint64 oldValue;
  12356. do {
  12357. oldValue = *dst;
  12358. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  12359. (void)order;
  12360. return oldValue;
  12361. }
  12362. static MA_INLINE ma_uint8 ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12363. {
  12364. (void)order;
  12365. return __sync_fetch_and_add(dst, src);
  12366. }
  12367. static MA_INLINE ma_uint16 ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12368. {
  12369. (void)order;
  12370. return __sync_fetch_and_add(dst, src);
  12371. }
  12372. static MA_INLINE ma_uint32 ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12373. {
  12374. (void)order;
  12375. return __sync_fetch_and_add(dst, src);
  12376. }
  12377. static MA_INLINE ma_uint64 ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12378. {
  12379. (void)order;
  12380. return __sync_fetch_and_add(dst, src);
  12381. }
  12382. static MA_INLINE ma_uint8 ma_atomic_fetch_sub_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12383. {
  12384. (void)order;
  12385. return __sync_fetch_and_sub(dst, src);
  12386. }
  12387. static MA_INLINE ma_uint16 ma_atomic_fetch_sub_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12388. {
  12389. (void)order;
  12390. return __sync_fetch_and_sub(dst, src);
  12391. }
  12392. static MA_INLINE ma_uint32 ma_atomic_fetch_sub_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12393. {
  12394. (void)order;
  12395. return __sync_fetch_and_sub(dst, src);
  12396. }
  12397. static MA_INLINE ma_uint64 ma_atomic_fetch_sub_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12398. {
  12399. (void)order;
  12400. return __sync_fetch_and_sub(dst, src);
  12401. }
  12402. static MA_INLINE ma_uint8 ma_atomic_fetch_or_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12403. {
  12404. (void)order;
  12405. return __sync_fetch_and_or(dst, src);
  12406. }
  12407. static MA_INLINE ma_uint16 ma_atomic_fetch_or_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12408. {
  12409. (void)order;
  12410. return __sync_fetch_and_or(dst, src);
  12411. }
  12412. static MA_INLINE ma_uint32 ma_atomic_fetch_or_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12413. {
  12414. (void)order;
  12415. return __sync_fetch_and_or(dst, src);
  12416. }
  12417. static MA_INLINE ma_uint64 ma_atomic_fetch_or_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12418. {
  12419. (void)order;
  12420. return __sync_fetch_and_or(dst, src);
  12421. }
  12422. static MA_INLINE ma_uint8 ma_atomic_fetch_xor_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12423. {
  12424. (void)order;
  12425. return __sync_fetch_and_xor(dst, src);
  12426. }
  12427. static MA_INLINE ma_uint16 ma_atomic_fetch_xor_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12428. {
  12429. (void)order;
  12430. return __sync_fetch_and_xor(dst, src);
  12431. }
  12432. static MA_INLINE ma_uint32 ma_atomic_fetch_xor_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12433. {
  12434. (void)order;
  12435. return __sync_fetch_and_xor(dst, src);
  12436. }
  12437. static MA_INLINE ma_uint64 ma_atomic_fetch_xor_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12438. {
  12439. (void)order;
  12440. return __sync_fetch_and_xor(dst, src);
  12441. }
  12442. static MA_INLINE ma_uint8 ma_atomic_fetch_and_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12443. {
  12444. (void)order;
  12445. return __sync_fetch_and_and(dst, src);
  12446. }
  12447. static MA_INLINE ma_uint16 ma_atomic_fetch_and_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12448. {
  12449. (void)order;
  12450. return __sync_fetch_and_and(dst, src);
  12451. }
  12452. static MA_INLINE ma_uint32 ma_atomic_fetch_and_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12453. {
  12454. (void)order;
  12455. return __sync_fetch_and_and(dst, src);
  12456. }
  12457. static MA_INLINE ma_uint64 ma_atomic_fetch_and_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12458. {
  12459. (void)order;
  12460. return __sync_fetch_and_and(dst, src);
  12461. }
  12462. #define ma_atomic_compare_and_swap_8( dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12463. #define ma_atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12464. #define ma_atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12465. #define ma_atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12466. #else
  12467. #if defined(MA_X86)
  12468. #define ma_atomic_thread_fence(order) __asm__ __volatile__("lock; addl $0, (%%esp)" ::: "memory", "cc")
  12469. #elif defined(MA_X64)
  12470. #define ma_atomic_thread_fence(order) __asm__ __volatile__("lock; addq $0, (%%rsp)" ::: "memory", "cc")
  12471. #else
  12472. #error Unsupported architecture. Please submit a feature request.
  12473. #endif
  12474. static MA_INLINE ma_uint8 ma_atomic_compare_and_swap_8(volatile ma_uint8* dst, ma_uint8 expected, ma_uint8 desired)
  12475. {
  12476. ma_uint8 result;
  12477. #if defined(MA_X86) || defined(MA_X64)
  12478. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12479. #else
  12480. #error Unsupported architecture. Please submit a feature request.
  12481. #endif
  12482. return result;
  12483. }
  12484. static MA_INLINE ma_uint16 ma_atomic_compare_and_swap_16(volatile ma_uint16* dst, ma_uint16 expected, ma_uint16 desired)
  12485. {
  12486. ma_uint16 result;
  12487. #if defined(MA_X86) || defined(MA_X64)
  12488. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12489. #else
  12490. #error Unsupported architecture. Please submit a feature request.
  12491. #endif
  12492. return result;
  12493. }
  12494. static MA_INLINE ma_uint32 ma_atomic_compare_and_swap_32(volatile ma_uint32* dst, ma_uint32 expected, ma_uint32 desired)
  12495. {
  12496. ma_uint32 result;
  12497. #if defined(MA_X86) || defined(MA_X64)
  12498. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12499. #else
  12500. #error Unsupported architecture. Please submit a feature request.
  12501. #endif
  12502. return result;
  12503. }
  12504. static MA_INLINE ma_uint64 ma_atomic_compare_and_swap_64(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired)
  12505. {
  12506. volatile ma_uint64 result;
  12507. #if defined(MA_X86)
  12508. ma_uint32 resultEAX;
  12509. ma_uint32 resultEDX;
  12510. __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");
  12511. result = ((ma_uint64)resultEDX << 32) | resultEAX;
  12512. #elif defined(MA_X64)
  12513. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12514. #else
  12515. #error Unsupported architecture. Please submit a feature request.
  12516. #endif
  12517. return result;
  12518. }
  12519. static MA_INLINE ma_uint8 ma_atomic_exchange_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12520. {
  12521. ma_uint8 result = 0;
  12522. (void)order;
  12523. #if defined(MA_X86) || defined(MA_X64)
  12524. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12525. #else
  12526. #error Unsupported architecture. Please submit a feature request.
  12527. #endif
  12528. return result;
  12529. }
  12530. static MA_INLINE ma_uint16 ma_atomic_exchange_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12531. {
  12532. ma_uint16 result = 0;
  12533. (void)order;
  12534. #if defined(MA_X86) || defined(MA_X64)
  12535. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12536. #else
  12537. #error Unsupported architecture. Please submit a feature request.
  12538. #endif
  12539. return result;
  12540. }
  12541. static MA_INLINE ma_uint32 ma_atomic_exchange_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12542. {
  12543. ma_uint32 result;
  12544. (void)order;
  12545. #if defined(MA_X86) || defined(MA_X64)
  12546. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12547. #else
  12548. #error Unsupported architecture. Please submit a feature request.
  12549. #endif
  12550. return result;
  12551. }
  12552. static MA_INLINE ma_uint64 ma_atomic_exchange_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12553. {
  12554. ma_uint64 result;
  12555. (void)order;
  12556. #if defined(MA_X86)
  12557. do {
  12558. result = *dst;
  12559. } while (ma_atomic_compare_and_swap_64(dst, result, src) != result);
  12560. #elif defined(MA_X64)
  12561. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12562. #else
  12563. #error Unsupported architecture. Please submit a feature request.
  12564. #endif
  12565. return result;
  12566. }
  12567. static MA_INLINE ma_uint8 ma_atomic_fetch_add_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12568. {
  12569. ma_uint8 result;
  12570. (void)order;
  12571. #if defined(MA_X86) || defined(MA_X64)
  12572. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12573. #else
  12574. #error Unsupported architecture. Please submit a feature request.
  12575. #endif
  12576. return result;
  12577. }
  12578. static MA_INLINE ma_uint16 ma_atomic_fetch_add_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12579. {
  12580. ma_uint16 result;
  12581. (void)order;
  12582. #if defined(MA_X86) || defined(MA_X64)
  12583. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12584. #else
  12585. #error Unsupported architecture. Please submit a feature request.
  12586. #endif
  12587. return result;
  12588. }
  12589. static MA_INLINE ma_uint32 ma_atomic_fetch_add_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12590. {
  12591. ma_uint32 result;
  12592. (void)order;
  12593. #if defined(MA_X86) || defined(MA_X64)
  12594. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12595. #else
  12596. #error Unsupported architecture. Please submit a feature request.
  12597. #endif
  12598. return result;
  12599. }
  12600. static MA_INLINE ma_uint64 ma_atomic_fetch_add_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12601. {
  12602. #if defined(MA_X86)
  12603. ma_uint64 oldValue;
  12604. ma_uint64 newValue;
  12605. (void)order;
  12606. do {
  12607. oldValue = *dst;
  12608. newValue = oldValue + src;
  12609. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12610. return oldValue;
  12611. #elif defined(MA_X64)
  12612. ma_uint64 result;
  12613. (void)order;
  12614. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12615. return result;
  12616. #endif
  12617. }
  12618. static MA_INLINE ma_uint8 ma_atomic_fetch_sub_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12619. {
  12620. ma_uint8 oldValue;
  12621. ma_uint8 newValue;
  12622. do {
  12623. oldValue = *dst;
  12624. newValue = (ma_uint8)(oldValue - src);
  12625. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12626. (void)order;
  12627. return oldValue;
  12628. }
  12629. static MA_INLINE ma_uint16 ma_atomic_fetch_sub_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12630. {
  12631. ma_uint16 oldValue;
  12632. ma_uint16 newValue;
  12633. do {
  12634. oldValue = *dst;
  12635. newValue = (ma_uint16)(oldValue - src);
  12636. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12637. (void)order;
  12638. return oldValue;
  12639. }
  12640. static MA_INLINE ma_uint32 ma_atomic_fetch_sub_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12641. {
  12642. ma_uint32 oldValue;
  12643. ma_uint32 newValue;
  12644. do {
  12645. oldValue = *dst;
  12646. newValue = oldValue - src;
  12647. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12648. (void)order;
  12649. return oldValue;
  12650. }
  12651. static MA_INLINE ma_uint64 ma_atomic_fetch_sub_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12652. {
  12653. ma_uint64 oldValue;
  12654. ma_uint64 newValue;
  12655. do {
  12656. oldValue = *dst;
  12657. newValue = oldValue - src;
  12658. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12659. (void)order;
  12660. return oldValue;
  12661. }
  12662. static MA_INLINE ma_uint8 ma_atomic_fetch_and_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12663. {
  12664. ma_uint8 oldValue;
  12665. ma_uint8 newValue;
  12666. do {
  12667. oldValue = *dst;
  12668. newValue = (ma_uint8)(oldValue & src);
  12669. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12670. (void)order;
  12671. return oldValue;
  12672. }
  12673. static MA_INLINE ma_uint16 ma_atomic_fetch_and_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12674. {
  12675. ma_uint16 oldValue;
  12676. ma_uint16 newValue;
  12677. do {
  12678. oldValue = *dst;
  12679. newValue = (ma_uint16)(oldValue & src);
  12680. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12681. (void)order;
  12682. return oldValue;
  12683. }
  12684. static MA_INLINE ma_uint32 ma_atomic_fetch_and_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12685. {
  12686. ma_uint32 oldValue;
  12687. ma_uint32 newValue;
  12688. do {
  12689. oldValue = *dst;
  12690. newValue = oldValue & src;
  12691. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12692. (void)order;
  12693. return oldValue;
  12694. }
  12695. static MA_INLINE ma_uint64 ma_atomic_fetch_and_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12696. {
  12697. ma_uint64 oldValue;
  12698. ma_uint64 newValue;
  12699. do {
  12700. oldValue = *dst;
  12701. newValue = oldValue & src;
  12702. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12703. (void)order;
  12704. return oldValue;
  12705. }
  12706. static MA_INLINE ma_uint8 ma_atomic_fetch_xor_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12707. {
  12708. ma_uint8 oldValue;
  12709. ma_uint8 newValue;
  12710. do {
  12711. oldValue = *dst;
  12712. newValue = (ma_uint8)(oldValue ^ src);
  12713. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12714. (void)order;
  12715. return oldValue;
  12716. }
  12717. static MA_INLINE ma_uint16 ma_atomic_fetch_xor_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12718. {
  12719. ma_uint16 oldValue;
  12720. ma_uint16 newValue;
  12721. do {
  12722. oldValue = *dst;
  12723. newValue = (ma_uint16)(oldValue ^ src);
  12724. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12725. (void)order;
  12726. return oldValue;
  12727. }
  12728. static MA_INLINE ma_uint32 ma_atomic_fetch_xor_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12729. {
  12730. ma_uint32 oldValue;
  12731. ma_uint32 newValue;
  12732. do {
  12733. oldValue = *dst;
  12734. newValue = oldValue ^ src;
  12735. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12736. (void)order;
  12737. return oldValue;
  12738. }
  12739. static MA_INLINE ma_uint64 ma_atomic_fetch_xor_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12740. {
  12741. ma_uint64 oldValue;
  12742. ma_uint64 newValue;
  12743. do {
  12744. oldValue = *dst;
  12745. newValue = oldValue ^ src;
  12746. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12747. (void)order;
  12748. return oldValue;
  12749. }
  12750. static MA_INLINE ma_uint8 ma_atomic_fetch_or_explicit_8(volatile ma_uint8* dst, ma_uint8 src, ma_atomic_memory_order order)
  12751. {
  12752. ma_uint8 oldValue;
  12753. ma_uint8 newValue;
  12754. do {
  12755. oldValue = *dst;
  12756. newValue = (ma_uint8)(oldValue | src);
  12757. } while (ma_atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12758. (void)order;
  12759. return oldValue;
  12760. }
  12761. static MA_INLINE ma_uint16 ma_atomic_fetch_or_explicit_16(volatile ma_uint16* dst, ma_uint16 src, ma_atomic_memory_order order)
  12762. {
  12763. ma_uint16 oldValue;
  12764. ma_uint16 newValue;
  12765. do {
  12766. oldValue = *dst;
  12767. newValue = (ma_uint16)(oldValue | src);
  12768. } while (ma_atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12769. (void)order;
  12770. return oldValue;
  12771. }
  12772. static MA_INLINE ma_uint32 ma_atomic_fetch_or_explicit_32(volatile ma_uint32* dst, ma_uint32 src, ma_atomic_memory_order order)
  12773. {
  12774. ma_uint32 oldValue;
  12775. ma_uint32 newValue;
  12776. do {
  12777. oldValue = *dst;
  12778. newValue = oldValue | src;
  12779. } while (ma_atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12780. (void)order;
  12781. return oldValue;
  12782. }
  12783. static MA_INLINE ma_uint64 ma_atomic_fetch_or_explicit_64(volatile ma_uint64* dst, ma_uint64 src, ma_atomic_memory_order order)
  12784. {
  12785. ma_uint64 oldValue;
  12786. ma_uint64 newValue;
  12787. do {
  12788. oldValue = *dst;
  12789. newValue = oldValue | src;
  12790. } while (ma_atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12791. (void)order;
  12792. return oldValue;
  12793. }
  12794. #endif
  12795. #define ma_atomic_signal_fence(order) ma_atomic_thread_fence(order)
  12796. static MA_INLINE ma_uint8 ma_atomic_load_explicit_8(volatile const ma_uint8* ptr, ma_atomic_memory_order order)
  12797. {
  12798. (void)order;
  12799. return ma_atomic_compare_and_swap_8((ma_uint8*)ptr, 0, 0);
  12800. }
  12801. static MA_INLINE ma_uint16 ma_atomic_load_explicit_16(volatile const ma_uint16* ptr, ma_atomic_memory_order order)
  12802. {
  12803. (void)order;
  12804. return ma_atomic_compare_and_swap_16((ma_uint16*)ptr, 0, 0);
  12805. }
  12806. static MA_INLINE ma_uint32 ma_atomic_load_explicit_32(volatile const ma_uint32* ptr, ma_atomic_memory_order order)
  12807. {
  12808. (void)order;
  12809. return ma_atomic_compare_and_swap_32((ma_uint32*)ptr, 0, 0);
  12810. }
  12811. static MA_INLINE ma_uint64 ma_atomic_load_explicit_64(volatile const ma_uint64* ptr, ma_atomic_memory_order order)
  12812. {
  12813. (void)order;
  12814. return ma_atomic_compare_and_swap_64((ma_uint64*)ptr, 0, 0);
  12815. }
  12816. #define ma_atomic_store_explicit_8( dst, src, order) (void)ma_atomic_exchange_explicit_8 (dst, src, order)
  12817. #define ma_atomic_store_explicit_16(dst, src, order) (void)ma_atomic_exchange_explicit_16(dst, src, order)
  12818. #define ma_atomic_store_explicit_32(dst, src, order) (void)ma_atomic_exchange_explicit_32(dst, src, order)
  12819. #define ma_atomic_store_explicit_64(dst, src, order) (void)ma_atomic_exchange_explicit_64(dst, src, order)
  12820. #define ma_atomic_test_and_set_explicit_8( dst, order) ma_atomic_exchange_explicit_8 (dst, 1, order)
  12821. #define ma_atomic_test_and_set_explicit_16(dst, order) ma_atomic_exchange_explicit_16(dst, 1, order)
  12822. #define ma_atomic_test_and_set_explicit_32(dst, order) ma_atomic_exchange_explicit_32(dst, 1, order)
  12823. #define ma_atomic_test_and_set_explicit_64(dst, order) ma_atomic_exchange_explicit_64(dst, 1, order)
  12824. #define ma_atomic_clear_explicit_8( dst, order) ma_atomic_store_explicit_8 (dst, 0, order)
  12825. #define ma_atomic_clear_explicit_16(dst, order) ma_atomic_store_explicit_16(dst, 0, order)
  12826. #define ma_atomic_clear_explicit_32(dst, order) ma_atomic_store_explicit_32(dst, 0, order)
  12827. #define ma_atomic_clear_explicit_64(dst, order) ma_atomic_store_explicit_64(dst, 0, order)
  12828. typedef ma_uint8 ma_atomic_flag;
  12829. #define ma_atomic_flag_test_and_set_explicit(ptr, order) (ma_bool32)ma_atomic_test_and_set_explicit_8(ptr, order)
  12830. #define ma_atomic_flag_clear_explicit(ptr, order) ma_atomic_clear_explicit_8(ptr, order)
  12831. #define c89atoimc_flag_load_explicit(ptr, order) ma_atomic_load_explicit_8(ptr, order)
  12832. #endif
  12833. #if !defined(MA_ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE)
  12834. #if defined(MA_ATOMIC_HAS_8)
  12835. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_8(volatile ma_uint8* dst, ma_uint8* expected, ma_uint8 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12836. {
  12837. ma_uint8 expectedValue;
  12838. ma_uint8 result;
  12839. (void)successOrder;
  12840. (void)failureOrder;
  12841. expectedValue = ma_atomic_load_explicit_8(expected, ma_atomic_memory_order_seq_cst);
  12842. result = ma_atomic_compare_and_swap_8(dst, expectedValue, desired);
  12843. if (result == expectedValue) {
  12844. return 1;
  12845. } else {
  12846. ma_atomic_store_explicit_8(expected, result, failureOrder);
  12847. return 0;
  12848. }
  12849. }
  12850. #endif
  12851. #if defined(MA_ATOMIC_HAS_16)
  12852. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_16(volatile ma_uint16* dst, ma_uint16* expected, ma_uint16 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12853. {
  12854. ma_uint16 expectedValue;
  12855. ma_uint16 result;
  12856. (void)successOrder;
  12857. (void)failureOrder;
  12858. expectedValue = ma_atomic_load_explicit_16(expected, ma_atomic_memory_order_seq_cst);
  12859. result = ma_atomic_compare_and_swap_16(dst, expectedValue, desired);
  12860. if (result == expectedValue) {
  12861. return 1;
  12862. } else {
  12863. ma_atomic_store_explicit_16(expected, result, failureOrder);
  12864. return 0;
  12865. }
  12866. }
  12867. #endif
  12868. #if defined(MA_ATOMIC_HAS_32)
  12869. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_32(volatile ma_uint32* dst, ma_uint32* expected, ma_uint32 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12870. {
  12871. ma_uint32 expectedValue;
  12872. ma_uint32 result;
  12873. (void)successOrder;
  12874. (void)failureOrder;
  12875. expectedValue = ma_atomic_load_explicit_32(expected, ma_atomic_memory_order_seq_cst);
  12876. result = ma_atomic_compare_and_swap_32(dst, expectedValue, desired);
  12877. if (result == expectedValue) {
  12878. return 1;
  12879. } else {
  12880. ma_atomic_store_explicit_32(expected, result, failureOrder);
  12881. return 0;
  12882. }
  12883. }
  12884. #endif
  12885. #if defined(MA_ATOMIC_HAS_64)
  12886. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_64(volatile ma_uint64* dst, volatile ma_uint64* expected, ma_uint64 desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12887. {
  12888. ma_uint64 expectedValue;
  12889. ma_uint64 result;
  12890. (void)successOrder;
  12891. (void)failureOrder;
  12892. expectedValue = ma_atomic_load_explicit_64(expected, ma_atomic_memory_order_seq_cst);
  12893. result = ma_atomic_compare_and_swap_64(dst, expectedValue, desired);
  12894. if (result == expectedValue) {
  12895. return 1;
  12896. } else {
  12897. ma_atomic_store_explicit_64(expected, result, failureOrder);
  12898. return 0;
  12899. }
  12900. }
  12901. #endif
  12902. #define ma_atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_8 (dst, expected, desired, successOrder, failureOrder)
  12903. #define ma_atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder)
  12904. #define ma_atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder)
  12905. #define ma_atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder)
  12906. #endif
  12907. #if !defined(MA_ATOMIC_HAS_NATIVE_IS_LOCK_FREE)
  12908. static MA_INLINE ma_bool32 ma_atomic_is_lock_free_8(volatile void* ptr)
  12909. {
  12910. (void)ptr;
  12911. return 1;
  12912. }
  12913. static MA_INLINE ma_bool32 ma_atomic_is_lock_free_16(volatile void* ptr)
  12914. {
  12915. (void)ptr;
  12916. return 1;
  12917. }
  12918. static MA_INLINE ma_bool32 ma_atomic_is_lock_free_32(volatile void* ptr)
  12919. {
  12920. (void)ptr;
  12921. return 1;
  12922. }
  12923. static MA_INLINE ma_bool32 ma_atomic_is_lock_free_64(volatile void* ptr)
  12924. {
  12925. (void)ptr;
  12926. #if defined(MA_64BIT)
  12927. return 1;
  12928. #else
  12929. #if defined(MA_X86) || defined(MA_X64)
  12930. return 1;
  12931. #else
  12932. return 0;
  12933. #endif
  12934. #endif
  12935. }
  12936. #endif
  12937. #if defined(MA_64BIT)
  12938. static MA_INLINE ma_bool32 ma_atomic_is_lock_free_ptr(volatile void** ptr)
  12939. {
  12940. return ma_atomic_is_lock_free_64((volatile ma_uint64*)ptr);
  12941. }
  12942. static MA_INLINE void* ma_atomic_load_explicit_ptr(volatile void** ptr, ma_atomic_memory_order order)
  12943. {
  12944. return (void*)ma_atomic_load_explicit_64((volatile ma_uint64*)ptr, order);
  12945. }
  12946. static MA_INLINE void ma_atomic_store_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order)
  12947. {
  12948. ma_atomic_store_explicit_64((volatile ma_uint64*)dst, (ma_uint64)src, order);
  12949. }
  12950. static MA_INLINE void* ma_atomic_exchange_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order)
  12951. {
  12952. return (void*)ma_atomic_exchange_explicit_64((volatile ma_uint64*)dst, (ma_uint64)src, order);
  12953. }
  12954. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12955. {
  12956. return ma_atomic_compare_exchange_strong_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder);
  12957. }
  12958. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12959. {
  12960. return ma_atomic_compare_exchange_weak_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder);
  12961. }
  12962. static MA_INLINE void* ma_atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
  12963. {
  12964. return (void*)ma_atomic_compare_and_swap_64((volatile ma_uint64*)dst, (ma_uint64)expected, (ma_uint64)desired);
  12965. }
  12966. #elif defined(MA_32BIT)
  12967. static MA_INLINE ma_bool32 ma_atomic_is_lock_free_ptr(volatile void** ptr)
  12968. {
  12969. return ma_atomic_is_lock_free_32((volatile ma_uint32*)ptr);
  12970. }
  12971. static MA_INLINE void* ma_atomic_load_explicit_ptr(volatile void** ptr, ma_atomic_memory_order order)
  12972. {
  12973. return (void*)ma_atomic_load_explicit_32((volatile ma_uint32*)ptr, order);
  12974. }
  12975. static MA_INLINE void ma_atomic_store_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order)
  12976. {
  12977. ma_atomic_store_explicit_32((volatile ma_uint32*)dst, (ma_uint32)src, order);
  12978. }
  12979. static MA_INLINE void* ma_atomic_exchange_explicit_ptr(volatile void** dst, void* src, ma_atomic_memory_order order)
  12980. {
  12981. return (void*)ma_atomic_exchange_explicit_32((volatile ma_uint32*)dst, (ma_uint32)src, order);
  12982. }
  12983. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12984. {
  12985. return ma_atomic_compare_exchange_strong_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder);
  12986. }
  12987. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  12988. {
  12989. return ma_atomic_compare_exchange_weak_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder);
  12990. }
  12991. static MA_INLINE void* ma_atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
  12992. {
  12993. return (void*)ma_atomic_compare_and_swap_32((volatile ma_uint32*)dst, (ma_uint32)expected, (ma_uint32)desired);
  12994. }
  12995. #else
  12996. #error Unsupported architecture.
  12997. #endif
  12998. #define ma_atomic_flag_test_and_set(ptr) ma_atomic_flag_test_and_set_explicit(ptr, ma_atomic_memory_order_seq_cst)
  12999. #define ma_atomic_flag_clear(ptr) ma_atomic_flag_clear_explicit(ptr, ma_atomic_memory_order_seq_cst)
  13000. #define ma_atomic_store_ptr(dst, src) ma_atomic_store_explicit_ptr((volatile void**)dst, (void*)src, ma_atomic_memory_order_seq_cst)
  13001. #define ma_atomic_load_ptr(ptr) ma_atomic_load_explicit_ptr((volatile void**)ptr, ma_atomic_memory_order_seq_cst)
  13002. #define ma_atomic_exchange_ptr(dst, src) ma_atomic_exchange_explicit_ptr((volatile void**)dst, (void*)src, ma_atomic_memory_order_seq_cst)
  13003. #define ma_atomic_compare_exchange_strong_ptr(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13004. #define ma_atomic_compare_exchange_weak_ptr(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13005. #define ma_atomic_test_and_set_8( ptr) ma_atomic_test_and_set_explicit_8( ptr, ma_atomic_memory_order_seq_cst)
  13006. #define ma_atomic_test_and_set_16(ptr) ma_atomic_test_and_set_explicit_16(ptr, ma_atomic_memory_order_seq_cst)
  13007. #define ma_atomic_test_and_set_32(ptr) ma_atomic_test_and_set_explicit_32(ptr, ma_atomic_memory_order_seq_cst)
  13008. #define ma_atomic_test_and_set_64(ptr) ma_atomic_test_and_set_explicit_64(ptr, ma_atomic_memory_order_seq_cst)
  13009. #define ma_atomic_clear_8( ptr) ma_atomic_clear_explicit_8( ptr, ma_atomic_memory_order_seq_cst)
  13010. #define ma_atomic_clear_16(ptr) ma_atomic_clear_explicit_16(ptr, ma_atomic_memory_order_seq_cst)
  13011. #define ma_atomic_clear_32(ptr) ma_atomic_clear_explicit_32(ptr, ma_atomic_memory_order_seq_cst)
  13012. #define ma_atomic_clear_64(ptr) ma_atomic_clear_explicit_64(ptr, ma_atomic_memory_order_seq_cst)
  13013. #define ma_atomic_store_8( dst, src) ma_atomic_store_explicit_8( dst, src, ma_atomic_memory_order_seq_cst)
  13014. #define ma_atomic_store_16(dst, src) ma_atomic_store_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13015. #define ma_atomic_store_32(dst, src) ma_atomic_store_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13016. #define ma_atomic_store_64(dst, src) ma_atomic_store_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13017. #define ma_atomic_load_8( ptr) ma_atomic_load_explicit_8( ptr, ma_atomic_memory_order_seq_cst)
  13018. #define ma_atomic_load_16(ptr) ma_atomic_load_explicit_16(ptr, ma_atomic_memory_order_seq_cst)
  13019. #define ma_atomic_load_32(ptr) ma_atomic_load_explicit_32(ptr, ma_atomic_memory_order_seq_cst)
  13020. #define ma_atomic_load_64(ptr) ma_atomic_load_explicit_64(ptr, ma_atomic_memory_order_seq_cst)
  13021. #define ma_atomic_exchange_8( dst, src) ma_atomic_exchange_explicit_8( dst, src, ma_atomic_memory_order_seq_cst)
  13022. #define ma_atomic_exchange_16(dst, src) ma_atomic_exchange_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13023. #define ma_atomic_exchange_32(dst, src) ma_atomic_exchange_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13024. #define ma_atomic_exchange_64(dst, src) ma_atomic_exchange_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13025. #define ma_atomic_compare_exchange_strong_8( dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13026. #define ma_atomic_compare_exchange_strong_16(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13027. #define ma_atomic_compare_exchange_strong_32(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13028. #define ma_atomic_compare_exchange_strong_64(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13029. #define ma_atomic_compare_exchange_weak_8( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13030. #define ma_atomic_compare_exchange_weak_16( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13031. #define ma_atomic_compare_exchange_weak_32( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13032. #define ma_atomic_compare_exchange_weak_64( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13033. #define ma_atomic_fetch_add_8( dst, src) ma_atomic_fetch_add_explicit_8( dst, src, ma_atomic_memory_order_seq_cst)
  13034. #define ma_atomic_fetch_add_16(dst, src) ma_atomic_fetch_add_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13035. #define ma_atomic_fetch_add_32(dst, src) ma_atomic_fetch_add_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13036. #define ma_atomic_fetch_add_64(dst, src) ma_atomic_fetch_add_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13037. #define ma_atomic_fetch_sub_8( dst, src) ma_atomic_fetch_sub_explicit_8( dst, src, ma_atomic_memory_order_seq_cst)
  13038. #define ma_atomic_fetch_sub_16(dst, src) ma_atomic_fetch_sub_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13039. #define ma_atomic_fetch_sub_32(dst, src) ma_atomic_fetch_sub_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13040. #define ma_atomic_fetch_sub_64(dst, src) ma_atomic_fetch_sub_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13041. #define ma_atomic_fetch_or_8( dst, src) ma_atomic_fetch_or_explicit_8( dst, src, ma_atomic_memory_order_seq_cst)
  13042. #define ma_atomic_fetch_or_16(dst, src) ma_atomic_fetch_or_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13043. #define ma_atomic_fetch_or_32(dst, src) ma_atomic_fetch_or_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13044. #define ma_atomic_fetch_or_64(dst, src) ma_atomic_fetch_or_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13045. #define ma_atomic_fetch_xor_8( dst, src) ma_atomic_fetch_xor_explicit_8( dst, src, ma_atomic_memory_order_seq_cst)
  13046. #define ma_atomic_fetch_xor_16(dst, src) ma_atomic_fetch_xor_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13047. #define ma_atomic_fetch_xor_32(dst, src) ma_atomic_fetch_xor_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13048. #define ma_atomic_fetch_xor_64(dst, src) ma_atomic_fetch_xor_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13049. #define ma_atomic_fetch_and_8( dst, src) ma_atomic_fetch_and_explicit_8 (dst, src, ma_atomic_memory_order_seq_cst)
  13050. #define ma_atomic_fetch_and_16(dst, src) ma_atomic_fetch_and_explicit_16(dst, src, ma_atomic_memory_order_seq_cst)
  13051. #define ma_atomic_fetch_and_32(dst, src) ma_atomic_fetch_and_explicit_32(dst, src, ma_atomic_memory_order_seq_cst)
  13052. #define ma_atomic_fetch_and_64(dst, src) ma_atomic_fetch_and_explicit_64(dst, src, ma_atomic_memory_order_seq_cst)
  13053. #define ma_atomic_test_and_set_explicit_i8( ptr, order) (ma_int8 )ma_atomic_test_and_set_explicit_8( (ma_uint8* )ptr, order)
  13054. #define ma_atomic_test_and_set_explicit_i16(ptr, order) (ma_int16)ma_atomic_test_and_set_explicit_16((ma_uint16*)ptr, order)
  13055. #define ma_atomic_test_and_set_explicit_i32(ptr, order) (ma_int32)ma_atomic_test_and_set_explicit_32((ma_uint32*)ptr, order)
  13056. #define ma_atomic_test_and_set_explicit_i64(ptr, order) (ma_int64)ma_atomic_test_and_set_explicit_64((ma_uint64*)ptr, order)
  13057. #define ma_atomic_clear_explicit_i8( ptr, order) ma_atomic_clear_explicit_8( (ma_uint8* )ptr, order)
  13058. #define ma_atomic_clear_explicit_i16(ptr, order) ma_atomic_clear_explicit_16((ma_uint16*)ptr, order)
  13059. #define ma_atomic_clear_explicit_i32(ptr, order) ma_atomic_clear_explicit_32((ma_uint32*)ptr, order)
  13060. #define ma_atomic_clear_explicit_i64(ptr, order) ma_atomic_clear_explicit_64((ma_uint64*)ptr, order)
  13061. #define ma_atomic_store_explicit_i8( dst, src, order) ma_atomic_store_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order)
  13062. #define ma_atomic_store_explicit_i16(dst, src, order) ma_atomic_store_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13063. #define ma_atomic_store_explicit_i32(dst, src, order) ma_atomic_store_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13064. #define ma_atomic_store_explicit_i64(dst, src, order) ma_atomic_store_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13065. #define ma_atomic_load_explicit_i8( ptr, order) (ma_int8 )ma_atomic_load_explicit_8( (ma_uint8* )ptr, order)
  13066. #define ma_atomic_load_explicit_i16(ptr, order) (ma_int16)ma_atomic_load_explicit_16((ma_uint16*)ptr, order)
  13067. #define ma_atomic_load_explicit_i32(ptr, order) (ma_int32)ma_atomic_load_explicit_32((ma_uint32*)ptr, order)
  13068. #define ma_atomic_load_explicit_i64(ptr, order) (ma_int64)ma_atomic_load_explicit_64((ma_uint64*)ptr, order)
  13069. #define ma_atomic_exchange_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_exchange_explicit_8 ((ma_uint8* )dst, (ma_uint8 )src, order)
  13070. #define ma_atomic_exchange_explicit_i16(dst, src, order) (ma_int16)ma_atomic_exchange_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13071. #define ma_atomic_exchange_explicit_i32(dst, src, order) (ma_int32)ma_atomic_exchange_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13072. #define ma_atomic_exchange_explicit_i64(dst, src, order) (ma_int64)ma_atomic_exchange_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13073. #define ma_atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_8( (ma_uint8* )dst, (ma_uint8* )expected, (ma_uint8 )desired, successOrder, failureOrder)
  13074. #define ma_atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_16((ma_uint16*)dst, (ma_uint16*)expected, (ma_uint16)desired, successOrder, failureOrder)
  13075. #define ma_atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_32((ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder)
  13076. #define ma_atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_strong_explicit_64((ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder)
  13077. #define ma_atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_8( (ma_uint8* )dst, (ma_uint8* )expected, (ma_uint8 )desired, successOrder, failureOrder)
  13078. #define ma_atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_16((ma_uint16*)dst, (ma_uint16*)expected, (ma_uint16)desired, successOrder, failureOrder)
  13079. #define ma_atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_32((ma_uint32*)dst, (ma_uint32*)expected, (ma_uint32)desired, successOrder, failureOrder)
  13080. #define ma_atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, successOrder, failureOrder) ma_atomic_compare_exchange_weak_explicit_64((ma_uint64*)dst, (ma_uint64*)expected, (ma_uint64)desired, successOrder, failureOrder)
  13081. #define ma_atomic_fetch_add_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_add_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order)
  13082. #define ma_atomic_fetch_add_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_add_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13083. #define ma_atomic_fetch_add_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_add_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13084. #define ma_atomic_fetch_add_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_add_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13085. #define ma_atomic_fetch_sub_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_sub_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order)
  13086. #define ma_atomic_fetch_sub_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_sub_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13087. #define ma_atomic_fetch_sub_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_sub_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13088. #define ma_atomic_fetch_sub_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_sub_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13089. #define ma_atomic_fetch_or_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_or_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order)
  13090. #define ma_atomic_fetch_or_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_or_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13091. #define ma_atomic_fetch_or_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_or_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13092. #define ma_atomic_fetch_or_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_or_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13093. #define ma_atomic_fetch_xor_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_xor_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order)
  13094. #define ma_atomic_fetch_xor_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_xor_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13095. #define ma_atomic_fetch_xor_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_xor_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13096. #define ma_atomic_fetch_xor_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_xor_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13097. #define ma_atomic_fetch_and_explicit_i8( dst, src, order) (ma_int8 )ma_atomic_fetch_and_explicit_8( (ma_uint8* )dst, (ma_uint8 )src, order)
  13098. #define ma_atomic_fetch_and_explicit_i16(dst, src, order) (ma_int16)ma_atomic_fetch_and_explicit_16((ma_uint16*)dst, (ma_uint16)src, order)
  13099. #define ma_atomic_fetch_and_explicit_i32(dst, src, order) (ma_int32)ma_atomic_fetch_and_explicit_32((ma_uint32*)dst, (ma_uint32)src, order)
  13100. #define ma_atomic_fetch_and_explicit_i64(dst, src, order) (ma_int64)ma_atomic_fetch_and_explicit_64((ma_uint64*)dst, (ma_uint64)src, order)
  13101. #define ma_atomic_test_and_set_i8( ptr) ma_atomic_test_and_set_explicit_i8( ptr, ma_atomic_memory_order_seq_cst)
  13102. #define ma_atomic_test_and_set_i16(ptr) ma_atomic_test_and_set_explicit_i16(ptr, ma_atomic_memory_order_seq_cst)
  13103. #define ma_atomic_test_and_set_i32(ptr) ma_atomic_test_and_set_explicit_i32(ptr, ma_atomic_memory_order_seq_cst)
  13104. #define ma_atomic_test_and_set_i64(ptr) ma_atomic_test_and_set_explicit_i64(ptr, ma_atomic_memory_order_seq_cst)
  13105. #define ma_atomic_clear_i8( ptr) ma_atomic_clear_explicit_i8( ptr, ma_atomic_memory_order_seq_cst)
  13106. #define ma_atomic_clear_i16(ptr) ma_atomic_clear_explicit_i16(ptr, ma_atomic_memory_order_seq_cst)
  13107. #define ma_atomic_clear_i32(ptr) ma_atomic_clear_explicit_i32(ptr, ma_atomic_memory_order_seq_cst)
  13108. #define ma_atomic_clear_i64(ptr) ma_atomic_clear_explicit_i64(ptr, ma_atomic_memory_order_seq_cst)
  13109. #define ma_atomic_store_i8( dst, src) ma_atomic_store_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13110. #define ma_atomic_store_i16(dst, src) ma_atomic_store_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13111. #define ma_atomic_store_i32(dst, src) ma_atomic_store_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13112. #define ma_atomic_store_i64(dst, src) ma_atomic_store_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13113. #define ma_atomic_load_i8( ptr) ma_atomic_load_explicit_i8( ptr, ma_atomic_memory_order_seq_cst)
  13114. #define ma_atomic_load_i16(ptr) ma_atomic_load_explicit_i16(ptr, ma_atomic_memory_order_seq_cst)
  13115. #define ma_atomic_load_i32(ptr) ma_atomic_load_explicit_i32(ptr, ma_atomic_memory_order_seq_cst)
  13116. #define ma_atomic_load_i64(ptr) ma_atomic_load_explicit_i64(ptr, ma_atomic_memory_order_seq_cst)
  13117. #define ma_atomic_exchange_i8( dst, src) ma_atomic_exchange_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13118. #define ma_atomic_exchange_i16(dst, src) ma_atomic_exchange_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13119. #define ma_atomic_exchange_i32(dst, src) ma_atomic_exchange_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13120. #define ma_atomic_exchange_i64(dst, src) ma_atomic_exchange_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13121. #define ma_atomic_compare_exchange_strong_i8( dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13122. #define ma_atomic_compare_exchange_strong_i16(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13123. #define ma_atomic_compare_exchange_strong_i32(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13124. #define ma_atomic_compare_exchange_strong_i64(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13125. #define ma_atomic_compare_exchange_weak_i8( dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13126. #define ma_atomic_compare_exchange_weak_i16(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13127. #define ma_atomic_compare_exchange_weak_i32(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13128. #define ma_atomic_compare_exchange_weak_i64(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13129. #define ma_atomic_fetch_add_i8( dst, src) ma_atomic_fetch_add_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13130. #define ma_atomic_fetch_add_i16(dst, src) ma_atomic_fetch_add_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13131. #define ma_atomic_fetch_add_i32(dst, src) ma_atomic_fetch_add_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13132. #define ma_atomic_fetch_add_i64(dst, src) ma_atomic_fetch_add_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13133. #define ma_atomic_fetch_sub_i8( dst, src) ma_atomic_fetch_sub_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13134. #define ma_atomic_fetch_sub_i16(dst, src) ma_atomic_fetch_sub_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13135. #define ma_atomic_fetch_sub_i32(dst, src) ma_atomic_fetch_sub_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13136. #define ma_atomic_fetch_sub_i64(dst, src) ma_atomic_fetch_sub_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13137. #define ma_atomic_fetch_or_i8( dst, src) ma_atomic_fetch_or_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13138. #define ma_atomic_fetch_or_i16(dst, src) ma_atomic_fetch_or_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13139. #define ma_atomic_fetch_or_i32(dst, src) ma_atomic_fetch_or_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13140. #define ma_atomic_fetch_or_i64(dst, src) ma_atomic_fetch_or_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13141. #define ma_atomic_fetch_xor_i8( dst, src) ma_atomic_fetch_xor_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13142. #define ma_atomic_fetch_xor_i16(dst, src) ma_atomic_fetch_xor_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13143. #define ma_atomic_fetch_xor_i32(dst, src) ma_atomic_fetch_xor_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13144. #define ma_atomic_fetch_xor_i64(dst, src) ma_atomic_fetch_xor_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13145. #define ma_atomic_fetch_and_i8( dst, src) ma_atomic_fetch_and_explicit_i8( dst, src, ma_atomic_memory_order_seq_cst)
  13146. #define ma_atomic_fetch_and_i16(dst, src) ma_atomic_fetch_and_explicit_i16(dst, src, ma_atomic_memory_order_seq_cst)
  13147. #define ma_atomic_fetch_and_i32(dst, src) ma_atomic_fetch_and_explicit_i32(dst, src, ma_atomic_memory_order_seq_cst)
  13148. #define ma_atomic_fetch_and_i64(dst, src) ma_atomic_fetch_and_explicit_i64(dst, src, ma_atomic_memory_order_seq_cst)
  13149. #define ma_atomic_compare_and_swap_i8( dst, expected, dedsired) (ma_int8 )ma_atomic_compare_and_swap_8( (ma_uint8* )dst, (ma_uint8 )expected, (ma_uint8 )dedsired)
  13150. #define ma_atomic_compare_and_swap_i16(dst, expected, dedsired) (ma_int16)ma_atomic_compare_and_swap_16((ma_uint16*)dst, (ma_uint16)expected, (ma_uint16)dedsired)
  13151. #define ma_atomic_compare_and_swap_i32(dst, expected, dedsired) (ma_int32)ma_atomic_compare_and_swap_32((ma_uint32*)dst, (ma_uint32)expected, (ma_uint32)dedsired)
  13152. #define ma_atomic_compare_and_swap_i64(dst, expected, dedsired) (ma_int64)ma_atomic_compare_and_swap_64((ma_uint64*)dst, (ma_uint64)expected, (ma_uint64)dedsired)
  13153. typedef union
  13154. {
  13155. ma_uint32 i;
  13156. float f;
  13157. } ma_atomic_if32;
  13158. typedef union
  13159. {
  13160. ma_uint64 i;
  13161. double f;
  13162. } ma_atomic_if64;
  13163. #define ma_atomic_clear_explicit_f32(ptr, order) ma_atomic_clear_explicit_32((ma_uint32*)ptr, order)
  13164. #define ma_atomic_clear_explicit_f64(ptr, order) ma_atomic_clear_explicit_64((ma_uint64*)ptr, order)
  13165. static MA_INLINE void ma_atomic_store_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13166. {
  13167. ma_atomic_if32 x;
  13168. x.f = src;
  13169. ma_atomic_store_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13170. }
  13171. static MA_INLINE void ma_atomic_store_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13172. {
  13173. ma_atomic_if64 x;
  13174. x.f = src;
  13175. ma_atomic_store_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13176. }
  13177. static MA_INLINE float ma_atomic_load_explicit_f32(volatile const float* ptr, ma_atomic_memory_order order)
  13178. {
  13179. ma_atomic_if32 r;
  13180. r.i = ma_atomic_load_explicit_32((volatile const ma_uint32*)ptr, order);
  13181. return r.f;
  13182. }
  13183. static MA_INLINE double ma_atomic_load_explicit_f64(volatile const double* ptr, ma_atomic_memory_order order)
  13184. {
  13185. ma_atomic_if64 r;
  13186. r.i = ma_atomic_load_explicit_64((volatile const ma_uint64*)ptr, order);
  13187. return r.f;
  13188. }
  13189. static MA_INLINE float ma_atomic_exchange_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13190. {
  13191. ma_atomic_if32 r;
  13192. ma_atomic_if32 x;
  13193. x.f = src;
  13194. r.i = ma_atomic_exchange_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13195. return r.f;
  13196. }
  13197. static MA_INLINE double ma_atomic_exchange_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13198. {
  13199. ma_atomic_if64 r;
  13200. ma_atomic_if64 x;
  13201. x.f = src;
  13202. r.i = ma_atomic_exchange_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13203. return r.f;
  13204. }
  13205. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_f32(volatile float* dst, float* expected, float desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  13206. {
  13207. ma_atomic_if32 d;
  13208. d.f = desired;
  13209. return ma_atomic_compare_exchange_strong_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, d.i, successOrder, failureOrder);
  13210. }
  13211. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_strong_explicit_f64(volatile double* dst, double* expected, double desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  13212. {
  13213. ma_atomic_if64 d;
  13214. d.f = desired;
  13215. return ma_atomic_compare_exchange_strong_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, d.i, successOrder, failureOrder);
  13216. }
  13217. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_f32(volatile float* dst, float* expected, float desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  13218. {
  13219. ma_atomic_if32 d;
  13220. d.f = desired;
  13221. return ma_atomic_compare_exchange_weak_explicit_32((volatile ma_uint32*)dst, (ma_uint32*)expected, d.i, successOrder, failureOrder);
  13222. }
  13223. static MA_INLINE ma_bool32 ma_atomic_compare_exchange_weak_explicit_f64(volatile double* dst, double* expected, double desired, ma_atomic_memory_order successOrder, ma_atomic_memory_order failureOrder)
  13224. {
  13225. ma_atomic_if64 d;
  13226. d.f = desired;
  13227. return ma_atomic_compare_exchange_weak_explicit_64((volatile ma_uint64*)dst, (ma_uint64*)expected, d.i, successOrder, failureOrder);
  13228. }
  13229. static MA_INLINE float ma_atomic_fetch_add_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13230. {
  13231. ma_atomic_if32 r;
  13232. ma_atomic_if32 x;
  13233. x.f = src;
  13234. r.i = ma_atomic_fetch_add_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13235. return r.f;
  13236. }
  13237. static MA_INLINE double ma_atomic_fetch_add_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13238. {
  13239. ma_atomic_if64 r;
  13240. ma_atomic_if64 x;
  13241. x.f = src;
  13242. r.i = ma_atomic_fetch_add_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13243. return r.f;
  13244. }
  13245. static MA_INLINE float ma_atomic_fetch_sub_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13246. {
  13247. ma_atomic_if32 r;
  13248. ma_atomic_if32 x;
  13249. x.f = src;
  13250. r.i = ma_atomic_fetch_sub_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13251. return r.f;
  13252. }
  13253. static MA_INLINE double ma_atomic_fetch_sub_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13254. {
  13255. ma_atomic_if64 r;
  13256. ma_atomic_if64 x;
  13257. x.f = src;
  13258. r.i = ma_atomic_fetch_sub_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13259. return r.f;
  13260. }
  13261. static MA_INLINE float ma_atomic_fetch_or_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13262. {
  13263. ma_atomic_if32 r;
  13264. ma_atomic_if32 x;
  13265. x.f = src;
  13266. r.i = ma_atomic_fetch_or_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13267. return r.f;
  13268. }
  13269. static MA_INLINE double ma_atomic_fetch_or_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13270. {
  13271. ma_atomic_if64 r;
  13272. ma_atomic_if64 x;
  13273. x.f = src;
  13274. r.i = ma_atomic_fetch_or_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13275. return r.f;
  13276. }
  13277. static MA_INLINE float ma_atomic_fetch_xor_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13278. {
  13279. ma_atomic_if32 r;
  13280. ma_atomic_if32 x;
  13281. x.f = src;
  13282. r.i = ma_atomic_fetch_xor_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13283. return r.f;
  13284. }
  13285. static MA_INLINE double ma_atomic_fetch_xor_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13286. {
  13287. ma_atomic_if64 r;
  13288. ma_atomic_if64 x;
  13289. x.f = src;
  13290. r.i = ma_atomic_fetch_xor_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13291. return r.f;
  13292. }
  13293. static MA_INLINE float ma_atomic_fetch_and_explicit_f32(volatile float* dst, float src, ma_atomic_memory_order order)
  13294. {
  13295. ma_atomic_if32 r;
  13296. ma_atomic_if32 x;
  13297. x.f = src;
  13298. r.i = ma_atomic_fetch_and_explicit_32((volatile ma_uint32*)dst, x.i, order);
  13299. return r.f;
  13300. }
  13301. static MA_INLINE double ma_atomic_fetch_and_explicit_f64(volatile double* dst, double src, ma_atomic_memory_order order)
  13302. {
  13303. ma_atomic_if64 r;
  13304. ma_atomic_if64 x;
  13305. x.f = src;
  13306. r.i = ma_atomic_fetch_and_explicit_64((volatile ma_uint64*)dst, x.i, order);
  13307. return r.f;
  13308. }
  13309. #define ma_atomic_clear_f32(ptr) (float )ma_atomic_clear_explicit_f32(ptr, ma_atomic_memory_order_seq_cst)
  13310. #define ma_atomic_clear_f64(ptr) (double)ma_atomic_clear_explicit_f64(ptr, ma_atomic_memory_order_seq_cst)
  13311. #define ma_atomic_store_f32(dst, src) ma_atomic_store_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13312. #define ma_atomic_store_f64(dst, src) ma_atomic_store_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13313. #define ma_atomic_load_f32(ptr) (float )ma_atomic_load_explicit_f32(ptr, ma_atomic_memory_order_seq_cst)
  13314. #define ma_atomic_load_f64(ptr) (double)ma_atomic_load_explicit_f64(ptr, ma_atomic_memory_order_seq_cst)
  13315. #define ma_atomic_exchange_f32(dst, src) (float )ma_atomic_exchange_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13316. #define ma_atomic_exchange_f64(dst, src) (double)ma_atomic_exchange_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13317. #define ma_atomic_compare_exchange_strong_f32(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_f32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13318. #define ma_atomic_compare_exchange_strong_f64(dst, expected, desired) ma_atomic_compare_exchange_strong_explicit_f64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13319. #define ma_atomic_compare_exchange_weak_f32(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_f32(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13320. #define ma_atomic_compare_exchange_weak_f64(dst, expected, desired) ma_atomic_compare_exchange_weak_explicit_f64(dst, expected, desired, ma_atomic_memory_order_seq_cst, ma_atomic_memory_order_seq_cst)
  13321. #define ma_atomic_fetch_add_f32(dst, src) ma_atomic_fetch_add_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13322. #define ma_atomic_fetch_add_f64(dst, src) ma_atomic_fetch_add_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13323. #define ma_atomic_fetch_sub_f32(dst, src) ma_atomic_fetch_sub_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13324. #define ma_atomic_fetch_sub_f64(dst, src) ma_atomic_fetch_sub_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13325. #define ma_atomic_fetch_or_f32(dst, src) ma_atomic_fetch_or_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13326. #define ma_atomic_fetch_or_f64(dst, src) ma_atomic_fetch_or_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13327. #define ma_atomic_fetch_xor_f32(dst, src) ma_atomic_fetch_xor_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13328. #define ma_atomic_fetch_xor_f64(dst, src) ma_atomic_fetch_xor_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13329. #define ma_atomic_fetch_and_f32(dst, src) ma_atomic_fetch_and_explicit_f32(dst, src, ma_atomic_memory_order_seq_cst)
  13330. #define ma_atomic_fetch_and_f64(dst, src) ma_atomic_fetch_and_explicit_f64(dst, src, ma_atomic_memory_order_seq_cst)
  13331. static MA_INLINE float ma_atomic_compare_and_swap_f32(volatile float* dst, float expected, float desired)
  13332. {
  13333. ma_atomic_if32 r;
  13334. ma_atomic_if32 e, d;
  13335. e.f = expected;
  13336. d.f = desired;
  13337. r.i = ma_atomic_compare_and_swap_32((volatile ma_uint32*)dst, e.i, d.i);
  13338. return r.f;
  13339. }
  13340. static MA_INLINE double ma_atomic_compare_and_swap_f64(volatile double* dst, double expected, double desired)
  13341. {
  13342. ma_atomic_if64 r;
  13343. ma_atomic_if64 e, d;
  13344. e.f = expected;
  13345. d.f = desired;
  13346. r.i = ma_atomic_compare_and_swap_64((volatile ma_uint64*)dst, e.i, d.i);
  13347. return r.f;
  13348. }
  13349. typedef ma_atomic_flag ma_atomic_spinlock;
  13350. static MA_INLINE void ma_atomic_spinlock_lock(volatile ma_atomic_spinlock* pSpinlock)
  13351. {
  13352. for (;;) {
  13353. if (ma_atomic_flag_test_and_set_explicit(pSpinlock, ma_atomic_memory_order_acquire) == 0) {
  13354. break;
  13355. }
  13356. while (c89atoimc_flag_load_explicit(pSpinlock, ma_atomic_memory_order_relaxed) == 1) {
  13357. }
  13358. }
  13359. }
  13360. static MA_INLINE void ma_atomic_spinlock_unlock(volatile ma_atomic_spinlock* pSpinlock)
  13361. {
  13362. ma_atomic_flag_clear_explicit(pSpinlock, ma_atomic_memory_order_release);
  13363. }
  13364. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  13365. #pragma GCC diagnostic pop
  13366. #endif
  13367. #if defined(__cplusplus)
  13368. }
  13369. #endif
  13370. #endif
  13371. /* ma_atomic.h end */
  13372. #define MA_ATOMIC_SAFE_TYPE_IMPL(c89TypeExtension, type) \
  13373. static MA_INLINE ma_##type ma_atomic_##type##_get(ma_atomic_##type* x) \
  13374. { \
  13375. return (ma_##type)ma_atomic_load_##c89TypeExtension(&x->value); \
  13376. } \
  13377. static MA_INLINE void ma_atomic_##type##_set(ma_atomic_##type* x, ma_##type value) \
  13378. { \
  13379. ma_atomic_store_##c89TypeExtension(&x->value, value); \
  13380. } \
  13381. static MA_INLINE ma_##type ma_atomic_##type##_exchange(ma_atomic_##type* x, ma_##type value) \
  13382. { \
  13383. return (ma_##type)ma_atomic_exchange_##c89TypeExtension(&x->value, value); \
  13384. } \
  13385. static MA_INLINE ma_bool32 ma_atomic_##type##_compare_exchange(ma_atomic_##type* x, ma_##type* expected, ma_##type desired) \
  13386. { \
  13387. return ma_atomic_compare_exchange_weak_##c89TypeExtension(&x->value, expected, desired); \
  13388. } \
  13389. static MA_INLINE ma_##type ma_atomic_##type##_fetch_add(ma_atomic_##type* x, ma_##type y) \
  13390. { \
  13391. return (ma_##type)ma_atomic_fetch_add_##c89TypeExtension(&x->value, y); \
  13392. } \
  13393. static MA_INLINE ma_##type ma_atomic_##type##_fetch_sub(ma_atomic_##type* x, ma_##type y) \
  13394. { \
  13395. return (ma_##type)ma_atomic_fetch_sub_##c89TypeExtension(&x->value, y); \
  13396. } \
  13397. static MA_INLINE ma_##type ma_atomic_##type##_fetch_or(ma_atomic_##type* x, ma_##type y) \
  13398. { \
  13399. return (ma_##type)ma_atomic_fetch_or_##c89TypeExtension(&x->value, y); \
  13400. } \
  13401. static MA_INLINE ma_##type ma_atomic_##type##_fetch_xor(ma_atomic_##type* x, ma_##type y) \
  13402. { \
  13403. return (ma_##type)ma_atomic_fetch_xor_##c89TypeExtension(&x->value, y); \
  13404. } \
  13405. static MA_INLINE ma_##type ma_atomic_##type##_fetch_and(ma_atomic_##type* x, ma_##type y) \
  13406. { \
  13407. return (ma_##type)ma_atomic_fetch_and_##c89TypeExtension(&x->value, y); \
  13408. } \
  13409. static MA_INLINE ma_##type ma_atomic_##type##_compare_and_swap(ma_atomic_##type* x, ma_##type expected, ma_##type desired) \
  13410. { \
  13411. return (ma_##type)ma_atomic_compare_and_swap_##c89TypeExtension(&x->value, expected, desired); \
  13412. } \
  13413. #define MA_ATOMIC_SAFE_TYPE_IMPL_PTR(type) \
  13414. static MA_INLINE ma_##type* ma_atomic_ptr_##type##_get(ma_atomic_ptr_##type* x) \
  13415. { \
  13416. return ma_atomic_load_ptr((void**)&x->value); \
  13417. } \
  13418. static MA_INLINE void ma_atomic_ptr_##type##_set(ma_atomic_ptr_##type* x, ma_##type* value) \
  13419. { \
  13420. ma_atomic_store_ptr((void**)&x->value, (void*)value); \
  13421. } \
  13422. static MA_INLINE ma_##type* ma_atomic_ptr_##type##_exchange(ma_atomic_ptr_##type* x, ma_##type* value) \
  13423. { \
  13424. return ma_atomic_exchange_ptr((void**)&x->value, (void*)value); \
  13425. } \
  13426. static MA_INLINE ma_bool32 ma_atomic_ptr_##type##_compare_exchange(ma_atomic_ptr_##type* x, ma_##type** expected, ma_##type* desired) \
  13427. { \
  13428. return ma_atomic_compare_exchange_weak_ptr((void**)&x->value, (void*)expected, (void*)desired); \
  13429. } \
  13430. static MA_INLINE ma_##type* ma_atomic_ptr_##type##_compare_and_swap(ma_atomic_ptr_##type* x, ma_##type* expected, ma_##type* desired) \
  13431. { \
  13432. return (ma_##type*)ma_atomic_compare_and_swap_ptr((void**)&x->value, (void*)expected, (void*)desired); \
  13433. } \
  13434. MA_ATOMIC_SAFE_TYPE_IMPL(32, uint32)
  13435. MA_ATOMIC_SAFE_TYPE_IMPL(i32, int32)
  13436. MA_ATOMIC_SAFE_TYPE_IMPL(64, uint64)
  13437. MA_ATOMIC_SAFE_TYPE_IMPL(f32, float)
  13438. MA_ATOMIC_SAFE_TYPE_IMPL(32, bool32)
  13439. #if !defined(MA_NO_DEVICE_IO)
  13440. MA_ATOMIC_SAFE_TYPE_IMPL(i32, device_state)
  13441. #endif
  13442. MA_API ma_uint64 ma_calculate_frame_count_after_resampling(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn)
  13443. {
  13444. /* This is based on the calculation in ma_linear_resampler_get_expected_output_frame_count(). */
  13445. ma_uint64 outputFrameCount;
  13446. ma_uint64 preliminaryInputFrameCountFromFrac;
  13447. ma_uint64 preliminaryInputFrameCount;
  13448. if (sampleRateIn == 0 || sampleRateOut == 0 || frameCountIn == 0) {
  13449. return 0;
  13450. }
  13451. if (sampleRateOut == sampleRateIn) {
  13452. return frameCountIn;
  13453. }
  13454. outputFrameCount = (frameCountIn * sampleRateOut) / sampleRateIn;
  13455. preliminaryInputFrameCountFromFrac = (outputFrameCount * (sampleRateIn / sampleRateOut)) / sampleRateOut;
  13456. preliminaryInputFrameCount = (outputFrameCount * (sampleRateIn % sampleRateOut)) + preliminaryInputFrameCountFromFrac;
  13457. if (preliminaryInputFrameCount <= frameCountIn) {
  13458. outputFrameCount += 1;
  13459. }
  13460. return outputFrameCount;
  13461. }
  13462. #ifndef MA_DATA_CONVERTER_STACK_BUFFER_SIZE
  13463. #define MA_DATA_CONVERTER_STACK_BUFFER_SIZE 4096
  13464. #endif
  13465. #if defined(MA_WIN32)
  13466. static ma_result ma_result_from_GetLastError(DWORD error)
  13467. {
  13468. switch (error)
  13469. {
  13470. case ERROR_SUCCESS: return MA_SUCCESS;
  13471. case ERROR_PATH_NOT_FOUND: return MA_DOES_NOT_EXIST;
  13472. case ERROR_TOO_MANY_OPEN_FILES: return MA_TOO_MANY_OPEN_FILES;
  13473. case ERROR_NOT_ENOUGH_MEMORY: return MA_OUT_OF_MEMORY;
  13474. case ERROR_DISK_FULL: return MA_NO_SPACE;
  13475. case ERROR_HANDLE_EOF: return MA_AT_END;
  13476. case ERROR_NEGATIVE_SEEK: return MA_BAD_SEEK;
  13477. case ERROR_INVALID_PARAMETER: return MA_INVALID_ARGS;
  13478. case ERROR_ACCESS_DENIED: return MA_ACCESS_DENIED;
  13479. case ERROR_SEM_TIMEOUT: return MA_TIMEOUT;
  13480. case ERROR_FILE_NOT_FOUND: return MA_DOES_NOT_EXIST;
  13481. default: break;
  13482. }
  13483. return MA_ERROR;
  13484. }
  13485. #endif /* MA_WIN32 */
  13486. /*******************************************************************************
  13487. Threading
  13488. *******************************************************************************/
  13489. static MA_INLINE ma_result ma_spinlock_lock_ex(volatile ma_spinlock* pSpinlock, ma_bool32 yield)
  13490. {
  13491. if (pSpinlock == NULL) {
  13492. return MA_INVALID_ARGS;
  13493. }
  13494. for (;;) {
  13495. if (ma_atomic_exchange_explicit_32(pSpinlock, 1, ma_atomic_memory_order_acquire) == 0) {
  13496. break;
  13497. }
  13498. while (ma_atomic_load_explicit_32(pSpinlock, ma_atomic_memory_order_relaxed) == 1) {
  13499. if (yield) {
  13500. ma_yield();
  13501. }
  13502. }
  13503. }
  13504. return MA_SUCCESS;
  13505. }
  13506. MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock)
  13507. {
  13508. return ma_spinlock_lock_ex(pSpinlock, MA_TRUE);
  13509. }
  13510. MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock)
  13511. {
  13512. return ma_spinlock_lock_ex(pSpinlock, MA_FALSE);
  13513. }
  13514. MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock)
  13515. {
  13516. if (pSpinlock == NULL) {
  13517. return MA_INVALID_ARGS;
  13518. }
  13519. ma_atomic_store_explicit_32(pSpinlock, 0, ma_atomic_memory_order_release);
  13520. return MA_SUCCESS;
  13521. }
  13522. #ifndef MA_NO_THREADING
  13523. #if defined(MA_POSIX)
  13524. #define MA_THREADCALL
  13525. typedef void* ma_thread_result;
  13526. #elif defined(MA_WIN32)
  13527. #define MA_THREADCALL WINAPI
  13528. typedef unsigned long ma_thread_result;
  13529. #endif
  13530. typedef ma_thread_result (MA_THREADCALL * ma_thread_entry_proc)(void* pData);
  13531. #ifdef MA_POSIX
  13532. static ma_result ma_thread_create__posix(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
  13533. {
  13534. int result;
  13535. pthread_attr_t* pAttr = NULL;
  13536. #if !defined(__EMSCRIPTEN__)
  13537. /* Try setting the thread priority. It's not critical if anything fails here. */
  13538. pthread_attr_t attr;
  13539. if (pthread_attr_init(&attr) == 0) {
  13540. int scheduler = -1;
  13541. /* We successfully initialized our attributes object so we can assign the pointer so it's passed into pthread_create(). */
  13542. pAttr = &attr;
  13543. /* We need to set the scheduler policy. Only do this if the OS supports pthread_attr_setschedpolicy() */
  13544. #if !defined(MA_BEOS)
  13545. {
  13546. if (priority == ma_thread_priority_idle) {
  13547. #ifdef SCHED_IDLE
  13548. if (pthread_attr_setschedpolicy(&attr, SCHED_IDLE) == 0) {
  13549. scheduler = SCHED_IDLE;
  13550. }
  13551. #endif
  13552. } else if (priority == ma_thread_priority_realtime) {
  13553. #ifdef SCHED_FIFO
  13554. if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0) {
  13555. scheduler = SCHED_FIFO;
  13556. }
  13557. #endif
  13558. #ifdef MA_LINUX
  13559. } else {
  13560. scheduler = sched_getscheduler(0);
  13561. #endif
  13562. }
  13563. }
  13564. #endif
  13565. if (stackSize > 0) {
  13566. pthread_attr_setstacksize(&attr, stackSize);
  13567. }
  13568. if (scheduler != -1) {
  13569. int priorityMin = sched_get_priority_min(scheduler);
  13570. int priorityMax = sched_get_priority_max(scheduler);
  13571. int priorityStep = (priorityMax - priorityMin) / 7; /* 7 = number of priorities supported by miniaudio. */
  13572. struct sched_param sched;
  13573. if (pthread_attr_getschedparam(&attr, &sched) == 0) {
  13574. if (priority == ma_thread_priority_idle) {
  13575. sched.sched_priority = priorityMin;
  13576. } else if (priority == ma_thread_priority_realtime) {
  13577. sched.sched_priority = priorityMax;
  13578. } else {
  13579. sched.sched_priority += ((int)priority + 5) * priorityStep; /* +5 because the lowest priority is -5. */
  13580. if (sched.sched_priority < priorityMin) {
  13581. sched.sched_priority = priorityMin;
  13582. }
  13583. if (sched.sched_priority > priorityMax) {
  13584. sched.sched_priority = priorityMax;
  13585. }
  13586. }
  13587. /* I'm not treating a failure of setting the priority as a critical error so not checking the return value here. */
  13588. pthread_attr_setschedparam(&attr, &sched);
  13589. }
  13590. }
  13591. }
  13592. #else
  13593. /* It's the emscripten build. We'll have a few unused parameters. */
  13594. (void)priority;
  13595. (void)stackSize;
  13596. #endif
  13597. result = pthread_create((pthread_t*)pThread, pAttr, entryProc, pData);
  13598. /* The thread attributes object is no longer required. */
  13599. if (pAttr != NULL) {
  13600. pthread_attr_destroy(pAttr);
  13601. }
  13602. if (result != 0) {
  13603. return ma_result_from_errno(result);
  13604. }
  13605. return MA_SUCCESS;
  13606. }
  13607. static void ma_thread_wait__posix(ma_thread* pThread)
  13608. {
  13609. pthread_join((pthread_t)*pThread, NULL);
  13610. }
  13611. static ma_result ma_mutex_init__posix(ma_mutex* pMutex)
  13612. {
  13613. int result;
  13614. if (pMutex == NULL) {
  13615. return MA_INVALID_ARGS;
  13616. }
  13617. MA_ZERO_OBJECT(pMutex);
  13618. result = pthread_mutex_init((pthread_mutex_t*)pMutex, NULL);
  13619. if (result != 0) {
  13620. return ma_result_from_errno(result);
  13621. }
  13622. return MA_SUCCESS;
  13623. }
  13624. static void ma_mutex_uninit__posix(ma_mutex* pMutex)
  13625. {
  13626. pthread_mutex_destroy((pthread_mutex_t*)pMutex);
  13627. }
  13628. static void ma_mutex_lock__posix(ma_mutex* pMutex)
  13629. {
  13630. pthread_mutex_lock((pthread_mutex_t*)pMutex);
  13631. }
  13632. static void ma_mutex_unlock__posix(ma_mutex* pMutex)
  13633. {
  13634. pthread_mutex_unlock((pthread_mutex_t*)pMutex);
  13635. }
  13636. static ma_result ma_event_init__posix(ma_event* pEvent)
  13637. {
  13638. int result;
  13639. result = pthread_mutex_init((pthread_mutex_t*)&pEvent->lock, NULL);
  13640. if (result != 0) {
  13641. return ma_result_from_errno(result);
  13642. }
  13643. result = pthread_cond_init((pthread_cond_t*)&pEvent->cond, NULL);
  13644. if (result != 0) {
  13645. pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock);
  13646. return ma_result_from_errno(result);
  13647. }
  13648. pEvent->value = 0;
  13649. return MA_SUCCESS;
  13650. }
  13651. static void ma_event_uninit__posix(ma_event* pEvent)
  13652. {
  13653. pthread_cond_destroy((pthread_cond_t*)&pEvent->cond);
  13654. pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock);
  13655. }
  13656. static ma_result ma_event_wait__posix(ma_event* pEvent)
  13657. {
  13658. pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock);
  13659. {
  13660. while (pEvent->value == 0) {
  13661. pthread_cond_wait((pthread_cond_t*)&pEvent->cond, (pthread_mutex_t*)&pEvent->lock);
  13662. }
  13663. pEvent->value = 0; /* Auto-reset. */
  13664. }
  13665. pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock);
  13666. return MA_SUCCESS;
  13667. }
  13668. static ma_result ma_event_signal__posix(ma_event* pEvent)
  13669. {
  13670. pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock);
  13671. {
  13672. pEvent->value = 1;
  13673. pthread_cond_signal((pthread_cond_t*)&pEvent->cond);
  13674. }
  13675. pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock);
  13676. return MA_SUCCESS;
  13677. }
  13678. static ma_result ma_semaphore_init__posix(int initialValue, ma_semaphore* pSemaphore)
  13679. {
  13680. int result;
  13681. if (pSemaphore == NULL) {
  13682. return MA_INVALID_ARGS;
  13683. }
  13684. pSemaphore->value = initialValue;
  13685. result = pthread_mutex_init((pthread_mutex_t*)&pSemaphore->lock, NULL);
  13686. if (result != 0) {
  13687. return ma_result_from_errno(result); /* Failed to create mutex. */
  13688. }
  13689. result = pthread_cond_init((pthread_cond_t*)&pSemaphore->cond, NULL);
  13690. if (result != 0) {
  13691. pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock);
  13692. return ma_result_from_errno(result); /* Failed to create condition variable. */
  13693. }
  13694. return MA_SUCCESS;
  13695. }
  13696. static void ma_semaphore_uninit__posix(ma_semaphore* pSemaphore)
  13697. {
  13698. if (pSemaphore == NULL) {
  13699. return;
  13700. }
  13701. pthread_cond_destroy((pthread_cond_t*)&pSemaphore->cond);
  13702. pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock);
  13703. }
  13704. static ma_result ma_semaphore_wait__posix(ma_semaphore* pSemaphore)
  13705. {
  13706. if (pSemaphore == NULL) {
  13707. return MA_INVALID_ARGS;
  13708. }
  13709. pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock);
  13710. {
  13711. /* We need to wait on a condition variable before escaping. We can't return from this function until the semaphore has been signaled. */
  13712. while (pSemaphore->value == 0) {
  13713. pthread_cond_wait((pthread_cond_t*)&pSemaphore->cond, (pthread_mutex_t*)&pSemaphore->lock);
  13714. }
  13715. pSemaphore->value -= 1;
  13716. }
  13717. pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock);
  13718. return MA_SUCCESS;
  13719. }
  13720. static ma_result ma_semaphore_release__posix(ma_semaphore* pSemaphore)
  13721. {
  13722. if (pSemaphore == NULL) {
  13723. return MA_INVALID_ARGS;
  13724. }
  13725. pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock);
  13726. {
  13727. pSemaphore->value += 1;
  13728. pthread_cond_signal((pthread_cond_t*)&pSemaphore->cond);
  13729. }
  13730. pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock);
  13731. return MA_SUCCESS;
  13732. }
  13733. #elif defined(MA_WIN32)
  13734. static int ma_thread_priority_to_win32(ma_thread_priority priority)
  13735. {
  13736. switch (priority) {
  13737. case ma_thread_priority_idle: return THREAD_PRIORITY_IDLE;
  13738. case ma_thread_priority_lowest: return THREAD_PRIORITY_LOWEST;
  13739. case ma_thread_priority_low: return THREAD_PRIORITY_BELOW_NORMAL;
  13740. case ma_thread_priority_normal: return THREAD_PRIORITY_NORMAL;
  13741. case ma_thread_priority_high: return THREAD_PRIORITY_ABOVE_NORMAL;
  13742. case ma_thread_priority_highest: return THREAD_PRIORITY_HIGHEST;
  13743. case ma_thread_priority_realtime: return THREAD_PRIORITY_TIME_CRITICAL;
  13744. default: return THREAD_PRIORITY_NORMAL;
  13745. }
  13746. }
  13747. static ma_result ma_thread_create__win32(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
  13748. {
  13749. DWORD threadID; /* Not used. Only used for passing into CreateThread() so it doesn't fail on Windows 98. */
  13750. *pThread = CreateThread(NULL, stackSize, entryProc, pData, 0, &threadID);
  13751. if (*pThread == NULL) {
  13752. return ma_result_from_GetLastError(GetLastError());
  13753. }
  13754. SetThreadPriority((HANDLE)*pThread, ma_thread_priority_to_win32(priority));
  13755. return MA_SUCCESS;
  13756. }
  13757. static void ma_thread_wait__win32(ma_thread* pThread)
  13758. {
  13759. WaitForSingleObject((HANDLE)*pThread, INFINITE);
  13760. CloseHandle((HANDLE)*pThread);
  13761. }
  13762. static ma_result ma_mutex_init__win32(ma_mutex* pMutex)
  13763. {
  13764. *pMutex = CreateEventA(NULL, FALSE, TRUE, NULL);
  13765. if (*pMutex == NULL) {
  13766. return ma_result_from_GetLastError(GetLastError());
  13767. }
  13768. return MA_SUCCESS;
  13769. }
  13770. static void ma_mutex_uninit__win32(ma_mutex* pMutex)
  13771. {
  13772. CloseHandle((HANDLE)*pMutex);
  13773. }
  13774. static void ma_mutex_lock__win32(ma_mutex* pMutex)
  13775. {
  13776. WaitForSingleObject((HANDLE)*pMutex, INFINITE);
  13777. }
  13778. static void ma_mutex_unlock__win32(ma_mutex* pMutex)
  13779. {
  13780. SetEvent((HANDLE)*pMutex);
  13781. }
  13782. static ma_result ma_event_init__win32(ma_event* pEvent)
  13783. {
  13784. *pEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
  13785. if (*pEvent == NULL) {
  13786. return ma_result_from_GetLastError(GetLastError());
  13787. }
  13788. return MA_SUCCESS;
  13789. }
  13790. static void ma_event_uninit__win32(ma_event* pEvent)
  13791. {
  13792. CloseHandle((HANDLE)*pEvent);
  13793. }
  13794. static ma_result ma_event_wait__win32(ma_event* pEvent)
  13795. {
  13796. DWORD result = WaitForSingleObject((HANDLE)*pEvent, INFINITE);
  13797. if (result == WAIT_OBJECT_0) {
  13798. return MA_SUCCESS;
  13799. }
  13800. if (result == WAIT_TIMEOUT) {
  13801. return MA_TIMEOUT;
  13802. }
  13803. return ma_result_from_GetLastError(GetLastError());
  13804. }
  13805. static ma_result ma_event_signal__win32(ma_event* pEvent)
  13806. {
  13807. BOOL result = SetEvent((HANDLE)*pEvent);
  13808. if (result == 0) {
  13809. return ma_result_from_GetLastError(GetLastError());
  13810. }
  13811. return MA_SUCCESS;
  13812. }
  13813. static ma_result ma_semaphore_init__win32(int initialValue, ma_semaphore* pSemaphore)
  13814. {
  13815. *pSemaphore = CreateSemaphoreW(NULL, (LONG)initialValue, LONG_MAX, NULL);
  13816. if (*pSemaphore == NULL) {
  13817. return ma_result_from_GetLastError(GetLastError());
  13818. }
  13819. return MA_SUCCESS;
  13820. }
  13821. static void ma_semaphore_uninit__win32(ma_semaphore* pSemaphore)
  13822. {
  13823. CloseHandle((HANDLE)*pSemaphore);
  13824. }
  13825. static ma_result ma_semaphore_wait__win32(ma_semaphore* pSemaphore)
  13826. {
  13827. DWORD result = WaitForSingleObject((HANDLE)*pSemaphore, INFINITE);
  13828. if (result == WAIT_OBJECT_0) {
  13829. return MA_SUCCESS;
  13830. }
  13831. if (result == WAIT_TIMEOUT) {
  13832. return MA_TIMEOUT;
  13833. }
  13834. return ma_result_from_GetLastError(GetLastError());
  13835. }
  13836. static ma_result ma_semaphore_release__win32(ma_semaphore* pSemaphore)
  13837. {
  13838. BOOL result = ReleaseSemaphore((HANDLE)*pSemaphore, 1, NULL);
  13839. if (result == 0) {
  13840. return ma_result_from_GetLastError(GetLastError());
  13841. }
  13842. return MA_SUCCESS;
  13843. }
  13844. #endif
  13845. typedef struct
  13846. {
  13847. ma_thread_entry_proc entryProc;
  13848. void* pData;
  13849. ma_allocation_callbacks allocationCallbacks;
  13850. } ma_thread_proxy_data;
  13851. static ma_thread_result MA_THREADCALL ma_thread_entry_proxy(void* pData)
  13852. {
  13853. ma_thread_proxy_data* pProxyData = (ma_thread_proxy_data*)pData;
  13854. ma_thread_entry_proc entryProc;
  13855. void* pEntryProcData;
  13856. ma_thread_result result;
  13857. #if defined(MA_ON_THREAD_ENTRY)
  13858. MA_ON_THREAD_ENTRY
  13859. #endif
  13860. entryProc = pProxyData->entryProc;
  13861. pEntryProcData = pProxyData->pData;
  13862. /* Free the proxy data before getting into the real thread entry proc. */
  13863. ma_free(pProxyData, &pProxyData->allocationCallbacks);
  13864. result = entryProc(pEntryProcData);
  13865. #if defined(MA_ON_THREAD_EXIT)
  13866. MA_ON_THREAD_EXIT
  13867. #endif
  13868. return result;
  13869. }
  13870. 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)
  13871. {
  13872. ma_result result;
  13873. ma_thread_proxy_data* pProxyData;
  13874. if (pThread == NULL || entryProc == NULL) {
  13875. return MA_INVALID_ARGS;
  13876. }
  13877. pProxyData = (ma_thread_proxy_data*)ma_malloc(sizeof(*pProxyData), pAllocationCallbacks); /* Will be freed by the proxy entry proc. */
  13878. if (pProxyData == NULL) {
  13879. return MA_OUT_OF_MEMORY;
  13880. }
  13881. #if defined(MA_THREAD_DEFAULT_STACK_SIZE)
  13882. if (stackSize == 0) {
  13883. stackSize = MA_THREAD_DEFAULT_STACK_SIZE;
  13884. }
  13885. #endif
  13886. pProxyData->entryProc = entryProc;
  13887. pProxyData->pData = pData;
  13888. ma_allocation_callbacks_init_copy(&pProxyData->allocationCallbacks, pAllocationCallbacks);
  13889. #if defined(MA_POSIX)
  13890. result = ma_thread_create__posix(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData);
  13891. #elif defined(MA_WIN32)
  13892. result = ma_thread_create__win32(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData);
  13893. #endif
  13894. if (result != MA_SUCCESS) {
  13895. ma_free(pProxyData, pAllocationCallbacks);
  13896. return result;
  13897. }
  13898. return MA_SUCCESS;
  13899. }
  13900. static void ma_thread_wait(ma_thread* pThread)
  13901. {
  13902. if (pThread == NULL) {
  13903. return;
  13904. }
  13905. #if defined(MA_POSIX)
  13906. ma_thread_wait__posix(pThread);
  13907. #elif defined(MA_WIN32)
  13908. ma_thread_wait__win32(pThread);
  13909. #endif
  13910. }
  13911. MA_API ma_result ma_mutex_init(ma_mutex* pMutex)
  13912. {
  13913. if (pMutex == NULL) {
  13914. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13915. return MA_INVALID_ARGS;
  13916. }
  13917. #if defined(MA_POSIX)
  13918. return ma_mutex_init__posix(pMutex);
  13919. #elif defined(MA_WIN32)
  13920. return ma_mutex_init__win32(pMutex);
  13921. #endif
  13922. }
  13923. MA_API void ma_mutex_uninit(ma_mutex* pMutex)
  13924. {
  13925. if (pMutex == NULL) {
  13926. return;
  13927. }
  13928. #if defined(MA_POSIX)
  13929. ma_mutex_uninit__posix(pMutex);
  13930. #elif defined(MA_WIN32)
  13931. ma_mutex_uninit__win32(pMutex);
  13932. #endif
  13933. }
  13934. MA_API void ma_mutex_lock(ma_mutex* pMutex)
  13935. {
  13936. if (pMutex == NULL) {
  13937. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13938. return;
  13939. }
  13940. #if defined(MA_POSIX)
  13941. ma_mutex_lock__posix(pMutex);
  13942. #elif defined(MA_WIN32)
  13943. ma_mutex_lock__win32(pMutex);
  13944. #endif
  13945. }
  13946. MA_API void ma_mutex_unlock(ma_mutex* pMutex)
  13947. {
  13948. if (pMutex == NULL) {
  13949. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13950. return;
  13951. }
  13952. #if defined(MA_POSIX)
  13953. ma_mutex_unlock__posix(pMutex);
  13954. #elif defined(MA_WIN32)
  13955. ma_mutex_unlock__win32(pMutex);
  13956. #endif
  13957. }
  13958. MA_API ma_result ma_event_init(ma_event* pEvent)
  13959. {
  13960. if (pEvent == NULL) {
  13961. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13962. return MA_INVALID_ARGS;
  13963. }
  13964. #if defined(MA_POSIX)
  13965. return ma_event_init__posix(pEvent);
  13966. #elif defined(MA_WIN32)
  13967. return ma_event_init__win32(pEvent);
  13968. #endif
  13969. }
  13970. #if 0
  13971. static ma_result ma_event_alloc_and_init(ma_event** ppEvent, ma_allocation_callbacks* pAllocationCallbacks)
  13972. {
  13973. ma_result result;
  13974. ma_event* pEvent;
  13975. if (ppEvent == NULL) {
  13976. return MA_INVALID_ARGS;
  13977. }
  13978. *ppEvent = NULL;
  13979. pEvent = ma_malloc(sizeof(*pEvent), pAllocationCallbacks);
  13980. if (pEvent == NULL) {
  13981. return MA_OUT_OF_MEMORY;
  13982. }
  13983. result = ma_event_init(pEvent);
  13984. if (result != MA_SUCCESS) {
  13985. ma_free(pEvent, pAllocationCallbacks);
  13986. return result;
  13987. }
  13988. *ppEvent = pEvent;
  13989. return result;
  13990. }
  13991. #endif
  13992. MA_API void ma_event_uninit(ma_event* pEvent)
  13993. {
  13994. if (pEvent == NULL) {
  13995. return;
  13996. }
  13997. #if defined(MA_POSIX)
  13998. ma_event_uninit__posix(pEvent);
  13999. #elif defined(MA_WIN32)
  14000. ma_event_uninit__win32(pEvent);
  14001. #endif
  14002. }
  14003. #if 0
  14004. static void ma_event_uninit_and_free(ma_event* pEvent, ma_allocation_callbacks* pAllocationCallbacks)
  14005. {
  14006. if (pEvent == NULL) {
  14007. return;
  14008. }
  14009. ma_event_uninit(pEvent);
  14010. ma_free(pEvent, pAllocationCallbacks);
  14011. }
  14012. #endif
  14013. MA_API ma_result ma_event_wait(ma_event* pEvent)
  14014. {
  14015. if (pEvent == NULL) {
  14016. MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
  14017. return MA_INVALID_ARGS;
  14018. }
  14019. #if defined(MA_POSIX)
  14020. return ma_event_wait__posix(pEvent);
  14021. #elif defined(MA_WIN32)
  14022. return ma_event_wait__win32(pEvent);
  14023. #endif
  14024. }
  14025. MA_API ma_result ma_event_signal(ma_event* pEvent)
  14026. {
  14027. if (pEvent == NULL) {
  14028. MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
  14029. return MA_INVALID_ARGS;
  14030. }
  14031. #if defined(MA_POSIX)
  14032. return ma_event_signal__posix(pEvent);
  14033. #elif defined(MA_WIN32)
  14034. return ma_event_signal__win32(pEvent);
  14035. #endif
  14036. }
  14037. MA_API ma_result ma_semaphore_init(int initialValue, ma_semaphore* pSemaphore)
  14038. {
  14039. if (pSemaphore == NULL) {
  14040. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14041. return MA_INVALID_ARGS;
  14042. }
  14043. #if defined(MA_POSIX)
  14044. return ma_semaphore_init__posix(initialValue, pSemaphore);
  14045. #elif defined(MA_WIN32)
  14046. return ma_semaphore_init__win32(initialValue, pSemaphore);
  14047. #endif
  14048. }
  14049. MA_API void ma_semaphore_uninit(ma_semaphore* pSemaphore)
  14050. {
  14051. if (pSemaphore == NULL) {
  14052. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14053. return;
  14054. }
  14055. #if defined(MA_POSIX)
  14056. ma_semaphore_uninit__posix(pSemaphore);
  14057. #elif defined(MA_WIN32)
  14058. ma_semaphore_uninit__win32(pSemaphore);
  14059. #endif
  14060. }
  14061. MA_API ma_result ma_semaphore_wait(ma_semaphore* pSemaphore)
  14062. {
  14063. if (pSemaphore == NULL) {
  14064. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14065. return MA_INVALID_ARGS;
  14066. }
  14067. #if defined(MA_POSIX)
  14068. return ma_semaphore_wait__posix(pSemaphore);
  14069. #elif defined(MA_WIN32)
  14070. return ma_semaphore_wait__win32(pSemaphore);
  14071. #endif
  14072. }
  14073. MA_API ma_result ma_semaphore_release(ma_semaphore* pSemaphore)
  14074. {
  14075. if (pSemaphore == NULL) {
  14076. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  14077. return MA_INVALID_ARGS;
  14078. }
  14079. #if defined(MA_POSIX)
  14080. return ma_semaphore_release__posix(pSemaphore);
  14081. #elif defined(MA_WIN32)
  14082. return ma_semaphore_release__win32(pSemaphore);
  14083. #endif
  14084. }
  14085. #else
  14086. /* 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. */
  14087. #ifndef MA_NO_DEVICE_IO
  14088. #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
  14089. #endif
  14090. #endif /* MA_NO_THREADING */
  14091. #define MA_FENCE_COUNTER_MAX 0x7FFFFFFF
  14092. MA_API ma_result ma_fence_init(ma_fence* pFence)
  14093. {
  14094. if (pFence == NULL) {
  14095. return MA_INVALID_ARGS;
  14096. }
  14097. MA_ZERO_OBJECT(pFence);
  14098. pFence->counter = 0;
  14099. #ifndef MA_NO_THREADING
  14100. {
  14101. ma_result result;
  14102. result = ma_event_init(&pFence->e);
  14103. if (result != MA_SUCCESS) {
  14104. return result;
  14105. }
  14106. }
  14107. #endif
  14108. return MA_SUCCESS;
  14109. }
  14110. MA_API void ma_fence_uninit(ma_fence* pFence)
  14111. {
  14112. if (pFence == NULL) {
  14113. return;
  14114. }
  14115. #ifndef MA_NO_THREADING
  14116. {
  14117. ma_event_uninit(&pFence->e);
  14118. }
  14119. #endif
  14120. MA_ZERO_OBJECT(pFence);
  14121. }
  14122. MA_API ma_result ma_fence_acquire(ma_fence* pFence)
  14123. {
  14124. if (pFence == NULL) {
  14125. return MA_INVALID_ARGS;
  14126. }
  14127. for (;;) {
  14128. ma_uint32 oldCounter = ma_atomic_load_32(&pFence->counter);
  14129. ma_uint32 newCounter = oldCounter + 1;
  14130. /* Make sure we're not about to exceed our maximum value. */
  14131. if (newCounter > MA_FENCE_COUNTER_MAX) {
  14132. MA_ASSERT(MA_FALSE);
  14133. return MA_OUT_OF_RANGE;
  14134. }
  14135. if (ma_atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) {
  14136. return MA_SUCCESS;
  14137. } else {
  14138. if (oldCounter == MA_FENCE_COUNTER_MAX) {
  14139. MA_ASSERT(MA_FALSE);
  14140. return MA_OUT_OF_RANGE; /* The other thread took the last available slot. Abort. */
  14141. }
  14142. }
  14143. }
  14144. /* Should never get here. */
  14145. /*return MA_SUCCESS;*/
  14146. }
  14147. MA_API ma_result ma_fence_release(ma_fence* pFence)
  14148. {
  14149. if (pFence == NULL) {
  14150. return MA_INVALID_ARGS;
  14151. }
  14152. for (;;) {
  14153. ma_uint32 oldCounter = ma_atomic_load_32(&pFence->counter);
  14154. ma_uint32 newCounter = oldCounter - 1;
  14155. if (oldCounter == 0) {
  14156. MA_ASSERT(MA_FALSE);
  14157. return MA_INVALID_OPERATION; /* Acquire/release mismatch. */
  14158. }
  14159. if (ma_atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) {
  14160. #ifndef MA_NO_THREADING
  14161. {
  14162. if (newCounter == 0) {
  14163. ma_event_signal(&pFence->e); /* <-- ma_fence_wait() will be waiting on this. */
  14164. }
  14165. }
  14166. #endif
  14167. return MA_SUCCESS;
  14168. } else {
  14169. if (oldCounter == 0) {
  14170. MA_ASSERT(MA_FALSE);
  14171. return MA_INVALID_OPERATION; /* Another thread has taken the 0 slot. Acquire/release mismatch. */
  14172. }
  14173. }
  14174. }
  14175. /* Should never get here. */
  14176. /*return MA_SUCCESS;*/
  14177. }
  14178. MA_API ma_result ma_fence_wait(ma_fence* pFence)
  14179. {
  14180. if (pFence == NULL) {
  14181. return MA_INVALID_ARGS;
  14182. }
  14183. for (;;) {
  14184. ma_uint32 counter;
  14185. counter = ma_atomic_load_32(&pFence->counter);
  14186. if (counter == 0) {
  14187. /*
  14188. Counter has hit zero. By the time we get here some other thread may have acquired the
  14189. fence again, but that is where the caller needs to take care with how they se the fence.
  14190. */
  14191. return MA_SUCCESS;
  14192. }
  14193. /* Getting here means the counter is > 0. We'll need to wait for something to happen. */
  14194. #ifndef MA_NO_THREADING
  14195. {
  14196. ma_result result;
  14197. result = ma_event_wait(&pFence->e);
  14198. if (result != MA_SUCCESS) {
  14199. return result;
  14200. }
  14201. }
  14202. #endif
  14203. }
  14204. /* Should never get here. */
  14205. /*return MA_INVALID_OPERATION;*/
  14206. }
  14207. MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification)
  14208. {
  14209. ma_async_notification_callbacks* pNotificationCallbacks = (ma_async_notification_callbacks*)pNotification;
  14210. if (pNotification == NULL) {
  14211. return MA_INVALID_ARGS;
  14212. }
  14213. if (pNotificationCallbacks->onSignal == NULL) {
  14214. return MA_NOT_IMPLEMENTED;
  14215. }
  14216. pNotificationCallbacks->onSignal(pNotification);
  14217. return MA_INVALID_ARGS;
  14218. }
  14219. static void ma_async_notification_poll__on_signal(ma_async_notification* pNotification)
  14220. {
  14221. ((ma_async_notification_poll*)pNotification)->signalled = MA_TRUE;
  14222. }
  14223. MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll)
  14224. {
  14225. if (pNotificationPoll == NULL) {
  14226. return MA_INVALID_ARGS;
  14227. }
  14228. pNotificationPoll->cb.onSignal = ma_async_notification_poll__on_signal;
  14229. pNotificationPoll->signalled = MA_FALSE;
  14230. return MA_SUCCESS;
  14231. }
  14232. MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll)
  14233. {
  14234. if (pNotificationPoll == NULL) {
  14235. return MA_FALSE;
  14236. }
  14237. return pNotificationPoll->signalled;
  14238. }
  14239. static void ma_async_notification_event__on_signal(ma_async_notification* pNotification)
  14240. {
  14241. ma_async_notification_event_signal((ma_async_notification_event*)pNotification);
  14242. }
  14243. MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent)
  14244. {
  14245. if (pNotificationEvent == NULL) {
  14246. return MA_INVALID_ARGS;
  14247. }
  14248. pNotificationEvent->cb.onSignal = ma_async_notification_event__on_signal;
  14249. #ifndef MA_NO_THREADING
  14250. {
  14251. ma_result result;
  14252. result = ma_event_init(&pNotificationEvent->e);
  14253. if (result != MA_SUCCESS) {
  14254. return result;
  14255. }
  14256. return MA_SUCCESS;
  14257. }
  14258. #else
  14259. {
  14260. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14261. }
  14262. #endif
  14263. }
  14264. MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent)
  14265. {
  14266. if (pNotificationEvent == NULL) {
  14267. return MA_INVALID_ARGS;
  14268. }
  14269. #ifndef MA_NO_THREADING
  14270. {
  14271. ma_event_uninit(&pNotificationEvent->e);
  14272. return MA_SUCCESS;
  14273. }
  14274. #else
  14275. {
  14276. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14277. }
  14278. #endif
  14279. }
  14280. MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent)
  14281. {
  14282. if (pNotificationEvent == NULL) {
  14283. return MA_INVALID_ARGS;
  14284. }
  14285. #ifndef MA_NO_THREADING
  14286. {
  14287. return ma_event_wait(&pNotificationEvent->e);
  14288. }
  14289. #else
  14290. {
  14291. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14292. }
  14293. #endif
  14294. }
  14295. MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent)
  14296. {
  14297. if (pNotificationEvent == NULL) {
  14298. return MA_INVALID_ARGS;
  14299. }
  14300. #ifndef MA_NO_THREADING
  14301. {
  14302. return ma_event_signal(&pNotificationEvent->e);
  14303. }
  14304. #else
  14305. {
  14306. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  14307. }
  14308. #endif
  14309. }
  14310. /************************************************************************************************************************************************************
  14311. Job Queue
  14312. ************************************************************************************************************************************************************/
  14313. MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity)
  14314. {
  14315. ma_slot_allocator_config config;
  14316. MA_ZERO_OBJECT(&config);
  14317. config.capacity = capacity;
  14318. return config;
  14319. }
  14320. static MA_INLINE ma_uint32 ma_slot_allocator_calculate_group_capacity(ma_uint32 slotCapacity)
  14321. {
  14322. ma_uint32 cap = slotCapacity / 32;
  14323. if ((slotCapacity % 32) != 0) {
  14324. cap += 1;
  14325. }
  14326. return cap;
  14327. }
  14328. static MA_INLINE ma_uint32 ma_slot_allocator_group_capacity(const ma_slot_allocator* pAllocator)
  14329. {
  14330. return ma_slot_allocator_calculate_group_capacity(pAllocator->capacity);
  14331. }
  14332. typedef struct
  14333. {
  14334. size_t sizeInBytes;
  14335. size_t groupsOffset;
  14336. size_t slotsOffset;
  14337. } ma_slot_allocator_heap_layout;
  14338. static ma_result ma_slot_allocator_get_heap_layout(const ma_slot_allocator_config* pConfig, ma_slot_allocator_heap_layout* pHeapLayout)
  14339. {
  14340. MA_ASSERT(pHeapLayout != NULL);
  14341. MA_ZERO_OBJECT(pHeapLayout);
  14342. if (pConfig == NULL) {
  14343. return MA_INVALID_ARGS;
  14344. }
  14345. if (pConfig->capacity == 0) {
  14346. return MA_INVALID_ARGS;
  14347. }
  14348. pHeapLayout->sizeInBytes = 0;
  14349. /* Groups. */
  14350. pHeapLayout->groupsOffset = pHeapLayout->sizeInBytes;
  14351. pHeapLayout->sizeInBytes += ma_align_64(ma_slot_allocator_calculate_group_capacity(pConfig->capacity) * sizeof(ma_slot_allocator_group));
  14352. /* Slots. */
  14353. pHeapLayout->slotsOffset = pHeapLayout->sizeInBytes;
  14354. pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_uint32));
  14355. return MA_SUCCESS;
  14356. }
  14357. MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes)
  14358. {
  14359. ma_result result;
  14360. ma_slot_allocator_heap_layout layout;
  14361. if (pHeapSizeInBytes == NULL) {
  14362. return MA_INVALID_ARGS;
  14363. }
  14364. *pHeapSizeInBytes = 0;
  14365. result = ma_slot_allocator_get_heap_layout(pConfig, &layout);
  14366. if (result != MA_SUCCESS) {
  14367. return result;
  14368. }
  14369. *pHeapSizeInBytes = layout.sizeInBytes;
  14370. return result;
  14371. }
  14372. MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator)
  14373. {
  14374. ma_result result;
  14375. ma_slot_allocator_heap_layout heapLayout;
  14376. if (pAllocator == NULL) {
  14377. return MA_INVALID_ARGS;
  14378. }
  14379. MA_ZERO_OBJECT(pAllocator);
  14380. if (pHeap == NULL) {
  14381. return MA_INVALID_ARGS;
  14382. }
  14383. result = ma_slot_allocator_get_heap_layout(pConfig, &heapLayout);
  14384. if (result != MA_SUCCESS) {
  14385. return result;
  14386. }
  14387. pAllocator->_pHeap = pHeap;
  14388. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  14389. pAllocator->pGroups = (ma_slot_allocator_group*)ma_offset_ptr(pHeap, heapLayout.groupsOffset);
  14390. pAllocator->pSlots = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.slotsOffset);
  14391. pAllocator->capacity = pConfig->capacity;
  14392. return MA_SUCCESS;
  14393. }
  14394. MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator)
  14395. {
  14396. ma_result result;
  14397. size_t heapSizeInBytes;
  14398. void* pHeap;
  14399. result = ma_slot_allocator_get_heap_size(pConfig, &heapSizeInBytes);
  14400. if (result != MA_SUCCESS) {
  14401. return result; /* Failed to retrieve the size of the heap allocation. */
  14402. }
  14403. if (heapSizeInBytes > 0) {
  14404. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  14405. if (pHeap == NULL) {
  14406. return MA_OUT_OF_MEMORY;
  14407. }
  14408. } else {
  14409. pHeap = NULL;
  14410. }
  14411. result = ma_slot_allocator_init_preallocated(pConfig, pHeap, pAllocator);
  14412. if (result != MA_SUCCESS) {
  14413. ma_free(pHeap, pAllocationCallbacks);
  14414. return result;
  14415. }
  14416. pAllocator->_ownsHeap = MA_TRUE;
  14417. return MA_SUCCESS;
  14418. }
  14419. MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks)
  14420. {
  14421. if (pAllocator == NULL) {
  14422. return;
  14423. }
  14424. if (pAllocator->_ownsHeap) {
  14425. ma_free(pAllocator->_pHeap, pAllocationCallbacks);
  14426. }
  14427. }
  14428. MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot)
  14429. {
  14430. ma_uint32 iAttempt;
  14431. const ma_uint32 maxAttempts = 2; /* The number of iterations to perform until returning MA_OUT_OF_MEMORY if no slots can be found. */
  14432. if (pAllocator == NULL || pSlot == NULL) {
  14433. return MA_INVALID_ARGS;
  14434. }
  14435. for (iAttempt = 0; iAttempt < maxAttempts; iAttempt += 1) {
  14436. /* We need to acquire a suitable bitfield first. This is a bitfield that's got an available slot within it. */
  14437. ma_uint32 iGroup;
  14438. for (iGroup = 0; iGroup < ma_slot_allocator_group_capacity(pAllocator); iGroup += 1) {
  14439. /* CAS */
  14440. for (;;) {
  14441. ma_uint32 oldBitfield;
  14442. ma_uint32 newBitfield;
  14443. ma_uint32 bitOffset;
  14444. oldBitfield = ma_atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */
  14445. /* Fast check to see if anything is available. */
  14446. if (oldBitfield == 0xFFFFFFFF) {
  14447. break; /* No available bits in this bitfield. */
  14448. }
  14449. bitOffset = ma_ffs_32(~oldBitfield);
  14450. MA_ASSERT(bitOffset < 32);
  14451. newBitfield = oldBitfield | (1 << bitOffset);
  14452. if (ma_atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) {
  14453. ma_uint32 slotIndex;
  14454. /* Increment the counter as soon as possible to have other threads report out-of-memory sooner than later. */
  14455. ma_atomic_fetch_add_32(&pAllocator->count, 1);
  14456. /* The slot index is required for constructing the output value. */
  14457. slotIndex = (iGroup << 5) + bitOffset; /* iGroup << 5 = iGroup * 32 */
  14458. if (slotIndex >= pAllocator->capacity) {
  14459. return MA_OUT_OF_MEMORY;
  14460. }
  14461. /* Increment the reference count before constructing the output value. */
  14462. pAllocator->pSlots[slotIndex] += 1;
  14463. /* Construct the output value. */
  14464. *pSlot = (((ma_uint64)pAllocator->pSlots[slotIndex] << 32) | slotIndex);
  14465. return MA_SUCCESS;
  14466. }
  14467. }
  14468. }
  14469. /* 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. */
  14470. if (pAllocator->count < pAllocator->capacity) {
  14471. ma_yield();
  14472. } else {
  14473. return MA_OUT_OF_MEMORY;
  14474. }
  14475. }
  14476. /* We couldn't find a slot within the maximum number of attempts. */
  14477. return MA_OUT_OF_MEMORY;
  14478. }
  14479. MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot)
  14480. {
  14481. ma_uint32 iGroup;
  14482. ma_uint32 iBit;
  14483. if (pAllocator == NULL) {
  14484. return MA_INVALID_ARGS;
  14485. }
  14486. iGroup = (ma_uint32)((slot & 0xFFFFFFFF) >> 5); /* slot / 32 */
  14487. iBit = (ma_uint32)((slot & 0xFFFFFFFF) & 31); /* slot % 32 */
  14488. if (iGroup >= ma_slot_allocator_group_capacity(pAllocator)) {
  14489. return MA_INVALID_ARGS;
  14490. }
  14491. MA_ASSERT(iBit < 32); /* This must be true due to the logic we used to actually calculate it. */
  14492. while (ma_atomic_load_32(&pAllocator->count) > 0) {
  14493. /* CAS */
  14494. ma_uint32 oldBitfield;
  14495. ma_uint32 newBitfield;
  14496. oldBitfield = ma_atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */
  14497. newBitfield = oldBitfield & ~(1 << iBit);
  14498. /* Debugging for checking for double-frees. */
  14499. #if defined(MA_DEBUG_OUTPUT)
  14500. {
  14501. if ((oldBitfield & (1 << iBit)) == 0) {
  14502. MA_ASSERT(MA_FALSE); /* Double free detected.*/
  14503. }
  14504. }
  14505. #endif
  14506. if (ma_atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) {
  14507. ma_atomic_fetch_sub_32(&pAllocator->count, 1);
  14508. return MA_SUCCESS;
  14509. }
  14510. }
  14511. /* Getting here means there are no allocations available for freeing. */
  14512. return MA_INVALID_OPERATION;
  14513. }
  14514. #define MA_JOB_ID_NONE ~((ma_uint64)0)
  14515. #define MA_JOB_SLOT_NONE (ma_uint16)(~0)
  14516. static MA_INLINE ma_uint32 ma_job_extract_refcount(ma_uint64 toc)
  14517. {
  14518. return (ma_uint32)(toc >> 32);
  14519. }
  14520. static MA_INLINE ma_uint16 ma_job_extract_slot(ma_uint64 toc)
  14521. {
  14522. return (ma_uint16)(toc & 0x0000FFFF);
  14523. }
  14524. static MA_INLINE ma_uint16 ma_job_extract_code(ma_uint64 toc)
  14525. {
  14526. return (ma_uint16)((toc & 0xFFFF0000) >> 16);
  14527. }
  14528. static MA_INLINE ma_uint64 ma_job_toc_to_allocation(ma_uint64 toc)
  14529. {
  14530. return ((ma_uint64)ma_job_extract_refcount(toc) << 32) | (ma_uint64)ma_job_extract_slot(toc);
  14531. }
  14532. static MA_INLINE ma_uint64 ma_job_set_refcount(ma_uint64 toc, ma_uint32 refcount)
  14533. {
  14534. /* Clear the reference count first. */
  14535. toc = toc & ~((ma_uint64)0xFFFFFFFF << 32);
  14536. toc = toc | ((ma_uint64)refcount << 32);
  14537. return toc;
  14538. }
  14539. MA_API ma_job ma_job_init(ma_uint16 code)
  14540. {
  14541. ma_job job;
  14542. MA_ZERO_OBJECT(&job);
  14543. job.toc.breakup.code = code;
  14544. job.toc.breakup.slot = MA_JOB_SLOT_NONE; /* Temp value. Will be allocated when posted to a queue. */
  14545. job.next = MA_JOB_ID_NONE;
  14546. return job;
  14547. }
  14548. static ma_result ma_job_process__noop(ma_job* pJob);
  14549. static ma_result ma_job_process__quit(ma_job* pJob);
  14550. static ma_result ma_job_process__custom(ma_job* pJob);
  14551. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob);
  14552. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob);
  14553. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob);
  14554. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob);
  14555. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob);
  14556. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob);
  14557. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob);
  14558. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob);
  14559. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob);
  14560. #if !defined(MA_NO_DEVICE_IO)
  14561. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob);
  14562. #endif
  14563. static ma_job_proc g_jobVTable[MA_JOB_TYPE_COUNT] =
  14564. {
  14565. /* Miscellaneous. */
  14566. ma_job_process__quit, /* MA_JOB_TYPE_QUIT */
  14567. ma_job_process__custom, /* MA_JOB_TYPE_CUSTOM */
  14568. /* Resource Manager. */
  14569. ma_job_process__resource_manager__load_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE */
  14570. ma_job_process__resource_manager__free_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE */
  14571. ma_job_process__resource_manager__page_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE */
  14572. ma_job_process__resource_manager__load_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER */
  14573. ma_job_process__resource_manager__free_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER */
  14574. ma_job_process__resource_manager__load_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM */
  14575. ma_job_process__resource_manager__free_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM */
  14576. ma_job_process__resource_manager__page_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM */
  14577. ma_job_process__resource_manager__seek_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM */
  14578. /* Device. */
  14579. #if !defined(MA_NO_DEVICE_IO)
  14580. ma_job_process__device__aaudio_reroute /*MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE*/
  14581. #endif
  14582. };
  14583. MA_API ma_result ma_job_process(ma_job* pJob)
  14584. {
  14585. if (pJob == NULL) {
  14586. return MA_INVALID_ARGS;
  14587. }
  14588. if (pJob->toc.breakup.code >= MA_JOB_TYPE_COUNT) {
  14589. return MA_INVALID_OPERATION;
  14590. }
  14591. return g_jobVTable[pJob->toc.breakup.code](pJob);
  14592. }
  14593. static ma_result ma_job_process__noop(ma_job* pJob)
  14594. {
  14595. MA_ASSERT(pJob != NULL);
  14596. /* No-op. */
  14597. (void)pJob;
  14598. return MA_SUCCESS;
  14599. }
  14600. static ma_result ma_job_process__quit(ma_job* pJob)
  14601. {
  14602. return ma_job_process__noop(pJob);
  14603. }
  14604. static ma_result ma_job_process__custom(ma_job* pJob)
  14605. {
  14606. MA_ASSERT(pJob != NULL);
  14607. /* No-op if there's no callback. */
  14608. if (pJob->data.custom.proc == NULL) {
  14609. return MA_SUCCESS;
  14610. }
  14611. return pJob->data.custom.proc(pJob);
  14612. }
  14613. MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity)
  14614. {
  14615. ma_job_queue_config config;
  14616. config.flags = flags;
  14617. config.capacity = capacity;
  14618. return config;
  14619. }
  14620. typedef struct
  14621. {
  14622. size_t sizeInBytes;
  14623. size_t allocatorOffset;
  14624. size_t jobsOffset;
  14625. } ma_job_queue_heap_layout;
  14626. static ma_result ma_job_queue_get_heap_layout(const ma_job_queue_config* pConfig, ma_job_queue_heap_layout* pHeapLayout)
  14627. {
  14628. ma_result result;
  14629. MA_ASSERT(pHeapLayout != NULL);
  14630. MA_ZERO_OBJECT(pHeapLayout);
  14631. if (pConfig == NULL) {
  14632. return MA_INVALID_ARGS;
  14633. }
  14634. if (pConfig->capacity == 0) {
  14635. return MA_INVALID_ARGS;
  14636. }
  14637. pHeapLayout->sizeInBytes = 0;
  14638. /* Allocator. */
  14639. {
  14640. ma_slot_allocator_config allocatorConfig;
  14641. size_t allocatorHeapSizeInBytes;
  14642. allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity);
  14643. result = ma_slot_allocator_get_heap_size(&allocatorConfig, &allocatorHeapSizeInBytes);
  14644. if (result != MA_SUCCESS) {
  14645. return result;
  14646. }
  14647. pHeapLayout->allocatorOffset = pHeapLayout->sizeInBytes;
  14648. pHeapLayout->sizeInBytes += allocatorHeapSizeInBytes;
  14649. }
  14650. /* Jobs. */
  14651. pHeapLayout->jobsOffset = pHeapLayout->sizeInBytes;
  14652. pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_job));
  14653. return MA_SUCCESS;
  14654. }
  14655. MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes)
  14656. {
  14657. ma_result result;
  14658. ma_job_queue_heap_layout layout;
  14659. if (pHeapSizeInBytes == NULL) {
  14660. return MA_INVALID_ARGS;
  14661. }
  14662. *pHeapSizeInBytes = 0;
  14663. result = ma_job_queue_get_heap_layout(pConfig, &layout);
  14664. if (result != MA_SUCCESS) {
  14665. return result;
  14666. }
  14667. *pHeapSizeInBytes = layout.sizeInBytes;
  14668. return MA_SUCCESS;
  14669. }
  14670. MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue)
  14671. {
  14672. ma_result result;
  14673. ma_job_queue_heap_layout heapLayout;
  14674. ma_slot_allocator_config allocatorConfig;
  14675. if (pQueue == NULL) {
  14676. return MA_INVALID_ARGS;
  14677. }
  14678. MA_ZERO_OBJECT(pQueue);
  14679. result = ma_job_queue_get_heap_layout(pConfig, &heapLayout);
  14680. if (result != MA_SUCCESS) {
  14681. return result;
  14682. }
  14683. pQueue->_pHeap = pHeap;
  14684. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  14685. pQueue->flags = pConfig->flags;
  14686. pQueue->capacity = pConfig->capacity;
  14687. pQueue->pJobs = (ma_job*)ma_offset_ptr(pHeap, heapLayout.jobsOffset);
  14688. allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity);
  14689. result = ma_slot_allocator_init_preallocated(&allocatorConfig, ma_offset_ptr(pHeap, heapLayout.allocatorOffset), &pQueue->allocator);
  14690. if (result != MA_SUCCESS) {
  14691. return result;
  14692. }
  14693. /* We need a semaphore if we're running in non-blocking mode. If threading is disabled we need to return an error. */
  14694. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14695. #ifndef MA_NO_THREADING
  14696. {
  14697. ma_semaphore_init(0, &pQueue->sem);
  14698. }
  14699. #else
  14700. {
  14701. /* Threading is disabled and we've requested non-blocking mode. */
  14702. return MA_INVALID_OPERATION;
  14703. }
  14704. #endif
  14705. }
  14706. /*
  14707. 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
  14708. just a dummy item for giving us the first item in the list which is stored in the "next" member.
  14709. */
  14710. ma_slot_allocator_alloc(&pQueue->allocator, &pQueue->head); /* Will never fail. */
  14711. pQueue->pJobs[ma_job_extract_slot(pQueue->head)].next = MA_JOB_ID_NONE;
  14712. pQueue->tail = pQueue->head;
  14713. return MA_SUCCESS;
  14714. }
  14715. MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue)
  14716. {
  14717. ma_result result;
  14718. size_t heapSizeInBytes;
  14719. void* pHeap;
  14720. result = ma_job_queue_get_heap_size(pConfig, &heapSizeInBytes);
  14721. if (result != MA_SUCCESS) {
  14722. return result;
  14723. }
  14724. if (heapSizeInBytes > 0) {
  14725. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  14726. if (pHeap == NULL) {
  14727. return MA_OUT_OF_MEMORY;
  14728. }
  14729. } else {
  14730. pHeap = NULL;
  14731. }
  14732. result = ma_job_queue_init_preallocated(pConfig, pHeap, pQueue);
  14733. if (result != MA_SUCCESS) {
  14734. ma_free(pHeap, pAllocationCallbacks);
  14735. return result;
  14736. }
  14737. pQueue->_ownsHeap = MA_TRUE;
  14738. return MA_SUCCESS;
  14739. }
  14740. MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks)
  14741. {
  14742. if (pQueue == NULL) {
  14743. return;
  14744. }
  14745. /* All we need to do is uninitialize the semaphore. */
  14746. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14747. #ifndef MA_NO_THREADING
  14748. {
  14749. ma_semaphore_uninit(&pQueue->sem);
  14750. }
  14751. #else
  14752. {
  14753. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14754. }
  14755. #endif
  14756. }
  14757. ma_slot_allocator_uninit(&pQueue->allocator, pAllocationCallbacks);
  14758. if (pQueue->_ownsHeap) {
  14759. ma_free(pQueue->_pHeap, pAllocationCallbacks);
  14760. }
  14761. }
  14762. static ma_bool32 ma_job_queue_cas(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired)
  14763. {
  14764. /* The new counter is taken from the expected value. */
  14765. return ma_atomic_compare_and_swap_64(dst, expected, ma_job_set_refcount(desired, ma_job_extract_refcount(expected) + 1)) == expected;
  14766. }
  14767. MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob)
  14768. {
  14769. /*
  14770. Lock free queue implementation based on the paper by Michael and Scott: Nonblocking Algorithms and Preemption-Safe Locking on Multiprogrammed Shared Memory Multiprocessors
  14771. */
  14772. ma_result result;
  14773. ma_uint64 slot;
  14774. ma_uint64 tail;
  14775. ma_uint64 next;
  14776. if (pQueue == NULL || pJob == NULL) {
  14777. return MA_INVALID_ARGS;
  14778. }
  14779. /* We need a new slot. */
  14780. result = ma_slot_allocator_alloc(&pQueue->allocator, &slot);
  14781. if (result != MA_SUCCESS) {
  14782. return result; /* Probably ran out of slots. If so, MA_OUT_OF_MEMORY will be returned. */
  14783. }
  14784. /* At this point we should have a slot to place the job. */
  14785. MA_ASSERT(ma_job_extract_slot(slot) < pQueue->capacity);
  14786. /* We need to put the job into memory before we do anything. */
  14787. pQueue->pJobs[ma_job_extract_slot(slot)] = *pJob;
  14788. pQueue->pJobs[ma_job_extract_slot(slot)].toc.allocation = slot; /* This will overwrite the job code. */
  14789. 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. */
  14790. pQueue->pJobs[ma_job_extract_slot(slot)].next = MA_JOB_ID_NONE; /* Reset for safety. */
  14791. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14792. ma_spinlock_lock(&pQueue->lock);
  14793. #endif
  14794. {
  14795. /* 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. */
  14796. for (;;) {
  14797. tail = ma_atomic_load_64(&pQueue->tail);
  14798. next = ma_atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(tail)].next);
  14799. if (ma_job_toc_to_allocation(tail) == ma_job_toc_to_allocation(ma_atomic_load_64(&pQueue->tail))) {
  14800. if (ma_job_extract_slot(next) == 0xFFFF) {
  14801. if (ma_job_queue_cas(&pQueue->pJobs[ma_job_extract_slot(tail)].next, next, slot)) {
  14802. break;
  14803. }
  14804. } else {
  14805. ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next));
  14806. }
  14807. }
  14808. }
  14809. ma_job_queue_cas(&pQueue->tail, tail, slot);
  14810. }
  14811. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14812. ma_spinlock_unlock(&pQueue->lock);
  14813. #endif
  14814. /* Signal the semaphore as the last step if we're using synchronous mode. */
  14815. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14816. #ifndef MA_NO_THREADING
  14817. {
  14818. ma_semaphore_release(&pQueue->sem);
  14819. }
  14820. #else
  14821. {
  14822. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14823. }
  14824. #endif
  14825. }
  14826. return MA_SUCCESS;
  14827. }
  14828. MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob)
  14829. {
  14830. ma_uint64 head;
  14831. ma_uint64 tail;
  14832. ma_uint64 next;
  14833. if (pQueue == NULL || pJob == NULL) {
  14834. return MA_INVALID_ARGS;
  14835. }
  14836. /* If we're running in synchronous mode we'll need to wait on a semaphore. */
  14837. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14838. #ifndef MA_NO_THREADING
  14839. {
  14840. ma_semaphore_wait(&pQueue->sem);
  14841. }
  14842. #else
  14843. {
  14844. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14845. }
  14846. #endif
  14847. }
  14848. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14849. ma_spinlock_lock(&pQueue->lock);
  14850. #endif
  14851. {
  14852. /*
  14853. BUG: In lock-free mode, multiple threads can be in this section of code. The "head" variable in the loop below
  14854. is stored. One thread can fall through to the freeing of this item while another is still using "head" for the
  14855. retrieval of the "next" variable.
  14856. The slot allocator might need to make use of some reference counting to ensure it's only truely freed when
  14857. there are no more references to the item. This must be fixed before removing these locks.
  14858. */
  14859. /* Now we need to remove the root item from the list. */
  14860. for (;;) {
  14861. head = ma_atomic_load_64(&pQueue->head);
  14862. tail = ma_atomic_load_64(&pQueue->tail);
  14863. next = ma_atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(head)].next);
  14864. if (ma_job_toc_to_allocation(head) == ma_job_toc_to_allocation(ma_atomic_load_64(&pQueue->head))) {
  14865. if (ma_job_extract_slot(head) == ma_job_extract_slot(tail)) {
  14866. if (ma_job_extract_slot(next) == 0xFFFF) {
  14867. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14868. ma_spinlock_unlock(&pQueue->lock);
  14869. #endif
  14870. return MA_NO_DATA_AVAILABLE;
  14871. }
  14872. ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next));
  14873. } else {
  14874. *pJob = pQueue->pJobs[ma_job_extract_slot(next)];
  14875. if (ma_job_queue_cas(&pQueue->head, head, ma_job_extract_slot(next))) {
  14876. break;
  14877. }
  14878. }
  14879. }
  14880. }
  14881. }
  14882. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14883. ma_spinlock_unlock(&pQueue->lock);
  14884. #endif
  14885. ma_slot_allocator_free(&pQueue->allocator, head);
  14886. /*
  14887. 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
  14888. 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
  14889. possible.
  14890. */
  14891. if (pJob->toc.breakup.code == MA_JOB_TYPE_QUIT) {
  14892. ma_job_queue_post(pQueue, pJob);
  14893. return MA_CANCELLED; /* Return a cancelled status just in case the thread is checking return codes and not properly checking for a quit job. */
  14894. }
  14895. return MA_SUCCESS;
  14896. }
  14897. /*******************************************************************************
  14898. Dynamic Linking
  14899. *******************************************************************************/
  14900. #ifdef MA_POSIX
  14901. /* No need for dlfcn.h if we're not using runtime linking. */
  14902. #ifndef MA_NO_RUNTIME_LINKING
  14903. #include <dlfcn.h>
  14904. #endif
  14905. #endif
  14906. MA_API ma_handle ma_dlopen(ma_log* pLog, const char* filename)
  14907. {
  14908. #ifndef MA_NO_RUNTIME_LINKING
  14909. ma_handle handle;
  14910. ma_log_postf(pLog, MA_LOG_LEVEL_DEBUG, "Loading library: %s\n", filename);
  14911. #ifdef MA_WIN32
  14912. /* From MSDN: Desktop applications cannot use LoadPackagedLibrary; if a desktop application calls this function it fails with APPMODEL_ERROR_NO_PACKAGE.*/
  14913. #if !defined(MA_WIN32_UWP)
  14914. handle = (ma_handle)LoadLibraryA(filename);
  14915. #else
  14916. /* *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... */
  14917. WCHAR filenameW[4096];
  14918. if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) {
  14919. handle = NULL;
  14920. } else {
  14921. handle = (ma_handle)LoadPackagedLibrary(filenameW, 0);
  14922. }
  14923. #endif
  14924. #else
  14925. handle = (ma_handle)dlopen(filename, RTLD_NOW);
  14926. #endif
  14927. /*
  14928. I'm not considering failure to load a library an error nor a warning because seamlessly falling through to a lower-priority
  14929. backend is a deliberate design choice. Instead I'm logging it as an informational message.
  14930. */
  14931. if (handle == NULL) {
  14932. ma_log_postf(pLog, MA_LOG_LEVEL_INFO, "Failed to load library: %s\n", filename);
  14933. }
  14934. return handle;
  14935. #else
  14936. /* Runtime linking is disabled. */
  14937. (void)pLog;
  14938. (void)filename;
  14939. return NULL;
  14940. #endif
  14941. }
  14942. MA_API void ma_dlclose(ma_log* pLog, ma_handle handle)
  14943. {
  14944. #ifndef MA_NO_RUNTIME_LINKING
  14945. #ifdef MA_WIN32
  14946. FreeLibrary((HMODULE)handle);
  14947. #else
  14948. dlclose((void*)handle);
  14949. #endif
  14950. (void)pLog;
  14951. #else
  14952. /* Runtime linking is disabled. */
  14953. (void)pLog;
  14954. (void)handle;
  14955. #endif
  14956. }
  14957. MA_API ma_proc ma_dlsym(ma_log* pLog, ma_handle handle, const char* symbol)
  14958. {
  14959. #ifndef MA_NO_RUNTIME_LINKING
  14960. ma_proc proc;
  14961. ma_log_postf(pLog, MA_LOG_LEVEL_DEBUG, "Loading symbol: %s\n", symbol);
  14962. #ifdef _WIN32
  14963. proc = (ma_proc)GetProcAddress((HMODULE)handle, symbol);
  14964. #else
  14965. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  14966. #pragma GCC diagnostic push
  14967. #pragma GCC diagnostic ignored "-Wpedantic"
  14968. #endif
  14969. proc = (ma_proc)dlsym((void*)handle, symbol);
  14970. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  14971. #pragma GCC diagnostic pop
  14972. #endif
  14973. #endif
  14974. if (proc == NULL) {
  14975. ma_log_postf(pLog, MA_LOG_LEVEL_WARNING, "Failed to load symbol: %s\n", symbol);
  14976. }
  14977. (void)pLog; /* It's possible for pContext to be unused. */
  14978. return proc;
  14979. #else
  14980. /* Runtime linking is disabled. */
  14981. (void)pLog;
  14982. (void)handle;
  14983. (void)symbol;
  14984. return NULL;
  14985. #endif
  14986. }
  14987. /************************************************************************************************************************************************************
  14988. *************************************************************************************************************************************************************
  14989. DEVICE I/O
  14990. ==========
  14991. *************************************************************************************************************************************************************
  14992. ************************************************************************************************************************************************************/
  14993. /* Disable run-time linking on certain backends and platforms. */
  14994. #ifndef MA_NO_RUNTIME_LINKING
  14995. #if defined(MA_EMSCRIPTEN) || defined(MA_ORBIS) || defined(MA_PROSPERO)
  14996. #define MA_NO_RUNTIME_LINKING
  14997. #endif
  14998. #endif
  14999. #ifndef MA_NO_DEVICE_IO
  15000. #if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
  15001. #include <mach/mach_time.h> /* For mach_absolute_time() */
  15002. #endif
  15003. #ifdef MA_POSIX
  15004. #include <sys/types.h>
  15005. #include <unistd.h>
  15006. /* No need for dlfcn.h if we're not using runtime linking. */
  15007. #ifndef MA_NO_RUNTIME_LINKING
  15008. #include <dlfcn.h>
  15009. #endif
  15010. #endif
  15011. 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)
  15012. {
  15013. if (pDeviceInfo == NULL) {
  15014. return;
  15015. }
  15016. if (pDeviceInfo->nativeDataFormatCount < ma_countof(pDeviceInfo->nativeDataFormats)) {
  15017. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  15018. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  15019. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  15020. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  15021. pDeviceInfo->nativeDataFormatCount += 1;
  15022. }
  15023. }
  15024. typedef struct
  15025. {
  15026. ma_backend backend;
  15027. const char* pName;
  15028. } ma_backend_info;
  15029. static ma_backend_info gBackendInfo[] = /* Indexed by the backend enum. Must be in the order backends are declared in the ma_backend enum. */
  15030. {
  15031. {ma_backend_wasapi, "WASAPI"},
  15032. {ma_backend_dsound, "DirectSound"},
  15033. {ma_backend_winmm, "WinMM"},
  15034. {ma_backend_coreaudio, "Core Audio"},
  15035. {ma_backend_sndio, "sndio"},
  15036. {ma_backend_audio4, "audio(4)"},
  15037. {ma_backend_oss, "OSS"},
  15038. {ma_backend_pulseaudio, "PulseAudio"},
  15039. {ma_backend_alsa, "ALSA"},
  15040. {ma_backend_jack, "JACK"},
  15041. {ma_backend_aaudio, "AAudio"},
  15042. {ma_backend_opensl, "OpenSL|ES"},
  15043. {ma_backend_webaudio, "Web Audio"},
  15044. {ma_backend_custom, "Custom"},
  15045. {ma_backend_null, "Null"}
  15046. };
  15047. MA_API const char* ma_get_backend_name(ma_backend backend)
  15048. {
  15049. if (backend < 0 || backend >= (int)ma_countof(gBackendInfo)) {
  15050. return "Unknown";
  15051. }
  15052. return gBackendInfo[backend].pName;
  15053. }
  15054. MA_API ma_result ma_get_backend_from_name(const char* pBackendName, ma_backend* pBackend)
  15055. {
  15056. size_t iBackend;
  15057. if (pBackendName == NULL) {
  15058. return MA_INVALID_ARGS;
  15059. }
  15060. for (iBackend = 0; iBackend < ma_countof(gBackendInfo); iBackend += 1) {
  15061. if (ma_strcmp(pBackendName, gBackendInfo[iBackend].pName) == 0) {
  15062. if (pBackend != NULL) {
  15063. *pBackend = gBackendInfo[iBackend].backend;
  15064. }
  15065. return MA_SUCCESS;
  15066. }
  15067. }
  15068. /* Getting here means the backend name is unknown. */
  15069. return MA_INVALID_ARGS;
  15070. }
  15071. MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend)
  15072. {
  15073. /*
  15074. This looks a little bit gross, but we want all backends to be included in the switch to avoid warnings on some compilers
  15075. about some enums not being handled by the switch statement.
  15076. */
  15077. switch (backend)
  15078. {
  15079. case ma_backend_wasapi:
  15080. #if defined(MA_HAS_WASAPI)
  15081. return MA_TRUE;
  15082. #else
  15083. return MA_FALSE;
  15084. #endif
  15085. case ma_backend_dsound:
  15086. #if defined(MA_HAS_DSOUND)
  15087. return MA_TRUE;
  15088. #else
  15089. return MA_FALSE;
  15090. #endif
  15091. case ma_backend_winmm:
  15092. #if defined(MA_HAS_WINMM)
  15093. return MA_TRUE;
  15094. #else
  15095. return MA_FALSE;
  15096. #endif
  15097. case ma_backend_coreaudio:
  15098. #if defined(MA_HAS_COREAUDIO)
  15099. return MA_TRUE;
  15100. #else
  15101. return MA_FALSE;
  15102. #endif
  15103. case ma_backend_sndio:
  15104. #if defined(MA_HAS_SNDIO)
  15105. return MA_TRUE;
  15106. #else
  15107. return MA_FALSE;
  15108. #endif
  15109. case ma_backend_audio4:
  15110. #if defined(MA_HAS_AUDIO4)
  15111. return MA_TRUE;
  15112. #else
  15113. return MA_FALSE;
  15114. #endif
  15115. case ma_backend_oss:
  15116. #if defined(MA_HAS_OSS)
  15117. return MA_TRUE;
  15118. #else
  15119. return MA_FALSE;
  15120. #endif
  15121. case ma_backend_pulseaudio:
  15122. #if defined(MA_HAS_PULSEAUDIO)
  15123. return MA_TRUE;
  15124. #else
  15125. return MA_FALSE;
  15126. #endif
  15127. case ma_backend_alsa:
  15128. #if defined(MA_HAS_ALSA)
  15129. return MA_TRUE;
  15130. #else
  15131. return MA_FALSE;
  15132. #endif
  15133. case ma_backend_jack:
  15134. #if defined(MA_HAS_JACK)
  15135. return MA_TRUE;
  15136. #else
  15137. return MA_FALSE;
  15138. #endif
  15139. case ma_backend_aaudio:
  15140. #if defined(MA_HAS_AAUDIO)
  15141. #if defined(MA_ANDROID)
  15142. {
  15143. return ma_android_sdk_version() >= 26;
  15144. }
  15145. #else
  15146. return MA_FALSE;
  15147. #endif
  15148. #else
  15149. return MA_FALSE;
  15150. #endif
  15151. case ma_backend_opensl:
  15152. #if defined(MA_HAS_OPENSL)
  15153. #if defined(MA_ANDROID)
  15154. {
  15155. return ma_android_sdk_version() >= 9;
  15156. }
  15157. #else
  15158. return MA_TRUE;
  15159. #endif
  15160. #else
  15161. return MA_FALSE;
  15162. #endif
  15163. case ma_backend_webaudio:
  15164. #if defined(MA_HAS_WEBAUDIO)
  15165. return MA_TRUE;
  15166. #else
  15167. return MA_FALSE;
  15168. #endif
  15169. case ma_backend_custom:
  15170. #if defined(MA_HAS_CUSTOM)
  15171. return MA_TRUE;
  15172. #else
  15173. return MA_FALSE;
  15174. #endif
  15175. case ma_backend_null:
  15176. #if defined(MA_HAS_NULL)
  15177. return MA_TRUE;
  15178. #else
  15179. return MA_FALSE;
  15180. #endif
  15181. default: return MA_FALSE;
  15182. }
  15183. }
  15184. MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount)
  15185. {
  15186. size_t backendCount;
  15187. size_t iBackend;
  15188. ma_result result = MA_SUCCESS;
  15189. if (pBackendCount == NULL) {
  15190. return MA_INVALID_ARGS;
  15191. }
  15192. backendCount = 0;
  15193. for (iBackend = 0; iBackend <= ma_backend_null; iBackend += 1) {
  15194. ma_backend backend = (ma_backend)iBackend;
  15195. if (ma_is_backend_enabled(backend)) {
  15196. /* The backend is enabled. Try adding it to the list. If there's no room, MA_NO_SPACE needs to be returned. */
  15197. if (backendCount == backendCap) {
  15198. result = MA_NO_SPACE;
  15199. break;
  15200. } else {
  15201. pBackends[backendCount] = backend;
  15202. backendCount += 1;
  15203. }
  15204. }
  15205. }
  15206. if (pBackendCount != NULL) {
  15207. *pBackendCount = backendCount;
  15208. }
  15209. return result;
  15210. }
  15211. MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend)
  15212. {
  15213. switch (backend)
  15214. {
  15215. case ma_backend_wasapi: return MA_TRUE;
  15216. case ma_backend_dsound: return MA_FALSE;
  15217. case ma_backend_winmm: return MA_FALSE;
  15218. case ma_backend_coreaudio: return MA_FALSE;
  15219. case ma_backend_sndio: return MA_FALSE;
  15220. case ma_backend_audio4: return MA_FALSE;
  15221. case ma_backend_oss: return MA_FALSE;
  15222. case ma_backend_pulseaudio: return MA_FALSE;
  15223. case ma_backend_alsa: return MA_FALSE;
  15224. case ma_backend_jack: return MA_FALSE;
  15225. case ma_backend_aaudio: return MA_FALSE;
  15226. case ma_backend_opensl: return MA_FALSE;
  15227. case ma_backend_webaudio: return MA_FALSE;
  15228. case ma_backend_custom: return MA_FALSE; /* <-- Will depend on the implementation of the backend. */
  15229. case ma_backend_null: return MA_FALSE;
  15230. default: return MA_FALSE;
  15231. }
  15232. }
  15233. #if defined(MA_WIN32)
  15234. /* WASAPI error codes. */
  15235. #define MA_AUDCLNT_E_NOT_INITIALIZED ((HRESULT)0x88890001)
  15236. #define MA_AUDCLNT_E_ALREADY_INITIALIZED ((HRESULT)0x88890002)
  15237. #define MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE ((HRESULT)0x88890003)
  15238. #define MA_AUDCLNT_E_DEVICE_INVALIDATED ((HRESULT)0x88890004)
  15239. #define MA_AUDCLNT_E_NOT_STOPPED ((HRESULT)0x88890005)
  15240. #define MA_AUDCLNT_E_BUFFER_TOO_LARGE ((HRESULT)0x88890006)
  15241. #define MA_AUDCLNT_E_OUT_OF_ORDER ((HRESULT)0x88890007)
  15242. #define MA_AUDCLNT_E_UNSUPPORTED_FORMAT ((HRESULT)0x88890008)
  15243. #define MA_AUDCLNT_E_INVALID_SIZE ((HRESULT)0x88890009)
  15244. #define MA_AUDCLNT_E_DEVICE_IN_USE ((HRESULT)0x8889000A)
  15245. #define MA_AUDCLNT_E_BUFFER_OPERATION_PENDING ((HRESULT)0x8889000B)
  15246. #define MA_AUDCLNT_E_THREAD_NOT_REGISTERED ((HRESULT)0x8889000C)
  15247. #define MA_AUDCLNT_E_NO_SINGLE_PROCESS ((HRESULT)0x8889000D)
  15248. #define MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED ((HRESULT)0x8889000E)
  15249. #define MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED ((HRESULT)0x8889000F)
  15250. #define MA_AUDCLNT_E_SERVICE_NOT_RUNNING ((HRESULT)0x88890010)
  15251. #define MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED ((HRESULT)0x88890011)
  15252. #define MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY ((HRESULT)0x88890012)
  15253. #define MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL ((HRESULT)0x88890013)
  15254. #define MA_AUDCLNT_E_EVENTHANDLE_NOT_SET ((HRESULT)0x88890014)
  15255. #define MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE ((HRESULT)0x88890015)
  15256. #define MA_AUDCLNT_E_BUFFER_SIZE_ERROR ((HRESULT)0x88890016)
  15257. #define MA_AUDCLNT_E_CPUUSAGE_EXCEEDED ((HRESULT)0x88890017)
  15258. #define MA_AUDCLNT_E_BUFFER_ERROR ((HRESULT)0x88890018)
  15259. #define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED ((HRESULT)0x88890019)
  15260. #define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD ((HRESULT)0x88890020)
  15261. #define MA_AUDCLNT_E_INVALID_STREAM_FLAG ((HRESULT)0x88890021)
  15262. #define MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE ((HRESULT)0x88890022)
  15263. #define MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES ((HRESULT)0x88890023)
  15264. #define MA_AUDCLNT_E_OFFLOAD_MODE_ONLY ((HRESULT)0x88890024)
  15265. #define MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY ((HRESULT)0x88890025)
  15266. #define MA_AUDCLNT_E_RESOURCES_INVALIDATED ((HRESULT)0x88890026)
  15267. #define MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED ((HRESULT)0x88890027)
  15268. #define MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED ((HRESULT)0x88890028)
  15269. #define MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED ((HRESULT)0x88890029)
  15270. #define MA_AUDCLNT_E_HEADTRACKING_ENABLED ((HRESULT)0x88890030)
  15271. #define MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED ((HRESULT)0x88890040)
  15272. #define MA_AUDCLNT_S_BUFFER_EMPTY ((HRESULT)0x08890001)
  15273. #define MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED ((HRESULT)0x08890002)
  15274. #define MA_AUDCLNT_S_POSITION_STALLED ((HRESULT)0x08890003)
  15275. #define MA_DS_OK ((HRESULT)0)
  15276. #define MA_DS_NO_VIRTUALIZATION ((HRESULT)0x0878000A)
  15277. #define MA_DSERR_ALLOCATED ((HRESULT)0x8878000A)
  15278. #define MA_DSERR_CONTROLUNAVAIL ((HRESULT)0x8878001E)
  15279. #define MA_DSERR_INVALIDPARAM ((HRESULT)0x80070057) /*E_INVALIDARG*/
  15280. #define MA_DSERR_INVALIDCALL ((HRESULT)0x88780032)
  15281. #define MA_DSERR_GENERIC ((HRESULT)0x80004005) /*E_FAIL*/
  15282. #define MA_DSERR_PRIOLEVELNEEDED ((HRESULT)0x88780046)
  15283. #define MA_DSERR_OUTOFMEMORY ((HRESULT)0x8007000E) /*E_OUTOFMEMORY*/
  15284. #define MA_DSERR_BADFORMAT ((HRESULT)0x88780064)
  15285. #define MA_DSERR_UNSUPPORTED ((HRESULT)0x80004001) /*E_NOTIMPL*/
  15286. #define MA_DSERR_NODRIVER ((HRESULT)0x88780078)
  15287. #define MA_DSERR_ALREADYINITIALIZED ((HRESULT)0x88780082)
  15288. #define MA_DSERR_NOAGGREGATION ((HRESULT)0x80040110) /*CLASS_E_NOAGGREGATION*/
  15289. #define MA_DSERR_BUFFERLOST ((HRESULT)0x88780096)
  15290. #define MA_DSERR_OTHERAPPHASPRIO ((HRESULT)0x887800A0)
  15291. #define MA_DSERR_UNINITIALIZED ((HRESULT)0x887800AA)
  15292. #define MA_DSERR_NOINTERFACE ((HRESULT)0x80004002) /*E_NOINTERFACE*/
  15293. #define MA_DSERR_ACCESSDENIED ((HRESULT)0x80070005) /*E_ACCESSDENIED*/
  15294. #define MA_DSERR_BUFFERTOOSMALL ((HRESULT)0x887800B4)
  15295. #define MA_DSERR_DS8_REQUIRED ((HRESULT)0x887800BE)
  15296. #define MA_DSERR_SENDLOOP ((HRESULT)0x887800C8)
  15297. #define MA_DSERR_BADSENDBUFFERGUID ((HRESULT)0x887800D2)
  15298. #define MA_DSERR_OBJECTNOTFOUND ((HRESULT)0x88781161)
  15299. #define MA_DSERR_FXUNAVAILABLE ((HRESULT)0x887800DC)
  15300. static ma_result ma_result_from_HRESULT(HRESULT hr)
  15301. {
  15302. switch (hr)
  15303. {
  15304. case NOERROR: return MA_SUCCESS;
  15305. /*case S_OK: return MA_SUCCESS;*/
  15306. case E_POINTER: return MA_INVALID_ARGS;
  15307. case E_UNEXPECTED: return MA_ERROR;
  15308. case E_NOTIMPL: return MA_NOT_IMPLEMENTED;
  15309. case E_OUTOFMEMORY: return MA_OUT_OF_MEMORY;
  15310. case E_INVALIDARG: return MA_INVALID_ARGS;
  15311. case E_NOINTERFACE: return MA_API_NOT_FOUND;
  15312. case E_HANDLE: return MA_INVALID_ARGS;
  15313. case E_ABORT: return MA_ERROR;
  15314. case E_FAIL: return MA_ERROR;
  15315. case E_ACCESSDENIED: return MA_ACCESS_DENIED;
  15316. /* WASAPI */
  15317. case MA_AUDCLNT_E_NOT_INITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
  15318. case MA_AUDCLNT_E_ALREADY_INITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
  15319. case MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE: return MA_INVALID_ARGS;
  15320. case MA_AUDCLNT_E_DEVICE_INVALIDATED: return MA_UNAVAILABLE;
  15321. case MA_AUDCLNT_E_NOT_STOPPED: return MA_DEVICE_NOT_STOPPED;
  15322. case MA_AUDCLNT_E_BUFFER_TOO_LARGE: return MA_TOO_BIG;
  15323. case MA_AUDCLNT_E_OUT_OF_ORDER: return MA_INVALID_OPERATION;
  15324. case MA_AUDCLNT_E_UNSUPPORTED_FORMAT: return MA_FORMAT_NOT_SUPPORTED;
  15325. case MA_AUDCLNT_E_INVALID_SIZE: return MA_INVALID_ARGS;
  15326. case MA_AUDCLNT_E_DEVICE_IN_USE: return MA_BUSY;
  15327. case MA_AUDCLNT_E_BUFFER_OPERATION_PENDING: return MA_INVALID_OPERATION;
  15328. case MA_AUDCLNT_E_THREAD_NOT_REGISTERED: return MA_DOES_NOT_EXIST;
  15329. case MA_AUDCLNT_E_NO_SINGLE_PROCESS: return MA_INVALID_OPERATION;
  15330. case MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: return MA_SHARE_MODE_NOT_SUPPORTED;
  15331. case MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED: return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  15332. case MA_AUDCLNT_E_SERVICE_NOT_RUNNING: return MA_NOT_CONNECTED;
  15333. case MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: return MA_INVALID_ARGS;
  15334. case MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY: return MA_SHARE_MODE_NOT_SUPPORTED;
  15335. case MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: return MA_INVALID_ARGS;
  15336. case MA_AUDCLNT_E_EVENTHANDLE_NOT_SET: return MA_INVALID_ARGS;
  15337. case MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE: return MA_INVALID_ARGS;
  15338. case MA_AUDCLNT_E_BUFFER_SIZE_ERROR: return MA_INVALID_ARGS;
  15339. case MA_AUDCLNT_E_CPUUSAGE_EXCEEDED: return MA_ERROR;
  15340. case MA_AUDCLNT_E_BUFFER_ERROR: return MA_ERROR;
  15341. case MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: return MA_INVALID_ARGS;
  15342. case MA_AUDCLNT_E_INVALID_DEVICE_PERIOD: return MA_INVALID_ARGS;
  15343. case MA_AUDCLNT_E_INVALID_STREAM_FLAG: return MA_INVALID_ARGS;
  15344. case MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: return MA_INVALID_OPERATION;
  15345. case MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: return MA_OUT_OF_MEMORY;
  15346. case MA_AUDCLNT_E_OFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
  15347. case MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
  15348. case MA_AUDCLNT_E_RESOURCES_INVALIDATED: return MA_INVALID_DATA;
  15349. case MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED: return MA_INVALID_OPERATION;
  15350. case MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED: return MA_INVALID_OPERATION;
  15351. case MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED: return MA_INVALID_OPERATION;
  15352. case MA_AUDCLNT_E_HEADTRACKING_ENABLED: return MA_INVALID_OPERATION;
  15353. case MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED: return MA_INVALID_OPERATION;
  15354. case MA_AUDCLNT_S_BUFFER_EMPTY: return MA_NO_SPACE;
  15355. case MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED: return MA_ALREADY_EXISTS;
  15356. case MA_AUDCLNT_S_POSITION_STALLED: return MA_ERROR;
  15357. /* DirectSound */
  15358. /*case MA_DS_OK: return MA_SUCCESS;*/ /* S_OK */
  15359. case MA_DS_NO_VIRTUALIZATION: return MA_SUCCESS;
  15360. case MA_DSERR_ALLOCATED: return MA_ALREADY_IN_USE;
  15361. case MA_DSERR_CONTROLUNAVAIL: return MA_INVALID_OPERATION;
  15362. /*case MA_DSERR_INVALIDPARAM: return MA_INVALID_ARGS;*/ /* E_INVALIDARG */
  15363. case MA_DSERR_INVALIDCALL: return MA_INVALID_OPERATION;
  15364. /*case MA_DSERR_GENERIC: return MA_ERROR;*/ /* E_FAIL */
  15365. case MA_DSERR_PRIOLEVELNEEDED: return MA_INVALID_OPERATION;
  15366. /*case MA_DSERR_OUTOFMEMORY: return MA_OUT_OF_MEMORY;*/ /* E_OUTOFMEMORY */
  15367. case MA_DSERR_BADFORMAT: return MA_FORMAT_NOT_SUPPORTED;
  15368. /*case MA_DSERR_UNSUPPORTED: return MA_NOT_IMPLEMENTED;*/ /* E_NOTIMPL */
  15369. case MA_DSERR_NODRIVER: return MA_FAILED_TO_INIT_BACKEND;
  15370. case MA_DSERR_ALREADYINITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
  15371. case MA_DSERR_NOAGGREGATION: return MA_ERROR;
  15372. case MA_DSERR_BUFFERLOST: return MA_UNAVAILABLE;
  15373. case MA_DSERR_OTHERAPPHASPRIO: return MA_ACCESS_DENIED;
  15374. case MA_DSERR_UNINITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
  15375. /*case MA_DSERR_NOINTERFACE: return MA_API_NOT_FOUND;*/ /* E_NOINTERFACE */
  15376. /*case MA_DSERR_ACCESSDENIED: return MA_ACCESS_DENIED;*/ /* E_ACCESSDENIED */
  15377. case MA_DSERR_BUFFERTOOSMALL: return MA_NO_SPACE;
  15378. case MA_DSERR_DS8_REQUIRED: return MA_INVALID_OPERATION;
  15379. case MA_DSERR_SENDLOOP: return MA_DEADLOCK;
  15380. case MA_DSERR_BADSENDBUFFERGUID: return MA_INVALID_ARGS;
  15381. case MA_DSERR_OBJECTNOTFOUND: return MA_NO_DEVICE;
  15382. case MA_DSERR_FXUNAVAILABLE: return MA_UNAVAILABLE;
  15383. default: return MA_ERROR;
  15384. }
  15385. }
  15386. /* PROPVARIANT */
  15387. #define MA_VT_LPWSTR 31
  15388. #define MA_VT_BLOB 65
  15389. #if defined(_MSC_VER) && !defined(__clang__)
  15390. #pragma warning(push)
  15391. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  15392. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  15393. #pragma GCC diagnostic push
  15394. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  15395. #if defined(__clang__)
  15396. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  15397. #endif
  15398. #endif
  15399. typedef struct
  15400. {
  15401. WORD vt;
  15402. WORD wReserved1;
  15403. WORD wReserved2;
  15404. WORD wReserved3;
  15405. union
  15406. {
  15407. struct
  15408. {
  15409. ULONG cbSize;
  15410. BYTE* pBlobData;
  15411. } blob;
  15412. WCHAR* pwszVal;
  15413. char pad[16]; /* Just to ensure the size of the struct matches the official version. */
  15414. };
  15415. } MA_PROPVARIANT;
  15416. #if defined(_MSC_VER) && !defined(__clang__)
  15417. #pragma warning(pop)
  15418. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  15419. #pragma GCC diagnostic pop
  15420. #endif
  15421. typedef HRESULT (WINAPI * MA_PFN_CoInitialize)(void* pvReserved);
  15422. typedef HRESULT (WINAPI * MA_PFN_CoInitializeEx)(void* pvReserved, DWORD dwCoInit);
  15423. typedef void (WINAPI * MA_PFN_CoUninitialize)(void);
  15424. typedef HRESULT (WINAPI * MA_PFN_CoCreateInstance)(const IID* rclsid, void* pUnkOuter, DWORD dwClsContext, const IID* riid, void* ppv);
  15425. typedef void (WINAPI * MA_PFN_CoTaskMemFree)(void* pv);
  15426. typedef HRESULT (WINAPI * MA_PFN_PropVariantClear)(MA_PROPVARIANT *pvar);
  15427. typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, WCHAR* lpsz, int cchMax);
  15428. typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(void);
  15429. typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(void);
  15430. #if defined(MA_WIN32_DESKTOP)
  15431. /* Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. */
  15432. typedef LONG (WINAPI * MA_PFN_RegOpenKeyExA)(HKEY hKey, const char* lpSubKey, DWORD ulOptions, DWORD samDesired, HKEY* phkResult);
  15433. typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey);
  15434. typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, const char* lpValueName, DWORD* lpReserved, DWORD* lpType, BYTE* lpData, DWORD* lpcbData);
  15435. #endif /* MA_WIN32_DESKTOP */
  15436. MA_API size_t ma_strlen_WCHAR(const WCHAR* str)
  15437. {
  15438. size_t len = 0;
  15439. while (str[len] != '\0') {
  15440. len += 1;
  15441. }
  15442. return len;
  15443. }
  15444. MA_API int ma_strcmp_WCHAR(const WCHAR *s1, const WCHAR *s2)
  15445. {
  15446. while (*s1 != '\0' && *s1 == *s2) {
  15447. s1 += 1;
  15448. s2 += 1;
  15449. }
  15450. return *s1 - *s2;
  15451. }
  15452. MA_API int ma_strcpy_s_WCHAR(WCHAR* dst, size_t dstCap, const WCHAR* src)
  15453. {
  15454. size_t i;
  15455. if (dst == 0) {
  15456. return 22;
  15457. }
  15458. if (dstCap == 0) {
  15459. return 34;
  15460. }
  15461. if (src == 0) {
  15462. dst[0] = '\0';
  15463. return 22;
  15464. }
  15465. for (i = 0; i < dstCap && src[i] != '\0'; ++i) {
  15466. dst[i] = src[i];
  15467. }
  15468. if (i < dstCap) {
  15469. dst[i] = '\0';
  15470. return 0;
  15471. }
  15472. dst[0] = '\0';
  15473. return 34;
  15474. }
  15475. #endif /* MA_WIN32 */
  15476. #define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device"
  15477. #define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device"
  15478. /*******************************************************************************
  15479. Timing
  15480. *******************************************************************************/
  15481. #if defined(MA_WIN32) && !defined(MA_POSIX)
  15482. static LARGE_INTEGER g_ma_TimerFrequency; /* <-- Initialized to zero since it's static. */
  15483. static void ma_timer_init(ma_timer* pTimer)
  15484. {
  15485. LARGE_INTEGER counter;
  15486. if (g_ma_TimerFrequency.QuadPart == 0) {
  15487. QueryPerformanceFrequency(&g_ma_TimerFrequency);
  15488. }
  15489. QueryPerformanceCounter(&counter);
  15490. pTimer->counter = counter.QuadPart;
  15491. }
  15492. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15493. {
  15494. LARGE_INTEGER counter;
  15495. if (!QueryPerformanceCounter(&counter)) {
  15496. return 0;
  15497. }
  15498. return (double)(counter.QuadPart - pTimer->counter) / g_ma_TimerFrequency.QuadPart;
  15499. }
  15500. #elif defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
  15501. static ma_uint64 g_ma_TimerFrequency = 0;
  15502. static void ma_timer_init(ma_timer* pTimer)
  15503. {
  15504. mach_timebase_info_data_t baseTime;
  15505. mach_timebase_info(&baseTime);
  15506. g_ma_TimerFrequency = (baseTime.denom * 1e9) / baseTime.numer;
  15507. pTimer->counter = mach_absolute_time();
  15508. }
  15509. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15510. {
  15511. ma_uint64 newTimeCounter = mach_absolute_time();
  15512. ma_uint64 oldTimeCounter = pTimer->counter;
  15513. return (newTimeCounter - oldTimeCounter) / g_ma_TimerFrequency;
  15514. }
  15515. #elif defined(MA_EMSCRIPTEN)
  15516. static MA_INLINE void ma_timer_init(ma_timer* pTimer)
  15517. {
  15518. pTimer->counterD = emscripten_get_now();
  15519. }
  15520. static MA_INLINE double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15521. {
  15522. return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */
  15523. }
  15524. #else
  15525. #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
  15526. #if defined(CLOCK_MONOTONIC)
  15527. #define MA_CLOCK_ID CLOCK_MONOTONIC
  15528. #else
  15529. #define MA_CLOCK_ID CLOCK_REALTIME
  15530. #endif
  15531. static void ma_timer_init(ma_timer* pTimer)
  15532. {
  15533. struct timespec newTime;
  15534. clock_gettime(MA_CLOCK_ID, &newTime);
  15535. pTimer->counter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
  15536. }
  15537. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15538. {
  15539. ma_uint64 newTimeCounter;
  15540. ma_uint64 oldTimeCounter;
  15541. struct timespec newTime;
  15542. clock_gettime(MA_CLOCK_ID, &newTime);
  15543. newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
  15544. oldTimeCounter = pTimer->counter;
  15545. return (newTimeCounter - oldTimeCounter) / 1000000000.0;
  15546. }
  15547. #else
  15548. static void ma_timer_init(ma_timer* pTimer)
  15549. {
  15550. struct timeval newTime;
  15551. gettimeofday(&newTime, NULL);
  15552. pTimer->counter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
  15553. }
  15554. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  15555. {
  15556. ma_uint64 newTimeCounter;
  15557. ma_uint64 oldTimeCounter;
  15558. struct timeval newTime;
  15559. gettimeofday(&newTime, NULL);
  15560. newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
  15561. oldTimeCounter = pTimer->counter;
  15562. return (newTimeCounter - oldTimeCounter) / 1000000.0;
  15563. }
  15564. #endif
  15565. #endif
  15566. #if 0
  15567. static ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn)
  15568. {
  15569. ma_uint32 closestRate = 0;
  15570. ma_uint32 closestDiff = 0xFFFFFFFF;
  15571. size_t iStandardRate;
  15572. for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
  15573. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
  15574. ma_uint32 diff;
  15575. if (sampleRateIn > standardRate) {
  15576. diff = sampleRateIn - standardRate;
  15577. } else {
  15578. diff = standardRate - sampleRateIn;
  15579. }
  15580. if (diff == 0) {
  15581. return standardRate; /* The input sample rate is a standard rate. */
  15582. }
  15583. if (closestDiff > diff) {
  15584. closestDiff = diff;
  15585. closestRate = standardRate;
  15586. }
  15587. }
  15588. return closestRate;
  15589. }
  15590. #endif
  15591. static MA_INLINE unsigned int ma_device_disable_denormals(ma_device* pDevice)
  15592. {
  15593. MA_ASSERT(pDevice != NULL);
  15594. if (!pDevice->noDisableDenormals) {
  15595. return ma_disable_denormals();
  15596. } else {
  15597. return 0;
  15598. }
  15599. }
  15600. static MA_INLINE void ma_device_restore_denormals(ma_device* pDevice, unsigned int prevState)
  15601. {
  15602. MA_ASSERT(pDevice != NULL);
  15603. if (!pDevice->noDisableDenormals) {
  15604. ma_restore_denormals(prevState);
  15605. } else {
  15606. /* Do nothing. */
  15607. (void)prevState;
  15608. }
  15609. }
  15610. static ma_device_notification ma_device_notification_init(ma_device* pDevice, ma_device_notification_type type)
  15611. {
  15612. ma_device_notification notification;
  15613. MA_ZERO_OBJECT(&notification);
  15614. notification.pDevice = pDevice;
  15615. notification.type = type;
  15616. return notification;
  15617. }
  15618. static void ma_device__on_notification(ma_device_notification notification)
  15619. {
  15620. MA_ASSERT(notification.pDevice != NULL);
  15621. if (notification.pDevice->onNotification != NULL) {
  15622. notification.pDevice->onNotification(&notification);
  15623. }
  15624. /* 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. */
  15625. if (notification.pDevice->onStop != NULL && notification.type == ma_device_notification_type_stopped) {
  15626. notification.pDevice->onStop(notification.pDevice);
  15627. }
  15628. }
  15629. static void ma_device__on_notification_started(ma_device* pDevice)
  15630. {
  15631. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_started));
  15632. }
  15633. static void ma_device__on_notification_stopped(ma_device* pDevice)
  15634. {
  15635. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_stopped));
  15636. }
  15637. /* Not all platforms support reroute notifications. */
  15638. #if !defined(MA_EMSCRIPTEN)
  15639. static void ma_device__on_notification_rerouted(ma_device* pDevice)
  15640. {
  15641. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_rerouted));
  15642. }
  15643. #endif
  15644. /* Interruptions are only used on some platforms. */
  15645. #if defined(MA_APPLE_MOBILE)
  15646. static void ma_device__on_notification_interruption_began(ma_device* pDevice)
  15647. {
  15648. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_began));
  15649. }
  15650. static void ma_device__on_notification_interruption_ended(ma_device* pDevice)
  15651. {
  15652. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_ended));
  15653. }
  15654. #endif
  15655. static void ma_device__on_data_inner(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15656. {
  15657. MA_ASSERT(pDevice != NULL);
  15658. MA_ASSERT(pDevice->onData != NULL);
  15659. if (!pDevice->noPreSilencedOutputBuffer && pFramesOut != NULL) {
  15660. ma_silence_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels);
  15661. }
  15662. pDevice->onData(pDevice, pFramesOut, pFramesIn, frameCount);
  15663. }
  15664. static void ma_device__on_data(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15665. {
  15666. MA_ASSERT(pDevice != NULL);
  15667. /* Don't read more data from the client if we're in the process of stopping. */
  15668. if (ma_device_get_state(pDevice) == ma_device_state_stopping) {
  15669. return;
  15670. }
  15671. if (pDevice->noFixedSizedCallback) {
  15672. /* Fast path. Not using a fixed sized callback. Process directly from the specified buffers. */
  15673. ma_device__on_data_inner(pDevice, pFramesOut, pFramesIn, frameCount);
  15674. } else {
  15675. /* Slow path. Using a fixed sized callback. Need to use the intermediary buffer. */
  15676. ma_uint32 totalFramesProcessed = 0;
  15677. while (totalFramesProcessed < frameCount) {
  15678. ma_uint32 totalFramesRemaining = frameCount - totalFramesProcessed;
  15679. ma_uint32 framesToProcessThisIteration = 0;
  15680. if (pFramesIn != NULL) {
  15681. /* Capturing. Write to the intermediary buffer. If there's no room, fire the callback to empty it. */
  15682. if (pDevice->capture.intermediaryBufferLen < pDevice->capture.intermediaryBufferCap) {
  15683. /* There's some room left in the intermediary buffer. Write to it without firing the callback. */
  15684. framesToProcessThisIteration = totalFramesRemaining;
  15685. if (framesToProcessThisIteration > pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen) {
  15686. framesToProcessThisIteration = pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen;
  15687. }
  15688. ma_copy_pcm_frames(
  15689. ma_offset_pcm_frames_ptr(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferLen, pDevice->capture.format, pDevice->capture.channels),
  15690. ma_offset_pcm_frames_const_ptr(pFramesIn, totalFramesProcessed, pDevice->capture.format, pDevice->capture.channels),
  15691. framesToProcessThisIteration,
  15692. pDevice->capture.format, pDevice->capture.channels);
  15693. pDevice->capture.intermediaryBufferLen += framesToProcessThisIteration;
  15694. }
  15695. if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) {
  15696. /* No room left in the intermediary buffer. Fire the data callback. */
  15697. if (pDevice->type == ma_device_type_duplex) {
  15698. /* We'll do the duplex data callback later after we've processed the playback data. */
  15699. } else {
  15700. ma_device__on_data_inner(pDevice, NULL, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap);
  15701. /* The intermediary buffer has just been drained. */
  15702. pDevice->capture.intermediaryBufferLen = 0;
  15703. }
  15704. }
  15705. }
  15706. if (pFramesOut != NULL) {
  15707. /* Playing back. Read from the intermediary buffer. If there's nothing in it, fire the callback to fill it. */
  15708. if (pDevice->playback.intermediaryBufferLen > 0) {
  15709. /* There's some content in the intermediary buffer. Read from that without firing the callback. */
  15710. if (pDevice->type == ma_device_type_duplex) {
  15711. /* The frames processed this iteration for a duplex device will always be based on the capture side. Leave it unmodified. */
  15712. } else {
  15713. framesToProcessThisIteration = totalFramesRemaining;
  15714. if (framesToProcessThisIteration > pDevice->playback.intermediaryBufferLen) {
  15715. framesToProcessThisIteration = pDevice->playback.intermediaryBufferLen;
  15716. }
  15717. }
  15718. ma_copy_pcm_frames(
  15719. ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, pDevice->playback.format, pDevice->playback.channels),
  15720. ma_offset_pcm_frames_ptr(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap - pDevice->playback.intermediaryBufferLen, pDevice->playback.format, pDevice->playback.channels),
  15721. framesToProcessThisIteration,
  15722. pDevice->playback.format, pDevice->playback.channels);
  15723. pDevice->playback.intermediaryBufferLen -= framesToProcessThisIteration;
  15724. }
  15725. if (pDevice->playback.intermediaryBufferLen == 0) {
  15726. /* There's nothing in the intermediary buffer. Fire the data callback to fill it. */
  15727. if (pDevice->type == ma_device_type_duplex) {
  15728. /* In duplex mode, the data callback will be fired later. Nothing to do here. */
  15729. } else {
  15730. ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, NULL, pDevice->playback.intermediaryBufferCap);
  15731. /* The intermediary buffer has just been filled. */
  15732. pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap;
  15733. }
  15734. }
  15735. }
  15736. /* If we're in duplex mode we might need to do a refill of the data. */
  15737. if (pDevice->type == ma_device_type_duplex) {
  15738. if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) {
  15739. ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap);
  15740. pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap; /* The playback buffer will have just been filled. */
  15741. pDevice->capture.intermediaryBufferLen = 0; /* The intermediary buffer has just been drained. */
  15742. }
  15743. }
  15744. /* Make sure this is only incremented once in the duplex case. */
  15745. totalFramesProcessed += framesToProcessThisIteration;
  15746. }
  15747. }
  15748. }
  15749. static void ma_device__handle_data_callback(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15750. {
  15751. float masterVolumeFactor;
  15752. ma_device_get_master_volume(pDevice, &masterVolumeFactor); /* Use ma_device_get_master_volume() to ensure the volume is loaded atomically. */
  15753. if (pDevice->onData) {
  15754. unsigned int prevDenormalState = ma_device_disable_denormals(pDevice);
  15755. {
  15756. /* 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. */
  15757. if (pFramesIn != NULL && masterVolumeFactor < 1) {
  15758. ma_uint8 tempFramesIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15759. ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15760. ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15761. ma_uint32 totalFramesProcessed = 0;
  15762. while (totalFramesProcessed < frameCount) {
  15763. ma_uint32 framesToProcessThisIteration = frameCount - totalFramesProcessed;
  15764. if (framesToProcessThisIteration > sizeof(tempFramesIn)/bpfCapture) {
  15765. framesToProcessThisIteration = sizeof(tempFramesIn)/bpfCapture;
  15766. }
  15767. ma_copy_and_apply_volume_factor_pcm_frames(tempFramesIn, ma_offset_ptr(pFramesIn, totalFramesProcessed*bpfCapture), framesToProcessThisIteration, pDevice->capture.format, pDevice->capture.channels, masterVolumeFactor);
  15768. ma_device__on_data(pDevice, ma_offset_ptr(pFramesOut, totalFramesProcessed*bpfPlayback), tempFramesIn, framesToProcessThisIteration);
  15769. totalFramesProcessed += framesToProcessThisIteration;
  15770. }
  15771. } else {
  15772. ma_device__on_data(pDevice, pFramesOut, pFramesIn, frameCount);
  15773. }
  15774. /* Volume control and clipping for playback devices. */
  15775. if (pFramesOut != NULL) {
  15776. if (masterVolumeFactor < 1) {
  15777. 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. */
  15778. ma_apply_volume_factor_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels, masterVolumeFactor);
  15779. }
  15780. }
  15781. if (!pDevice->noClip && pDevice->playback.format == ma_format_f32) {
  15782. 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. */
  15783. }
  15784. }
  15785. }
  15786. ma_device_restore_denormals(pDevice, prevDenormalState);
  15787. }
  15788. }
  15789. /* A helper function for reading sample data from the client. */
  15790. static void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pFramesOut)
  15791. {
  15792. MA_ASSERT(pDevice != NULL);
  15793. MA_ASSERT(frameCount > 0);
  15794. MA_ASSERT(pFramesOut != NULL);
  15795. if (pDevice->playback.converter.isPassthrough) {
  15796. ma_device__handle_data_callback(pDevice, pFramesOut, NULL, frameCount);
  15797. } else {
  15798. ma_result result;
  15799. ma_uint64 totalFramesReadOut;
  15800. void* pRunningFramesOut;
  15801. totalFramesReadOut = 0;
  15802. pRunningFramesOut = pFramesOut;
  15803. /*
  15804. We run slightly different logic depending on whether or not we're using a heap-allocated
  15805. buffer for caching input data. This will be the case if the data converter does not have
  15806. the ability to retrieve the required input frame count for a given output frame count.
  15807. */
  15808. if (pDevice->playback.pInputCache != NULL) {
  15809. while (totalFramesReadOut < frameCount) {
  15810. ma_uint64 framesToReadThisIterationIn;
  15811. ma_uint64 framesToReadThisIterationOut;
  15812. /* If there's any data available in the cache, that needs to get processed first. */
  15813. if (pDevice->playback.inputCacheRemaining > 0) {
  15814. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  15815. framesToReadThisIterationIn = framesToReadThisIterationOut;
  15816. if (framesToReadThisIterationIn > pDevice->playback.inputCacheRemaining) {
  15817. framesToReadThisIterationIn = pDevice->playback.inputCacheRemaining;
  15818. }
  15819. 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);
  15820. if (result != MA_SUCCESS) {
  15821. break;
  15822. }
  15823. pDevice->playback.inputCacheConsumed += framesToReadThisIterationIn;
  15824. pDevice->playback.inputCacheRemaining -= framesToReadThisIterationIn;
  15825. totalFramesReadOut += framesToReadThisIterationOut;
  15826. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15827. if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) {
  15828. break; /* We're done. */
  15829. }
  15830. }
  15831. /* Getting here means there's no data in the cache and we need to fill it up with data from the client. */
  15832. if (pDevice->playback.inputCacheRemaining == 0) {
  15833. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, NULL, (ma_uint32)pDevice->playback.inputCacheCap);
  15834. pDevice->playback.inputCacheConsumed = 0;
  15835. pDevice->playback.inputCacheRemaining = pDevice->playback.inputCacheCap;
  15836. }
  15837. }
  15838. } else {
  15839. while (totalFramesReadOut < frameCount) {
  15840. ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In client format. */
  15841. ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15842. ma_uint64 framesToReadThisIterationIn;
  15843. ma_uint64 framesReadThisIterationIn;
  15844. ma_uint64 framesToReadThisIterationOut;
  15845. ma_uint64 framesReadThisIterationOut;
  15846. ma_uint64 requiredInputFrameCount;
  15847. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  15848. framesToReadThisIterationIn = framesToReadThisIterationOut;
  15849. if (framesToReadThisIterationIn > intermediaryBufferCap) {
  15850. framesToReadThisIterationIn = intermediaryBufferCap;
  15851. }
  15852. ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, framesToReadThisIterationOut, &requiredInputFrameCount);
  15853. if (framesToReadThisIterationIn > requiredInputFrameCount) {
  15854. framesToReadThisIterationIn = requiredInputFrameCount;
  15855. }
  15856. if (framesToReadThisIterationIn > 0) {
  15857. ma_device__handle_data_callback(pDevice, pIntermediaryBuffer, NULL, (ma_uint32)framesToReadThisIterationIn);
  15858. }
  15859. /*
  15860. 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
  15861. input frames, we still want to try processing frames because there may some output frames generated from cached input data.
  15862. */
  15863. framesReadThisIterationIn = framesToReadThisIterationIn;
  15864. framesReadThisIterationOut = framesToReadThisIterationOut;
  15865. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
  15866. if (result != MA_SUCCESS) {
  15867. break;
  15868. }
  15869. totalFramesReadOut += framesReadThisIterationOut;
  15870. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15871. if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
  15872. break; /* We're done. */
  15873. }
  15874. }
  15875. }
  15876. }
  15877. }
  15878. /* A helper for sending sample data to the client. */
  15879. static void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat)
  15880. {
  15881. MA_ASSERT(pDevice != NULL);
  15882. MA_ASSERT(frameCountInDeviceFormat > 0);
  15883. MA_ASSERT(pFramesInDeviceFormat != NULL);
  15884. if (pDevice->capture.converter.isPassthrough) {
  15885. ma_device__handle_data_callback(pDevice, NULL, pFramesInDeviceFormat, frameCountInDeviceFormat);
  15886. } else {
  15887. ma_result result;
  15888. ma_uint8 pFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15889. ma_uint64 framesInClientFormatCap = sizeof(pFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15890. ma_uint64 totalDeviceFramesProcessed = 0;
  15891. ma_uint64 totalClientFramesProcessed = 0;
  15892. const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
  15893. /* We just keep going until we've exhaused all of our input frames and cannot generate any more output frames. */
  15894. for (;;) {
  15895. ma_uint64 deviceFramesProcessedThisIteration;
  15896. ma_uint64 clientFramesProcessedThisIteration;
  15897. deviceFramesProcessedThisIteration = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
  15898. clientFramesProcessedThisIteration = framesInClientFormatCap;
  15899. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &deviceFramesProcessedThisIteration, pFramesInClientFormat, &clientFramesProcessedThisIteration);
  15900. if (result != MA_SUCCESS) {
  15901. break;
  15902. }
  15903. if (clientFramesProcessedThisIteration > 0) {
  15904. ma_device__handle_data_callback(pDevice, NULL, pFramesInClientFormat, (ma_uint32)clientFramesProcessedThisIteration); /* Safe cast. */
  15905. }
  15906. pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, deviceFramesProcessedThisIteration * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15907. totalDeviceFramesProcessed += deviceFramesProcessedThisIteration;
  15908. totalClientFramesProcessed += clientFramesProcessedThisIteration;
  15909. /* This is just to silence a warning. I might want to use this variable later so leaving in place for now. */
  15910. (void)totalClientFramesProcessed;
  15911. if (deviceFramesProcessedThisIteration == 0 && clientFramesProcessedThisIteration == 0) {
  15912. break; /* We're done. */
  15913. }
  15914. }
  15915. }
  15916. }
  15917. static ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat, ma_pcm_rb* pRB)
  15918. {
  15919. ma_result result;
  15920. ma_uint32 totalDeviceFramesProcessed = 0;
  15921. const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
  15922. MA_ASSERT(pDevice != NULL);
  15923. MA_ASSERT(frameCountInDeviceFormat > 0);
  15924. MA_ASSERT(pFramesInDeviceFormat != NULL);
  15925. MA_ASSERT(pRB != NULL);
  15926. /* Write to the ring buffer. The ring buffer is in the client format which means we need to convert. */
  15927. for (;;) {
  15928. ma_uint32 framesToProcessInDeviceFormat = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
  15929. ma_uint32 framesToProcessInClientFormat = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15930. ma_uint64 framesProcessedInDeviceFormat;
  15931. ma_uint64 framesProcessedInClientFormat;
  15932. void* pFramesInClientFormat;
  15933. result = ma_pcm_rb_acquire_write(pRB, &framesToProcessInClientFormat, &pFramesInClientFormat);
  15934. if (result != MA_SUCCESS) {
  15935. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer.");
  15936. break;
  15937. }
  15938. if (framesToProcessInClientFormat == 0) {
  15939. if (ma_pcm_rb_pointer_distance(pRB) == (ma_int32)ma_pcm_rb_get_subbuffer_size(pRB)) {
  15940. break; /* Overrun. Not enough room in the ring buffer for input frame. Excess frames are dropped. */
  15941. }
  15942. }
  15943. /* Convert. */
  15944. framesProcessedInDeviceFormat = framesToProcessInDeviceFormat;
  15945. framesProcessedInClientFormat = framesToProcessInClientFormat;
  15946. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &framesProcessedInDeviceFormat, pFramesInClientFormat, &framesProcessedInClientFormat);
  15947. if (result != MA_SUCCESS) {
  15948. break;
  15949. }
  15950. result = ma_pcm_rb_commit_write(pRB, (ma_uint32)framesProcessedInClientFormat); /* Safe cast. */
  15951. if (result != MA_SUCCESS) {
  15952. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to commit capture PCM frames to ring buffer.");
  15953. break;
  15954. }
  15955. pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, framesProcessedInDeviceFormat * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15956. totalDeviceFramesProcessed += (ma_uint32)framesProcessedInDeviceFormat; /* Safe cast. */
  15957. /* We're done when we're unable to process any client nor device frames. */
  15958. if (framesProcessedInClientFormat == 0 && framesProcessedInDeviceFormat == 0) {
  15959. break; /* Done. */
  15960. }
  15961. }
  15962. return MA_SUCCESS;
  15963. }
  15964. static ma_result ma_device__handle_duplex_callback_playback(ma_device* pDevice, ma_uint32 frameCount, void* pFramesInInternalFormat, ma_pcm_rb* pRB)
  15965. {
  15966. ma_result result;
  15967. ma_uint8 silentInputFrames[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15968. ma_uint32 totalFramesReadOut = 0;
  15969. MA_ASSERT(pDevice != NULL);
  15970. MA_ASSERT(frameCount > 0);
  15971. MA_ASSERT(pFramesInInternalFormat != NULL);
  15972. MA_ASSERT(pRB != NULL);
  15973. MA_ASSERT(pDevice->playback.pInputCache != NULL);
  15974. /*
  15975. 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
  15976. the whole frameCount frames we just use silence instead for the input data.
  15977. */
  15978. MA_ZERO_MEMORY(silentInputFrames, sizeof(silentInputFrames));
  15979. while (totalFramesReadOut < frameCount && ma_device_is_started(pDevice)) {
  15980. /*
  15981. We should have a buffer allocated on the heap. Any playback frames still sitting in there
  15982. need to be sent to the internal device before we process any more data from the client.
  15983. */
  15984. if (pDevice->playback.inputCacheRemaining > 0) {
  15985. ma_uint64 framesConvertedIn = pDevice->playback.inputCacheRemaining;
  15986. ma_uint64 framesConvertedOut = (frameCount - totalFramesReadOut);
  15987. 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);
  15988. pDevice->playback.inputCacheConsumed += framesConvertedIn;
  15989. pDevice->playback.inputCacheRemaining -= framesConvertedIn;
  15990. totalFramesReadOut += (ma_uint32)framesConvertedOut; /* Safe cast. */
  15991. pFramesInInternalFormat = ma_offset_ptr(pFramesInInternalFormat, framesConvertedOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15992. }
  15993. /* If there's no more data in the cache we'll need to fill it with some. */
  15994. if (totalFramesReadOut < frameCount && pDevice->playback.inputCacheRemaining == 0) {
  15995. ma_uint32 inputFrameCount;
  15996. void* pInputFrames;
  15997. inputFrameCount = (ma_uint32)pDevice->playback.inputCacheCap;
  15998. result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames);
  15999. if (result == MA_SUCCESS) {
  16000. if (inputFrameCount > 0) {
  16001. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, pInputFrames, inputFrameCount);
  16002. } else {
  16003. if (ma_pcm_rb_pointer_distance(pRB) == 0) {
  16004. break; /* Underrun. */
  16005. }
  16006. }
  16007. } else {
  16008. /* No capture data available. Feed in silence. */
  16009. inputFrameCount = (ma_uint32)ma_min(pDevice->playback.inputCacheCap, sizeof(silentInputFrames) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
  16010. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, silentInputFrames, inputFrameCount);
  16011. }
  16012. pDevice->playback.inputCacheConsumed = 0;
  16013. pDevice->playback.inputCacheRemaining = inputFrameCount;
  16014. result = ma_pcm_rb_commit_read(pRB, inputFrameCount);
  16015. if (result != MA_SUCCESS) {
  16016. return result; /* Should never happen. */
  16017. }
  16018. }
  16019. }
  16020. return MA_SUCCESS;
  16021. }
  16022. /* A helper for changing the state of the device. */
  16023. static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_device_state newState)
  16024. {
  16025. ma_atomic_device_state_set(&pDevice->state, newState);
  16026. }
  16027. #if defined(MA_WIN32)
  16028. static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
  16029. static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
  16030. /*static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
  16031. /*static GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
  16032. #endif
  16033. MA_API ma_uint32 ma_get_format_priority_index(ma_format format) /* Lower = better. */
  16034. {
  16035. ma_uint32 i;
  16036. for (i = 0; i < ma_countof(g_maFormatPriorities); ++i) {
  16037. if (g_maFormatPriorities[i] == format) {
  16038. return i;
  16039. }
  16040. }
  16041. /* Getting here means the format could not be found or is equal to ma_format_unknown. */
  16042. return (ma_uint32)-1;
  16043. }
  16044. static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType);
  16045. static ma_bool32 ma_device_descriptor_is_valid(const ma_device_descriptor* pDeviceDescriptor)
  16046. {
  16047. if (pDeviceDescriptor == NULL) {
  16048. return MA_FALSE;
  16049. }
  16050. if (pDeviceDescriptor->format == ma_format_unknown) {
  16051. return MA_FALSE;
  16052. }
  16053. if (pDeviceDescriptor->channels == 0 || pDeviceDescriptor->channels > MA_MAX_CHANNELS) {
  16054. return MA_FALSE;
  16055. }
  16056. if (pDeviceDescriptor->sampleRate == 0) {
  16057. return MA_FALSE;
  16058. }
  16059. return MA_TRUE;
  16060. }
  16061. static ma_result ma_device_audio_thread__default_read_write(ma_device* pDevice)
  16062. {
  16063. ma_result result = MA_SUCCESS;
  16064. ma_bool32 exitLoop = MA_FALSE;
  16065. ma_uint8 capturedDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16066. ma_uint8 playbackDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16067. ma_uint32 capturedDeviceDataCapInFrames = 0;
  16068. ma_uint32 playbackDeviceDataCapInFrames = 0;
  16069. MA_ASSERT(pDevice != NULL);
  16070. /* Just some quick validation on the device type and the available callbacks. */
  16071. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  16072. if (pDevice->pContext->callbacks.onDeviceRead == NULL) {
  16073. return MA_NOT_IMPLEMENTED;
  16074. }
  16075. capturedDeviceDataCapInFrames = sizeof(capturedDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  16076. }
  16077. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  16078. if (pDevice->pContext->callbacks.onDeviceWrite == NULL) {
  16079. return MA_NOT_IMPLEMENTED;
  16080. }
  16081. playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  16082. }
  16083. /* NOTE: The device was started outside of this function, in the worker thread. */
  16084. while (ma_device_get_state(pDevice) == ma_device_state_started && !exitLoop) {
  16085. switch (pDevice->type) {
  16086. case ma_device_type_duplex:
  16087. {
  16088. /* The process is: onDeviceRead() -> convert -> callback -> convert -> onDeviceWrite() */
  16089. ma_uint32 totalCapturedDeviceFramesProcessed = 0;
  16090. ma_uint32 capturedDevicePeriodSizeInFrames = ma_min(pDevice->capture.internalPeriodSizeInFrames, pDevice->playback.internalPeriodSizeInFrames);
  16091. while (totalCapturedDeviceFramesProcessed < capturedDevicePeriodSizeInFrames) {
  16092. ma_uint32 capturedDeviceFramesRemaining;
  16093. ma_uint32 capturedDeviceFramesProcessed;
  16094. ma_uint32 capturedDeviceFramesToProcess;
  16095. ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
  16096. if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
  16097. capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
  16098. }
  16099. result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, capturedDeviceFramesToTryProcessing, &capturedDeviceFramesToProcess);
  16100. if (result != MA_SUCCESS) {
  16101. exitLoop = MA_TRUE;
  16102. break;
  16103. }
  16104. capturedDeviceFramesRemaining = capturedDeviceFramesToProcess;
  16105. capturedDeviceFramesProcessed = 0;
  16106. /* At this point we have our captured data in device format and we now need to convert it to client format. */
  16107. for (;;) {
  16108. ma_uint8 capturedClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16109. ma_uint8 playbackClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  16110. ma_uint32 capturedClientDataCapInFrames = sizeof(capturedClientData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  16111. ma_uint32 playbackClientDataCapInFrames = sizeof(playbackClientData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  16112. ma_uint64 capturedClientFramesToProcessThisIteration = ma_min(capturedClientDataCapInFrames, playbackClientDataCapInFrames);
  16113. ma_uint64 capturedDeviceFramesToProcessThisIteration = capturedDeviceFramesRemaining;
  16114. ma_uint8* pRunningCapturedDeviceFrames = ma_offset_ptr(capturedDeviceData, capturedDeviceFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  16115. /* Convert capture data from device format to client format. */
  16116. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningCapturedDeviceFrames, &capturedDeviceFramesToProcessThisIteration, capturedClientData, &capturedClientFramesToProcessThisIteration);
  16117. if (result != MA_SUCCESS) {
  16118. break;
  16119. }
  16120. /*
  16121. 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
  16122. which should never be the case when it's of the size MA_DATA_CONVERTER_STACK_BUFFER_SIZE.
  16123. */
  16124. if (capturedClientFramesToProcessThisIteration == 0) {
  16125. break;
  16126. }
  16127. ma_device__handle_data_callback(pDevice, playbackClientData, capturedClientData, (ma_uint32)capturedClientFramesToProcessThisIteration); /* Safe cast .*/
  16128. capturedDeviceFramesProcessed += (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
  16129. capturedDeviceFramesRemaining -= (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
  16130. /* At this point the playbackClientData buffer should be holding data that needs to be written to the device. */
  16131. for (;;) {
  16132. ma_uint64 convertedClientFrameCount = capturedClientFramesToProcessThisIteration;
  16133. ma_uint64 convertedDeviceFrameCount = playbackDeviceDataCapInFrames;
  16134. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackClientData, &convertedClientFrameCount, playbackDeviceData, &convertedDeviceFrameCount);
  16135. if (result != MA_SUCCESS) {
  16136. break;
  16137. }
  16138. result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, (ma_uint32)convertedDeviceFrameCount, NULL); /* Safe cast. */
  16139. if (result != MA_SUCCESS) {
  16140. exitLoop = MA_TRUE;
  16141. break;
  16142. }
  16143. capturedClientFramesToProcessThisIteration -= (ma_uint32)convertedClientFrameCount; /* Safe cast. */
  16144. if (capturedClientFramesToProcessThisIteration == 0) {
  16145. break;
  16146. }
  16147. }
  16148. /* In case an error happened from ma_device_write__null()... */
  16149. if (result != MA_SUCCESS) {
  16150. exitLoop = MA_TRUE;
  16151. break;
  16152. }
  16153. }
  16154. /* Make sure we don't get stuck in the inner loop. */
  16155. if (capturedDeviceFramesProcessed == 0) {
  16156. break;
  16157. }
  16158. totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
  16159. }
  16160. } break;
  16161. case ma_device_type_capture:
  16162. case ma_device_type_loopback:
  16163. {
  16164. ma_uint32 periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
  16165. ma_uint32 framesReadThisPeriod = 0;
  16166. while (framesReadThisPeriod < periodSizeInFrames) {
  16167. ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesReadThisPeriod;
  16168. ma_uint32 framesProcessed;
  16169. ma_uint32 framesToReadThisIteration = framesRemainingInPeriod;
  16170. if (framesToReadThisIteration > capturedDeviceDataCapInFrames) {
  16171. framesToReadThisIteration = capturedDeviceDataCapInFrames;
  16172. }
  16173. result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, framesToReadThisIteration, &framesProcessed);
  16174. if (result != MA_SUCCESS) {
  16175. exitLoop = MA_TRUE;
  16176. break;
  16177. }
  16178. /* Make sure we don't get stuck in the inner loop. */
  16179. if (framesProcessed == 0) {
  16180. break;
  16181. }
  16182. ma_device__send_frames_to_client(pDevice, framesProcessed, capturedDeviceData);
  16183. framesReadThisPeriod += framesProcessed;
  16184. }
  16185. } break;
  16186. case ma_device_type_playback:
  16187. {
  16188. /* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
  16189. ma_uint32 periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
  16190. ma_uint32 framesWrittenThisPeriod = 0;
  16191. while (framesWrittenThisPeriod < periodSizeInFrames) {
  16192. ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesWrittenThisPeriod;
  16193. ma_uint32 framesProcessed;
  16194. ma_uint32 framesToWriteThisIteration = framesRemainingInPeriod;
  16195. if (framesToWriteThisIteration > playbackDeviceDataCapInFrames) {
  16196. framesToWriteThisIteration = playbackDeviceDataCapInFrames;
  16197. }
  16198. ma_device__read_frames_from_client(pDevice, framesToWriteThisIteration, playbackDeviceData);
  16199. result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, framesToWriteThisIteration, &framesProcessed);
  16200. if (result != MA_SUCCESS) {
  16201. exitLoop = MA_TRUE;
  16202. break;
  16203. }
  16204. /* Make sure we don't get stuck in the inner loop. */
  16205. if (framesProcessed == 0) {
  16206. break;
  16207. }
  16208. framesWrittenThisPeriod += framesProcessed;
  16209. }
  16210. } break;
  16211. /* Should never get here. */
  16212. default: break;
  16213. }
  16214. }
  16215. return result;
  16216. }
  16217. /*******************************************************************************
  16218. Null Backend
  16219. *******************************************************************************/
  16220. #ifdef MA_HAS_NULL
  16221. #define MA_DEVICE_OP_NONE__NULL 0
  16222. #define MA_DEVICE_OP_START__NULL 1
  16223. #define MA_DEVICE_OP_SUSPEND__NULL 2
  16224. #define MA_DEVICE_OP_KILL__NULL 3
  16225. static ma_thread_result MA_THREADCALL ma_device_thread__null(void* pData)
  16226. {
  16227. ma_device* pDevice = (ma_device*)pData;
  16228. MA_ASSERT(pDevice != NULL);
  16229. for (;;) { /* Keep the thread alive until the device is uninitialized. */
  16230. ma_uint32 operation;
  16231. /* Wait for an operation to be requested. */
  16232. ma_event_wait(&pDevice->null_device.operationEvent);
  16233. /* At this point an event should have been triggered. */
  16234. operation = pDevice->null_device.operation;
  16235. /* Starting the device needs to put the thread into a loop. */
  16236. if (operation == MA_DEVICE_OP_START__NULL) {
  16237. /* Reset the timer just in case. */
  16238. ma_timer_init(&pDevice->null_device.timer);
  16239. /* Getting here means a suspend or kill operation has been requested. */
  16240. pDevice->null_device.operationResult = MA_SUCCESS;
  16241. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16242. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16243. continue;
  16244. }
  16245. /* Suspending the device means we need to stop the timer and just continue the loop. */
  16246. if (operation == MA_DEVICE_OP_SUSPEND__NULL) {
  16247. /* We need to add the current run time to the prior run time, then reset the timer. */
  16248. pDevice->null_device.priorRunTime += ma_timer_get_time_in_seconds(&pDevice->null_device.timer);
  16249. ma_timer_init(&pDevice->null_device.timer);
  16250. /* We're done. */
  16251. pDevice->null_device.operationResult = MA_SUCCESS;
  16252. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16253. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16254. continue;
  16255. }
  16256. /* Killing the device means we need to get out of this loop so that this thread can terminate. */
  16257. if (operation == MA_DEVICE_OP_KILL__NULL) {
  16258. pDevice->null_device.operationResult = MA_SUCCESS;
  16259. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16260. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16261. break;
  16262. }
  16263. /* Getting a signal on a "none" operation probably means an error. Return invalid operation. */
  16264. if (operation == MA_DEVICE_OP_NONE__NULL) {
  16265. 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). */
  16266. pDevice->null_device.operationResult = MA_INVALID_OPERATION;
  16267. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  16268. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  16269. continue; /* Continue the loop. Don't terminate. */
  16270. }
  16271. }
  16272. return (ma_thread_result)0;
  16273. }
  16274. static ma_result ma_device_do_operation__null(ma_device* pDevice, ma_uint32 operation)
  16275. {
  16276. ma_result result;
  16277. /*
  16278. TODO: Need to review this and consider just using mutual exclusion. I think the original motivation
  16279. for this was to just post the event to a queue and return immediately, but that has since changed
  16280. and now this function is synchronous. I think this can be simplified to just use a mutex.
  16281. */
  16282. /*
  16283. 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
  16284. to support queing of operations.
  16285. */
  16286. result = ma_semaphore_wait(&pDevice->null_device.operationSemaphore);
  16287. if (result != MA_SUCCESS) {
  16288. return result; /* Failed to wait for the event. */
  16289. }
  16290. /*
  16291. 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
  16292. signal an event to the worker thread to let it know that it can start work.
  16293. */
  16294. pDevice->null_device.operation = operation;
  16295. /* Once the operation code has been set, the worker thread can start work. */
  16296. if (ma_event_signal(&pDevice->null_device.operationEvent) != MA_SUCCESS) {
  16297. return MA_ERROR;
  16298. }
  16299. /* We want everything to be synchronous so we're going to wait for the worker thread to complete it's operation. */
  16300. if (ma_event_wait(&pDevice->null_device.operationCompletionEvent) != MA_SUCCESS) {
  16301. return MA_ERROR;
  16302. }
  16303. return pDevice->null_device.operationResult;
  16304. }
  16305. static ma_uint64 ma_device_get_total_run_time_in_frames__null(ma_device* pDevice)
  16306. {
  16307. ma_uint32 internalSampleRate;
  16308. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  16309. internalSampleRate = pDevice->capture.internalSampleRate;
  16310. } else {
  16311. internalSampleRate = pDevice->playback.internalSampleRate;
  16312. }
  16313. return (ma_uint64)((pDevice->null_device.priorRunTime + ma_timer_get_time_in_seconds(&pDevice->null_device.timer)) * internalSampleRate);
  16314. }
  16315. static ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  16316. {
  16317. ma_bool32 cbResult = MA_TRUE;
  16318. MA_ASSERT(pContext != NULL);
  16319. MA_ASSERT(callback != NULL);
  16320. /* Playback. */
  16321. if (cbResult) {
  16322. ma_device_info deviceInfo;
  16323. MA_ZERO_OBJECT(&deviceInfo);
  16324. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Playback Device", (size_t)-1);
  16325. deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  16326. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  16327. }
  16328. /* Capture. */
  16329. if (cbResult) {
  16330. ma_device_info deviceInfo;
  16331. MA_ZERO_OBJECT(&deviceInfo);
  16332. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Capture Device", (size_t)-1);
  16333. deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  16334. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  16335. }
  16336. (void)cbResult; /* Silence a static analysis warning. */
  16337. return MA_SUCCESS;
  16338. }
  16339. 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)
  16340. {
  16341. MA_ASSERT(pContext != NULL);
  16342. if (pDeviceID != NULL && pDeviceID->nullbackend != 0) {
  16343. return MA_NO_DEVICE; /* Don't know the device. */
  16344. }
  16345. /* Name / Description */
  16346. if (deviceType == ma_device_type_playback) {
  16347. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1);
  16348. } else {
  16349. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1);
  16350. }
  16351. pDeviceInfo->isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  16352. /* Support everything on the null backend. */
  16353. pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
  16354. pDeviceInfo->nativeDataFormats[0].channels = 0;
  16355. pDeviceInfo->nativeDataFormats[0].sampleRate = 0;
  16356. pDeviceInfo->nativeDataFormats[0].flags = 0;
  16357. pDeviceInfo->nativeDataFormatCount = 1;
  16358. (void)pContext;
  16359. return MA_SUCCESS;
  16360. }
  16361. static ma_result ma_device_uninit__null(ma_device* pDevice)
  16362. {
  16363. MA_ASSERT(pDevice != NULL);
  16364. /* Keep it clean and wait for the device thread to finish before returning. */
  16365. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_KILL__NULL);
  16366. /* Wait for the thread to finish before continuing. */
  16367. ma_thread_wait(&pDevice->null_device.deviceThread);
  16368. /* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */
  16369. ma_semaphore_uninit(&pDevice->null_device.operationSemaphore);
  16370. ma_event_uninit(&pDevice->null_device.operationCompletionEvent);
  16371. ma_event_uninit(&pDevice->null_device.operationEvent);
  16372. return MA_SUCCESS;
  16373. }
  16374. static ma_result ma_device_init__null(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  16375. {
  16376. ma_result result;
  16377. MA_ASSERT(pDevice != NULL);
  16378. MA_ZERO_OBJECT(&pDevice->null_device);
  16379. if (pConfig->deviceType == ma_device_type_loopback) {
  16380. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  16381. }
  16382. /* The null backend supports everything exactly as we specify it. */
  16383. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  16384. pDescriptorCapture->format = (pDescriptorCapture->format != ma_format_unknown) ? pDescriptorCapture->format : MA_DEFAULT_FORMAT;
  16385. pDescriptorCapture->channels = (pDescriptorCapture->channels != 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS;
  16386. pDescriptorCapture->sampleRate = (pDescriptorCapture->sampleRate != 0) ? pDescriptorCapture->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  16387. if (pDescriptorCapture->channelMap[0] == MA_CHANNEL_NONE) {
  16388. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  16389. }
  16390. pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  16391. }
  16392. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  16393. pDescriptorPlayback->format = (pDescriptorPlayback->format != ma_format_unknown) ? pDescriptorPlayback->format : MA_DEFAULT_FORMAT;
  16394. pDescriptorPlayback->channels = (pDescriptorPlayback->channels != 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS;
  16395. pDescriptorPlayback->sampleRate = (pDescriptorPlayback->sampleRate != 0) ? pDescriptorPlayback->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  16396. if (pDescriptorPlayback->channelMap[0] == MA_CHANNEL_NONE) {
  16397. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorPlayback->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorPlayback->channels);
  16398. }
  16399. pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  16400. }
  16401. /*
  16402. 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
  16403. first period is "written" to it, and then stopped in ma_device_stop__null().
  16404. */
  16405. result = ma_event_init(&pDevice->null_device.operationEvent);
  16406. if (result != MA_SUCCESS) {
  16407. return result;
  16408. }
  16409. result = ma_event_init(&pDevice->null_device.operationCompletionEvent);
  16410. if (result != MA_SUCCESS) {
  16411. return result;
  16412. }
  16413. result = ma_semaphore_init(1, &pDevice->null_device.operationSemaphore); /* <-- It's important that the initial value is set to 1. */
  16414. if (result != MA_SUCCESS) {
  16415. return result;
  16416. }
  16417. result = ma_thread_create(&pDevice->null_device.deviceThread, pDevice->pContext->threadPriority, 0, ma_device_thread__null, pDevice, &pDevice->pContext->allocationCallbacks);
  16418. if (result != MA_SUCCESS) {
  16419. return result;
  16420. }
  16421. return MA_SUCCESS;
  16422. }
  16423. static ma_result ma_device_start__null(ma_device* pDevice)
  16424. {
  16425. MA_ASSERT(pDevice != NULL);
  16426. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_START__NULL);
  16427. ma_atomic_bool32_set(&pDevice->null_device.isStarted, MA_TRUE);
  16428. return MA_SUCCESS;
  16429. }
  16430. static ma_result ma_device_stop__null(ma_device* pDevice)
  16431. {
  16432. MA_ASSERT(pDevice != NULL);
  16433. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_SUSPEND__NULL);
  16434. ma_atomic_bool32_set(&pDevice->null_device.isStarted, MA_FALSE);
  16435. return MA_SUCCESS;
  16436. }
  16437. static ma_bool32 ma_device_is_started__null(ma_device* pDevice)
  16438. {
  16439. MA_ASSERT(pDevice != NULL);
  16440. return ma_atomic_bool32_get(&pDevice->null_device.isStarted);
  16441. }
  16442. static ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  16443. {
  16444. ma_result result = MA_SUCCESS;
  16445. ma_uint32 totalPCMFramesProcessed;
  16446. ma_bool32 wasStartedOnEntry;
  16447. if (pFramesWritten != NULL) {
  16448. *pFramesWritten = 0;
  16449. }
  16450. wasStartedOnEntry = ma_device_is_started__null(pDevice);
  16451. /* Keep going until everything has been read. */
  16452. totalPCMFramesProcessed = 0;
  16453. while (totalPCMFramesProcessed < frameCount) {
  16454. ma_uint64 targetFrame;
  16455. /* If there are any frames remaining in the current period, consume those first. */
  16456. if (pDevice->null_device.currentPeriodFramesRemainingPlayback > 0) {
  16457. ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
  16458. ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingPlayback;
  16459. if (framesToProcess > framesRemaining) {
  16460. framesToProcess = framesRemaining;
  16461. }
  16462. /* We don't actually do anything with pPCMFrames, so just mark it as unused to prevent a warning. */
  16463. (void)pPCMFrames;
  16464. pDevice->null_device.currentPeriodFramesRemainingPlayback -= framesToProcess;
  16465. totalPCMFramesProcessed += framesToProcess;
  16466. }
  16467. /* 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. */
  16468. if (pDevice->null_device.currentPeriodFramesRemainingPlayback == 0) {
  16469. pDevice->null_device.currentPeriodFramesRemainingPlayback = 0;
  16470. if (!ma_device_is_started__null(pDevice) && !wasStartedOnEntry) {
  16471. result = ma_device_start__null(pDevice);
  16472. if (result != MA_SUCCESS) {
  16473. break;
  16474. }
  16475. }
  16476. }
  16477. /* If we've consumed the whole buffer we can return now. */
  16478. MA_ASSERT(totalPCMFramesProcessed <= frameCount);
  16479. if (totalPCMFramesProcessed == frameCount) {
  16480. break;
  16481. }
  16482. /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
  16483. targetFrame = pDevice->null_device.lastProcessedFramePlayback;
  16484. for (;;) {
  16485. ma_uint64 currentFrame;
  16486. /* Stop waiting if the device has been stopped. */
  16487. if (!ma_device_is_started__null(pDevice)) {
  16488. break;
  16489. }
  16490. currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
  16491. if (currentFrame >= targetFrame) {
  16492. break;
  16493. }
  16494. /* Getting here means we haven't yet reached the target sample, so continue waiting. */
  16495. ma_sleep(10);
  16496. }
  16497. pDevice->null_device.lastProcessedFramePlayback += pDevice->playback.internalPeriodSizeInFrames;
  16498. pDevice->null_device.currentPeriodFramesRemainingPlayback = pDevice->playback.internalPeriodSizeInFrames;
  16499. }
  16500. if (pFramesWritten != NULL) {
  16501. *pFramesWritten = totalPCMFramesProcessed;
  16502. }
  16503. return result;
  16504. }
  16505. static ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  16506. {
  16507. ma_result result = MA_SUCCESS;
  16508. ma_uint32 totalPCMFramesProcessed;
  16509. if (pFramesRead != NULL) {
  16510. *pFramesRead = 0;
  16511. }
  16512. /* Keep going until everything has been read. */
  16513. totalPCMFramesProcessed = 0;
  16514. while (totalPCMFramesProcessed < frameCount) {
  16515. ma_uint64 targetFrame;
  16516. /* If there are any frames remaining in the current period, consume those first. */
  16517. if (pDevice->null_device.currentPeriodFramesRemainingCapture > 0) {
  16518. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  16519. ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
  16520. ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingCapture;
  16521. if (framesToProcess > framesRemaining) {
  16522. framesToProcess = framesRemaining;
  16523. }
  16524. /* We need to ensure the output buffer is zeroed. */
  16525. MA_ZERO_MEMORY(ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed*bpf), framesToProcess*bpf);
  16526. pDevice->null_device.currentPeriodFramesRemainingCapture -= framesToProcess;
  16527. totalPCMFramesProcessed += framesToProcess;
  16528. }
  16529. /* 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. */
  16530. if (pDevice->null_device.currentPeriodFramesRemainingCapture == 0) {
  16531. pDevice->null_device.currentPeriodFramesRemainingCapture = 0;
  16532. }
  16533. /* If we've consumed the whole buffer we can return now. */
  16534. MA_ASSERT(totalPCMFramesProcessed <= frameCount);
  16535. if (totalPCMFramesProcessed == frameCount) {
  16536. break;
  16537. }
  16538. /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
  16539. targetFrame = pDevice->null_device.lastProcessedFrameCapture + pDevice->capture.internalPeriodSizeInFrames;
  16540. for (;;) {
  16541. ma_uint64 currentFrame;
  16542. /* Stop waiting if the device has been stopped. */
  16543. if (!ma_device_is_started__null(pDevice)) {
  16544. break;
  16545. }
  16546. currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
  16547. if (currentFrame >= targetFrame) {
  16548. break;
  16549. }
  16550. /* Getting here means we haven't yet reached the target sample, so continue waiting. */
  16551. ma_sleep(10);
  16552. }
  16553. pDevice->null_device.lastProcessedFrameCapture += pDevice->capture.internalPeriodSizeInFrames;
  16554. pDevice->null_device.currentPeriodFramesRemainingCapture = pDevice->capture.internalPeriodSizeInFrames;
  16555. }
  16556. if (pFramesRead != NULL) {
  16557. *pFramesRead = totalPCMFramesProcessed;
  16558. }
  16559. return result;
  16560. }
  16561. static ma_result ma_context_uninit__null(ma_context* pContext)
  16562. {
  16563. MA_ASSERT(pContext != NULL);
  16564. MA_ASSERT(pContext->backend == ma_backend_null);
  16565. (void)pContext;
  16566. return MA_SUCCESS;
  16567. }
  16568. static ma_result ma_context_init__null(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  16569. {
  16570. MA_ASSERT(pContext != NULL);
  16571. (void)pConfig;
  16572. (void)pContext;
  16573. pCallbacks->onContextInit = ma_context_init__null;
  16574. pCallbacks->onContextUninit = ma_context_uninit__null;
  16575. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__null;
  16576. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__null;
  16577. pCallbacks->onDeviceInit = ma_device_init__null;
  16578. pCallbacks->onDeviceUninit = ma_device_uninit__null;
  16579. pCallbacks->onDeviceStart = ma_device_start__null;
  16580. pCallbacks->onDeviceStop = ma_device_stop__null;
  16581. pCallbacks->onDeviceRead = ma_device_read__null;
  16582. pCallbacks->onDeviceWrite = ma_device_write__null;
  16583. 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. */
  16584. /* The null backend always works. */
  16585. return MA_SUCCESS;
  16586. }
  16587. #endif
  16588. /*******************************************************************************
  16589. WIN32 COMMON
  16590. *******************************************************************************/
  16591. #if defined(MA_WIN32)
  16592. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16593. #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((pContext->win32.CoInitializeEx) ? ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit) : ((MA_PFN_CoInitialize)pContext->win32.CoInitialize)(pvReserved))
  16594. #define ma_CoUninitialize(pContext) ((MA_PFN_CoUninitialize)pContext->win32.CoUninitialize)()
  16595. #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) ((MA_PFN_CoCreateInstance)pContext->win32.CoCreateInstance)(rclsid, pUnkOuter, dwClsContext, riid, ppv)
  16596. #define ma_CoTaskMemFree(pContext, pv) ((MA_PFN_CoTaskMemFree)pContext->win32.CoTaskMemFree)(pv)
  16597. #define ma_PropVariantClear(pContext, pvar) ((MA_PFN_PropVariantClear)pContext->win32.PropVariantClear)(pvar)
  16598. #else
  16599. #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) CoInitializeEx(pvReserved, dwCoInit)
  16600. #define ma_CoUninitialize(pContext) CoUninitialize()
  16601. #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv)
  16602. #define ma_CoTaskMemFree(pContext, pv) CoTaskMemFree(pv)
  16603. #define ma_PropVariantClear(pContext, pvar) PropVariantClear(pvar)
  16604. #endif
  16605. #if !defined(MAXULONG_PTR) && !defined(__WATCOMC__)
  16606. typedef size_t DWORD_PTR;
  16607. #endif
  16608. #if !defined(WAVE_FORMAT_1M08)
  16609. #define WAVE_FORMAT_1M08 0x00000001
  16610. #define WAVE_FORMAT_1S08 0x00000002
  16611. #define WAVE_FORMAT_1M16 0x00000004
  16612. #define WAVE_FORMAT_1S16 0x00000008
  16613. #define WAVE_FORMAT_2M08 0x00000010
  16614. #define WAVE_FORMAT_2S08 0x00000020
  16615. #define WAVE_FORMAT_2M16 0x00000040
  16616. #define WAVE_FORMAT_2S16 0x00000080
  16617. #define WAVE_FORMAT_4M08 0x00000100
  16618. #define WAVE_FORMAT_4S08 0x00000200
  16619. #define WAVE_FORMAT_4M16 0x00000400
  16620. #define WAVE_FORMAT_4S16 0x00000800
  16621. #endif
  16622. #if !defined(WAVE_FORMAT_44M08)
  16623. #define WAVE_FORMAT_44M08 0x00000100
  16624. #define WAVE_FORMAT_44S08 0x00000200
  16625. #define WAVE_FORMAT_44M16 0x00000400
  16626. #define WAVE_FORMAT_44S16 0x00000800
  16627. #define WAVE_FORMAT_48M08 0x00001000
  16628. #define WAVE_FORMAT_48S08 0x00002000
  16629. #define WAVE_FORMAT_48M16 0x00004000
  16630. #define WAVE_FORMAT_48S16 0x00008000
  16631. #define WAVE_FORMAT_96M08 0x00010000
  16632. #define WAVE_FORMAT_96S08 0x00020000
  16633. #define WAVE_FORMAT_96M16 0x00040000
  16634. #define WAVE_FORMAT_96S16 0x00080000
  16635. #endif
  16636. #ifndef SPEAKER_FRONT_LEFT
  16637. #define SPEAKER_FRONT_LEFT 0x1
  16638. #define SPEAKER_FRONT_RIGHT 0x2
  16639. #define SPEAKER_FRONT_CENTER 0x4
  16640. #define SPEAKER_LOW_FREQUENCY 0x8
  16641. #define SPEAKER_BACK_LEFT 0x10
  16642. #define SPEAKER_BACK_RIGHT 0x20
  16643. #define SPEAKER_FRONT_LEFT_OF_CENTER 0x40
  16644. #define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80
  16645. #define SPEAKER_BACK_CENTER 0x100
  16646. #define SPEAKER_SIDE_LEFT 0x200
  16647. #define SPEAKER_SIDE_RIGHT 0x400
  16648. #define SPEAKER_TOP_CENTER 0x800
  16649. #define SPEAKER_TOP_FRONT_LEFT 0x1000
  16650. #define SPEAKER_TOP_FRONT_CENTER 0x2000
  16651. #define SPEAKER_TOP_FRONT_RIGHT 0x4000
  16652. #define SPEAKER_TOP_BACK_LEFT 0x8000
  16653. #define SPEAKER_TOP_BACK_CENTER 0x10000
  16654. #define SPEAKER_TOP_BACK_RIGHT 0x20000
  16655. #endif
  16656. /*
  16657. Implement our own version of MA_WAVEFORMATEXTENSIBLE so we can avoid a header. Be careful with this
  16658. because MA_WAVEFORMATEX has an extra two bytes over standard WAVEFORMATEX due to padding. The
  16659. standard version uses tight packing, but for compiler compatibility we're not doing that with ours.
  16660. */
  16661. typedef struct
  16662. {
  16663. WORD wFormatTag;
  16664. WORD nChannels;
  16665. DWORD nSamplesPerSec;
  16666. DWORD nAvgBytesPerSec;
  16667. WORD nBlockAlign;
  16668. WORD wBitsPerSample;
  16669. WORD cbSize;
  16670. } MA_WAVEFORMATEX;
  16671. typedef struct
  16672. {
  16673. WORD wFormatTag;
  16674. WORD nChannels;
  16675. DWORD nSamplesPerSec;
  16676. DWORD nAvgBytesPerSec;
  16677. WORD nBlockAlign;
  16678. WORD wBitsPerSample;
  16679. WORD cbSize;
  16680. union
  16681. {
  16682. WORD wValidBitsPerSample;
  16683. WORD wSamplesPerBlock;
  16684. WORD wReserved;
  16685. } Samples;
  16686. DWORD dwChannelMask;
  16687. GUID SubFormat;
  16688. } MA_WAVEFORMATEXTENSIBLE;
  16689. #ifndef WAVE_FORMAT_EXTENSIBLE
  16690. #define WAVE_FORMAT_EXTENSIBLE 0xFFFE
  16691. #endif
  16692. #ifndef WAVE_FORMAT_PCM
  16693. #define WAVE_FORMAT_PCM 1
  16694. #endif
  16695. #ifndef WAVE_FORMAT_IEEE_FLOAT
  16696. #define WAVE_FORMAT_IEEE_FLOAT 0x0003
  16697. #endif
  16698. /* Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
  16699. static ma_uint8 ma_channel_id_to_ma__win32(DWORD id)
  16700. {
  16701. switch (id)
  16702. {
  16703. case SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  16704. case SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  16705. case SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  16706. case SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
  16707. case SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
  16708. case SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  16709. case SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  16710. case SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  16711. case SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
  16712. case SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  16713. case SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  16714. case SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  16715. case SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  16716. case SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  16717. case SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  16718. case SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  16719. case SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  16720. case SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  16721. default: return 0;
  16722. }
  16723. }
  16724. /* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. */
  16725. static DWORD ma_channel_id_to_win32(DWORD id)
  16726. {
  16727. switch (id)
  16728. {
  16729. case MA_CHANNEL_MONO: return SPEAKER_FRONT_CENTER;
  16730. case MA_CHANNEL_FRONT_LEFT: return SPEAKER_FRONT_LEFT;
  16731. case MA_CHANNEL_FRONT_RIGHT: return SPEAKER_FRONT_RIGHT;
  16732. case MA_CHANNEL_FRONT_CENTER: return SPEAKER_FRONT_CENTER;
  16733. case MA_CHANNEL_LFE: return SPEAKER_LOW_FREQUENCY;
  16734. case MA_CHANNEL_BACK_LEFT: return SPEAKER_BACK_LEFT;
  16735. case MA_CHANNEL_BACK_RIGHT: return SPEAKER_BACK_RIGHT;
  16736. case MA_CHANNEL_FRONT_LEFT_CENTER: return SPEAKER_FRONT_LEFT_OF_CENTER;
  16737. case MA_CHANNEL_FRONT_RIGHT_CENTER: return SPEAKER_FRONT_RIGHT_OF_CENTER;
  16738. case MA_CHANNEL_BACK_CENTER: return SPEAKER_BACK_CENTER;
  16739. case MA_CHANNEL_SIDE_LEFT: return SPEAKER_SIDE_LEFT;
  16740. case MA_CHANNEL_SIDE_RIGHT: return SPEAKER_SIDE_RIGHT;
  16741. case MA_CHANNEL_TOP_CENTER: return SPEAKER_TOP_CENTER;
  16742. case MA_CHANNEL_TOP_FRONT_LEFT: return SPEAKER_TOP_FRONT_LEFT;
  16743. case MA_CHANNEL_TOP_FRONT_CENTER: return SPEAKER_TOP_FRONT_CENTER;
  16744. case MA_CHANNEL_TOP_FRONT_RIGHT: return SPEAKER_TOP_FRONT_RIGHT;
  16745. case MA_CHANNEL_TOP_BACK_LEFT: return SPEAKER_TOP_BACK_LEFT;
  16746. case MA_CHANNEL_TOP_BACK_CENTER: return SPEAKER_TOP_BACK_CENTER;
  16747. case MA_CHANNEL_TOP_BACK_RIGHT: return SPEAKER_TOP_BACK_RIGHT;
  16748. default: return 0;
  16749. }
  16750. }
  16751. /* Converts a channel mapping to a Win32-style channel mask. */
  16752. static DWORD ma_channel_map_to_channel_mask__win32(const ma_channel* pChannelMap, ma_uint32 channels)
  16753. {
  16754. DWORD dwChannelMask = 0;
  16755. ma_uint32 iChannel;
  16756. for (iChannel = 0; iChannel < channels; ++iChannel) {
  16757. dwChannelMask |= ma_channel_id_to_win32(pChannelMap[iChannel]);
  16758. }
  16759. return dwChannelMask;
  16760. }
  16761. /* Converts a Win32-style channel mask to a miniaudio channel map. */
  16762. static void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel* pChannelMap)
  16763. {
  16764. /* If the channel mask is set to 0, just assume a default Win32 channel map. */
  16765. if (dwChannelMask == 0) {
  16766. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channels, channels);
  16767. } else {
  16768. if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) {
  16769. pChannelMap[0] = MA_CHANNEL_MONO;
  16770. } else {
  16771. /* Just iterate over each bit. */
  16772. ma_uint32 iChannel = 0;
  16773. ma_uint32 iBit;
  16774. for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
  16775. DWORD bitValue = (dwChannelMask & (1UL << iBit));
  16776. if (bitValue != 0) {
  16777. /* The bit is set. */
  16778. pChannelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue);
  16779. iChannel += 1;
  16780. }
  16781. }
  16782. }
  16783. }
  16784. }
  16785. #ifdef __cplusplus
  16786. static ma_bool32 ma_is_guid_equal(const void* a, const void* b)
  16787. {
  16788. return IsEqualGUID(*(const GUID*)a, *(const GUID*)b);
  16789. }
  16790. #else
  16791. #define ma_is_guid_equal(a, b) IsEqualGUID((const GUID*)a, (const GUID*)b)
  16792. #endif
  16793. static MA_INLINE ma_bool32 ma_is_guid_null(const void* guid)
  16794. {
  16795. static GUID nullguid = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
  16796. return ma_is_guid_equal(guid, &nullguid);
  16797. }
  16798. static ma_format ma_format_from_WAVEFORMATEX(const MA_WAVEFORMATEX* pWF)
  16799. {
  16800. MA_ASSERT(pWF != NULL);
  16801. if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  16802. const MA_WAVEFORMATEXTENSIBLE* pWFEX = (const MA_WAVEFORMATEXTENSIBLE*)pWF;
  16803. if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_PCM)) {
  16804. if (pWFEX->Samples.wValidBitsPerSample == 32) {
  16805. return ma_format_s32;
  16806. }
  16807. if (pWFEX->Samples.wValidBitsPerSample == 24) {
  16808. if (pWFEX->wBitsPerSample == 32) {
  16809. return ma_format_s32;
  16810. }
  16811. if (pWFEX->wBitsPerSample == 24) {
  16812. return ma_format_s24;
  16813. }
  16814. }
  16815. if (pWFEX->Samples.wValidBitsPerSample == 16) {
  16816. return ma_format_s16;
  16817. }
  16818. if (pWFEX->Samples.wValidBitsPerSample == 8) {
  16819. return ma_format_u8;
  16820. }
  16821. }
  16822. if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
  16823. if (pWFEX->Samples.wValidBitsPerSample == 32) {
  16824. return ma_format_f32;
  16825. }
  16826. /*
  16827. if (pWFEX->Samples.wValidBitsPerSample == 64) {
  16828. return ma_format_f64;
  16829. }
  16830. */
  16831. }
  16832. } else {
  16833. if (pWF->wFormatTag == WAVE_FORMAT_PCM) {
  16834. if (pWF->wBitsPerSample == 32) {
  16835. return ma_format_s32;
  16836. }
  16837. if (pWF->wBitsPerSample == 24) {
  16838. return ma_format_s24;
  16839. }
  16840. if (pWF->wBitsPerSample == 16) {
  16841. return ma_format_s16;
  16842. }
  16843. if (pWF->wBitsPerSample == 8) {
  16844. return ma_format_u8;
  16845. }
  16846. }
  16847. if (pWF->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
  16848. if (pWF->wBitsPerSample == 32) {
  16849. return ma_format_f32;
  16850. }
  16851. if (pWF->wBitsPerSample == 64) {
  16852. /*return ma_format_f64;*/
  16853. }
  16854. }
  16855. }
  16856. return ma_format_unknown;
  16857. }
  16858. #endif
  16859. /*******************************************************************************
  16860. WASAPI Backend
  16861. *******************************************************************************/
  16862. #ifdef MA_HAS_WASAPI
  16863. #if 0
  16864. #if defined(_MSC_VER)
  16865. #pragma warning(push)
  16866. #pragma warning(disable:4091) /* 'typedef ': ignored on left of '' when no variable is declared */
  16867. #endif
  16868. #include <audioclient.h>
  16869. #include <mmdeviceapi.h>
  16870. #if defined(_MSC_VER)
  16871. #pragma warning(pop)
  16872. #endif
  16873. #endif /* 0 */
  16874. static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType);
  16875. /* Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. */
  16876. #define MA_WIN32_WINNT_VISTA 0x0600
  16877. #define MA_VER_MINORVERSION 0x01
  16878. #define MA_VER_MAJORVERSION 0x02
  16879. #define MA_VER_SERVICEPACKMAJOR 0x20
  16880. #define MA_VER_GREATER_EQUAL 0x03
  16881. typedef struct {
  16882. DWORD dwOSVersionInfoSize;
  16883. DWORD dwMajorVersion;
  16884. DWORD dwMinorVersion;
  16885. DWORD dwBuildNumber;
  16886. DWORD dwPlatformId;
  16887. WCHAR szCSDVersion[128];
  16888. WORD wServicePackMajor;
  16889. WORD wServicePackMinor;
  16890. WORD wSuiteMask;
  16891. BYTE wProductType;
  16892. BYTE wReserved;
  16893. } ma_OSVERSIONINFOEXW;
  16894. typedef BOOL (WINAPI * ma_PFNVerifyVersionInfoW) (ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask);
  16895. typedef ULONGLONG (WINAPI * ma_PFNVerSetConditionMask)(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask);
  16896. #ifndef PROPERTYKEY_DEFINED
  16897. #define PROPERTYKEY_DEFINED
  16898. #ifndef __WATCOMC__
  16899. typedef struct
  16900. {
  16901. GUID fmtid;
  16902. DWORD pid;
  16903. } PROPERTYKEY;
  16904. #endif
  16905. #endif
  16906. /* Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). */
  16907. static MA_INLINE void ma_PropVariantInit(MA_PROPVARIANT* pProp)
  16908. {
  16909. MA_ZERO_OBJECT(pProp);
  16910. }
  16911. static const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14};
  16912. static const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0};
  16913. static const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; /* 00000000-0000-0000-C000-000000000046 */
  16914. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16915. static const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; /* 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 */
  16916. #endif
  16917. static const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; /* 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) */
  16918. static const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; /* 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) */
  16919. static const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; /* 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) */
  16920. static const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; /* F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) */
  16921. static const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; /* C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) */
  16922. static const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; /* 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) */
  16923. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16924. static const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; /* E6327CAD-DCEC-4949-AE8A-991E976A79D2 */
  16925. static const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; /* 2EEF81BE-33FA-4800-9670-1CD474972C3F */
  16926. static const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; /* 41D949AB-9862-444A-80F6-C261334DA5EB */
  16927. #endif
  16928. static const IID MA_CLSID_MMDeviceEnumerator = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; /* BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) */
  16929. static const IID MA_IID_IMMDeviceEnumerator = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; /* A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) */
  16930. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16931. #define MA_MM_DEVICE_STATE_ACTIVE 1
  16932. #define MA_MM_DEVICE_STATE_DISABLED 2
  16933. #define MA_MM_DEVICE_STATE_NOTPRESENT 4
  16934. #define MA_MM_DEVICE_STATE_UNPLUGGED 8
  16935. typedef struct ma_IMMDeviceEnumerator ma_IMMDeviceEnumerator;
  16936. typedef struct ma_IMMDeviceCollection ma_IMMDeviceCollection;
  16937. typedef struct ma_IMMDevice ma_IMMDevice;
  16938. #else
  16939. typedef struct ma_IActivateAudioInterfaceCompletionHandler ma_IActivateAudioInterfaceCompletionHandler;
  16940. typedef struct ma_IActivateAudioInterfaceAsyncOperation ma_IActivateAudioInterfaceAsyncOperation;
  16941. #endif
  16942. typedef struct ma_IPropertyStore ma_IPropertyStore;
  16943. typedef struct ma_IAudioClient ma_IAudioClient;
  16944. typedef struct ma_IAudioClient2 ma_IAudioClient2;
  16945. typedef struct ma_IAudioClient3 ma_IAudioClient3;
  16946. typedef struct ma_IAudioRenderClient ma_IAudioRenderClient;
  16947. typedef struct ma_IAudioCaptureClient ma_IAudioCaptureClient;
  16948. typedef ma_int64 MA_REFERENCE_TIME;
  16949. #define MA_AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000
  16950. #define MA_AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000
  16951. #define MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000
  16952. #define MA_AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000
  16953. #define MA_AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
  16954. #define MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  16955. #define MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  16956. #define MA_AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000
  16957. #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000
  16958. #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000
  16959. /* Buffer flags. */
  16960. #define MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY 1
  16961. #define MA_AUDCLNT_BUFFERFLAGS_SILENT 2
  16962. #define MA_AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR 4
  16963. typedef enum
  16964. {
  16965. ma_eRender = 0,
  16966. ma_eCapture = 1,
  16967. ma_eAll = 2
  16968. } ma_EDataFlow;
  16969. typedef enum
  16970. {
  16971. ma_eConsole = 0,
  16972. ma_eMultimedia = 1,
  16973. ma_eCommunications = 2
  16974. } ma_ERole;
  16975. typedef enum
  16976. {
  16977. MA_AUDCLNT_SHAREMODE_SHARED,
  16978. MA_AUDCLNT_SHAREMODE_EXCLUSIVE
  16979. } MA_AUDCLNT_SHAREMODE;
  16980. typedef enum
  16981. {
  16982. MA_AudioCategory_Other = 0 /* <-- miniaudio is only caring about Other. */
  16983. } MA_AUDIO_STREAM_CATEGORY;
  16984. typedef struct
  16985. {
  16986. ma_uint32 cbSize;
  16987. BOOL bIsOffload;
  16988. MA_AUDIO_STREAM_CATEGORY eCategory;
  16989. } ma_AudioClientProperties;
  16990. /* IUnknown */
  16991. typedef struct
  16992. {
  16993. /* IUnknown */
  16994. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IUnknown* pThis, const IID* const riid, void** ppObject);
  16995. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IUnknown* pThis);
  16996. ULONG (STDMETHODCALLTYPE * Release) (ma_IUnknown* pThis);
  16997. } ma_IUnknownVtbl;
  16998. struct ma_IUnknown
  16999. {
  17000. ma_IUnknownVtbl* lpVtbl;
  17001. };
  17002. static MA_INLINE HRESULT ma_IUnknown_QueryInterface(ma_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17003. static MA_INLINE ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17004. static MA_INLINE ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); }
  17005. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17006. /* IMMNotificationClient */
  17007. typedef struct
  17008. {
  17009. /* IUnknown */
  17010. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject);
  17011. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMNotificationClient* pThis);
  17012. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMNotificationClient* pThis);
  17013. /* IMMNotificationClient */
  17014. HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, DWORD dwNewState);
  17015. HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID);
  17016. HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID);
  17017. HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, const WCHAR* pDefaultDeviceID);
  17018. HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, const PROPERTYKEY key);
  17019. } ma_IMMNotificationClientVtbl;
  17020. /* IMMDeviceEnumerator */
  17021. typedef struct
  17022. {
  17023. /* IUnknown */
  17024. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject);
  17025. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceEnumerator* pThis);
  17026. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceEnumerator* pThis);
  17027. /* IMMDeviceEnumerator */
  17028. HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices);
  17029. HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint);
  17030. HRESULT (STDMETHODCALLTYPE * GetDevice) (ma_IMMDeviceEnumerator* pThis, const WCHAR* pID, ma_IMMDevice** ppDevice);
  17031. HRESULT (STDMETHODCALLTYPE * RegisterEndpointNotificationCallback) (ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
  17032. HRESULT (STDMETHODCALLTYPE * UnregisterEndpointNotificationCallback)(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
  17033. } ma_IMMDeviceEnumeratorVtbl;
  17034. struct ma_IMMDeviceEnumerator
  17035. {
  17036. ma_IMMDeviceEnumeratorVtbl* lpVtbl;
  17037. };
  17038. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_QueryInterface(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17039. static MA_INLINE ULONG ma_IMMDeviceEnumerator_AddRef(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17040. static MA_INLINE ULONG ma_IMMDeviceEnumerator_Release(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); }
  17041. 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); }
  17042. 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); }
  17043. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDevice(ma_IMMDeviceEnumerator* pThis, const WCHAR* pID, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); }
  17044. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); }
  17045. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); }
  17046. /* IMMDeviceCollection */
  17047. typedef struct
  17048. {
  17049. /* IUnknown */
  17050. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject);
  17051. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceCollection* pThis);
  17052. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceCollection* pThis);
  17053. /* IMMDeviceCollection */
  17054. HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IMMDeviceCollection* pThis, UINT* pDevices);
  17055. HRESULT (STDMETHODCALLTYPE * Item) (ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice);
  17056. } ma_IMMDeviceCollectionVtbl;
  17057. struct ma_IMMDeviceCollection
  17058. {
  17059. ma_IMMDeviceCollectionVtbl* lpVtbl;
  17060. };
  17061. static MA_INLINE HRESULT ma_IMMDeviceCollection_QueryInterface(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17062. static MA_INLINE ULONG ma_IMMDeviceCollection_AddRef(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17063. static MA_INLINE ULONG ma_IMMDeviceCollection_Release(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); }
  17064. static MA_INLINE HRESULT ma_IMMDeviceCollection_GetCount(ma_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); }
  17065. static MA_INLINE HRESULT ma_IMMDeviceCollection_Item(ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); }
  17066. /* IMMDevice */
  17067. typedef struct
  17068. {
  17069. /* IUnknown */
  17070. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDevice* pThis, const IID* const riid, void** ppObject);
  17071. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDevice* pThis);
  17072. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDevice* pThis);
  17073. /* IMMDevice */
  17074. HRESULT (STDMETHODCALLTYPE * Activate) (ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, MA_PROPVARIANT* pActivationParams, void** ppInterface);
  17075. HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties);
  17076. HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, WCHAR** pID);
  17077. HRESULT (STDMETHODCALLTYPE * GetState) (ma_IMMDevice* pThis, DWORD *pState);
  17078. } ma_IMMDeviceVtbl;
  17079. struct ma_IMMDevice
  17080. {
  17081. ma_IMMDeviceVtbl* lpVtbl;
  17082. };
  17083. static MA_INLINE HRESULT ma_IMMDevice_QueryInterface(ma_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17084. static MA_INLINE ULONG ma_IMMDevice_AddRef(ma_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17085. static MA_INLINE ULONG ma_IMMDevice_Release(ma_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); }
  17086. 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); }
  17087. static MA_INLINE HRESULT ma_IMMDevice_OpenPropertyStore(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); }
  17088. static MA_INLINE HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, WCHAR** pID) { return pThis->lpVtbl->GetId(pThis, pID); }
  17089. static MA_INLINE HRESULT ma_IMMDevice_GetState(ma_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); }
  17090. #else
  17091. /* IActivateAudioInterfaceAsyncOperation */
  17092. typedef struct
  17093. {
  17094. /* IUnknown */
  17095. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject);
  17096. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
  17097. ULONG (STDMETHODCALLTYPE * Release) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
  17098. /* IActivateAudioInterfaceAsyncOperation */
  17099. HRESULT (STDMETHODCALLTYPE * GetActivateResult)(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface);
  17100. } ma_IActivateAudioInterfaceAsyncOperationVtbl;
  17101. struct ma_IActivateAudioInterfaceAsyncOperation
  17102. {
  17103. ma_IActivateAudioInterfaceAsyncOperationVtbl* lpVtbl;
  17104. };
  17105. static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_QueryInterface(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17106. static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_AddRef(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17107. static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_Release(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); }
  17108. static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); }
  17109. #endif
  17110. /* IPropertyStore */
  17111. typedef struct
  17112. {
  17113. /* IUnknown */
  17114. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject);
  17115. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IPropertyStore* pThis);
  17116. ULONG (STDMETHODCALLTYPE * Release) (ma_IPropertyStore* pThis);
  17117. /* IPropertyStore */
  17118. HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IPropertyStore* pThis, DWORD* pPropCount);
  17119. HRESULT (STDMETHODCALLTYPE * GetAt) (ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey);
  17120. HRESULT (STDMETHODCALLTYPE * GetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, MA_PROPVARIANT* pPropVar);
  17121. HRESULT (STDMETHODCALLTYPE * SetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const MA_PROPVARIANT* const pPropVar);
  17122. HRESULT (STDMETHODCALLTYPE * Commit) (ma_IPropertyStore* pThis);
  17123. } ma_IPropertyStoreVtbl;
  17124. struct ma_IPropertyStore
  17125. {
  17126. ma_IPropertyStoreVtbl* lpVtbl;
  17127. };
  17128. static MA_INLINE HRESULT ma_IPropertyStore_QueryInterface(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17129. static MA_INLINE ULONG ma_IPropertyStore_AddRef(ma_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17130. static MA_INLINE ULONG ma_IPropertyStore_Release(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); }
  17131. static MA_INLINE HRESULT ma_IPropertyStore_GetCount(ma_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); }
  17132. static MA_INLINE HRESULT ma_IPropertyStore_GetAt(ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); }
  17133. static MA_INLINE HRESULT ma_IPropertyStore_GetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, MA_PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); }
  17134. 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); }
  17135. static MA_INLINE HRESULT ma_IPropertyStore_Commit(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); }
  17136. /* IAudioClient */
  17137. typedef struct
  17138. {
  17139. /* IUnknown */
  17140. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient* pThis, const IID* const riid, void** ppObject);
  17141. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient* pThis);
  17142. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient* pThis);
  17143. /* IAudioClient */
  17144. 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);
  17145. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames);
  17146. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency);
  17147. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames);
  17148. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch);
  17149. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient* pThis, MA_WAVEFORMATEX** ppDeviceFormat);
  17150. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  17151. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient* pThis);
  17152. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient* pThis);
  17153. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient* pThis);
  17154. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient* pThis, HANDLE eventHandle);
  17155. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient* pThis, const IID* const riid, void** pp);
  17156. } ma_IAudioClientVtbl;
  17157. struct ma_IAudioClient
  17158. {
  17159. ma_IAudioClientVtbl* lpVtbl;
  17160. };
  17161. static MA_INLINE HRESULT ma_IAudioClient_QueryInterface(ma_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17162. static MA_INLINE ULONG ma_IAudioClient_AddRef(ma_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17163. static MA_INLINE ULONG ma_IAudioClient_Release(ma_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  17164. 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); }
  17165. static MA_INLINE HRESULT ma_IAudioClient_GetBufferSize(ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  17166. static MA_INLINE HRESULT ma_IAudioClient_GetStreamLatency(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  17167. static MA_INLINE HRESULT ma_IAudioClient_GetCurrentPadding(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  17168. 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); }
  17169. static MA_INLINE HRESULT ma_IAudioClient_GetMixFormat(ma_IAudioClient* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  17170. 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); }
  17171. static MA_INLINE HRESULT ma_IAudioClient_Start(ma_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); }
  17172. static MA_INLINE HRESULT ma_IAudioClient_Stop(ma_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); }
  17173. static MA_INLINE HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); }
  17174. static MA_INLINE HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  17175. static MA_INLINE HRESULT ma_IAudioClient_GetService(ma_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  17176. /* IAudioClient2 */
  17177. typedef struct
  17178. {
  17179. /* IUnknown */
  17180. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject);
  17181. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient2* pThis);
  17182. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient2* pThis);
  17183. /* IAudioClient */
  17184. 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);
  17185. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames);
  17186. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency);
  17187. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames);
  17188. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch);
  17189. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient2* pThis, MA_WAVEFORMATEX** ppDeviceFormat);
  17190. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  17191. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient2* pThis);
  17192. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient2* pThis);
  17193. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient2* pThis);
  17194. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient2* pThis, HANDLE eventHandle);
  17195. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient2* pThis, const IID* const riid, void** pp);
  17196. /* IAudioClient2 */
  17197. HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
  17198. HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties);
  17199. HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient2* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
  17200. } ma_IAudioClient2Vtbl;
  17201. struct ma_IAudioClient2
  17202. {
  17203. ma_IAudioClient2Vtbl* lpVtbl;
  17204. };
  17205. static MA_INLINE HRESULT ma_IAudioClient2_QueryInterface(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17206. static MA_INLINE ULONG ma_IAudioClient2_AddRef(ma_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17207. static MA_INLINE ULONG ma_IAudioClient2_Release(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); }
  17208. 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); }
  17209. static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSize(ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  17210. static MA_INLINE HRESULT ma_IAudioClient2_GetStreamLatency(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  17211. static MA_INLINE HRESULT ma_IAudioClient2_GetCurrentPadding(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  17212. 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); }
  17213. static MA_INLINE HRESULT ma_IAudioClient2_GetMixFormat(ma_IAudioClient2* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  17214. 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); }
  17215. static MA_INLINE HRESULT ma_IAudioClient2_Start(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); }
  17216. static MA_INLINE HRESULT ma_IAudioClient2_Stop(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); }
  17217. static MA_INLINE HRESULT ma_IAudioClient2_Reset(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); }
  17218. static MA_INLINE HRESULT ma_IAudioClient2_SetEventHandle(ma_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  17219. static MA_INLINE HRESULT ma_IAudioClient2_GetService(ma_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  17220. static MA_INLINE HRESULT ma_IAudioClient2_IsOffloadCapable(ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
  17221. static MA_INLINE HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
  17222. 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); }
  17223. /* IAudioClient3 */
  17224. typedef struct
  17225. {
  17226. /* IUnknown */
  17227. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject);
  17228. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient3* pThis);
  17229. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient3* pThis);
  17230. /* IAudioClient */
  17231. 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);
  17232. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames);
  17233. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency);
  17234. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames);
  17235. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const MA_WAVEFORMATEX* pFormat, MA_WAVEFORMATEX** ppClosestMatch);
  17236. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppDeviceFormat);
  17237. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  17238. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient3* pThis);
  17239. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient3* pThis);
  17240. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient3* pThis);
  17241. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient3* pThis, HANDLE eventHandle);
  17242. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient3* pThis, const IID* const riid, void** pp);
  17243. /* IAudioClient2 */
  17244. HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
  17245. HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties);
  17246. HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
  17247. /* IAudioClient3 */
  17248. HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const MA_WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames);
  17249. HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames);
  17250. HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const MA_WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  17251. } ma_IAudioClient3Vtbl;
  17252. struct ma_IAudioClient3
  17253. {
  17254. ma_IAudioClient3Vtbl* lpVtbl;
  17255. };
  17256. static MA_INLINE HRESULT ma_IAudioClient3_QueryInterface(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17257. static MA_INLINE ULONG ma_IAudioClient3_AddRef(ma_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17258. static MA_INLINE ULONG ma_IAudioClient3_Release(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); }
  17259. 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); }
  17260. static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSize(ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  17261. static MA_INLINE HRESULT ma_IAudioClient3_GetStreamLatency(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  17262. static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentPadding(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  17263. 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); }
  17264. static MA_INLINE HRESULT ma_IAudioClient3_GetMixFormat(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  17265. 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); }
  17266. static MA_INLINE HRESULT ma_IAudioClient3_Start(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); }
  17267. static MA_INLINE HRESULT ma_IAudioClient3_Stop(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); }
  17268. static MA_INLINE HRESULT ma_IAudioClient3_Reset(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); }
  17269. static MA_INLINE HRESULT ma_IAudioClient3_SetEventHandle(ma_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  17270. static MA_INLINE HRESULT ma_IAudioClient3_GetService(ma_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  17271. static MA_INLINE HRESULT ma_IAudioClient3_IsOffloadCapable(ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
  17272. static MA_INLINE HRESULT ma_IAudioClient3_SetClientProperties(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
  17273. 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); }
  17274. 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); }
  17275. static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThis, MA_WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); }
  17276. 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); }
  17277. /* IAudioRenderClient */
  17278. typedef struct
  17279. {
  17280. /* IUnknown */
  17281. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject);
  17282. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioRenderClient* pThis);
  17283. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioRenderClient* pThis);
  17284. /* IAudioRenderClient */
  17285. HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData);
  17286. HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags);
  17287. } ma_IAudioRenderClientVtbl;
  17288. struct ma_IAudioRenderClient
  17289. {
  17290. ma_IAudioRenderClientVtbl* lpVtbl;
  17291. };
  17292. static MA_INLINE HRESULT ma_IAudioRenderClient_QueryInterface(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17293. static MA_INLINE ULONG ma_IAudioRenderClient_AddRef(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17294. static MA_INLINE ULONG ma_IAudioRenderClient_Release(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  17295. static MA_INLINE HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); }
  17296. static MA_INLINE HRESULT ma_IAudioRenderClient_ReleaseBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); }
  17297. /* IAudioCaptureClient */
  17298. typedef struct
  17299. {
  17300. /* IUnknown */
  17301. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject);
  17302. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioCaptureClient* pThis);
  17303. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioCaptureClient* pThis);
  17304. /* IAudioRenderClient */
  17305. HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition);
  17306. HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead);
  17307. HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket);
  17308. } ma_IAudioCaptureClientVtbl;
  17309. struct ma_IAudioCaptureClient
  17310. {
  17311. ma_IAudioCaptureClientVtbl* lpVtbl;
  17312. };
  17313. static MA_INLINE HRESULT ma_IAudioCaptureClient_QueryInterface(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  17314. static MA_INLINE ULONG ma_IAudioCaptureClient_AddRef(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  17315. static MA_INLINE ULONG ma_IAudioCaptureClient_Release(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  17316. 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); }
  17317. static MA_INLINE HRESULT ma_IAudioCaptureClient_ReleaseBuffer(ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); }
  17318. static MA_INLINE HRESULT ma_IAudioCaptureClient_GetNextPacketSize(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); }
  17319. #if defined(MA_WIN32_UWP)
  17320. /* mmdevapi Functions */
  17321. typedef HRESULT (WINAPI * MA_PFN_ActivateAudioInterfaceAsync)(const wchar_t* deviceInterfacePath, const IID* riid, MA_PROPVARIANT* activationParams, ma_IActivateAudioInterfaceCompletionHandler* completionHandler, ma_IActivateAudioInterfaceAsyncOperation** activationOperation);
  17322. #endif
  17323. /* Avrt Functions */
  17324. typedef HANDLE (WINAPI * MA_PFN_AvSetMmThreadCharacteristicsA)(const char* TaskName, DWORD* TaskIndex);
  17325. typedef BOOL (WINAPI * MA_PFN_AvRevertMmThreadCharacteristics)(HANDLE AvrtHandle);
  17326. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  17327. typedef struct ma_completion_handler_uwp ma_completion_handler_uwp;
  17328. typedef struct
  17329. {
  17330. /* IUnknown */
  17331. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject);
  17332. ULONG (STDMETHODCALLTYPE * AddRef) (ma_completion_handler_uwp* pThis);
  17333. ULONG (STDMETHODCALLTYPE * Release) (ma_completion_handler_uwp* pThis);
  17334. /* IActivateAudioInterfaceCompletionHandler */
  17335. HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation);
  17336. } ma_completion_handler_uwp_vtbl;
  17337. struct ma_completion_handler_uwp
  17338. {
  17339. ma_completion_handler_uwp_vtbl* lpVtbl;
  17340. MA_ATOMIC(4, ma_uint32) counter;
  17341. HANDLE hEvent;
  17342. };
  17343. static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_QueryInterface(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject)
  17344. {
  17345. /*
  17346. We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To
  17347. "implement" this, we just make sure we return pThis when the IAgileObject is requested.
  17348. */
  17349. 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)) {
  17350. *ppObject = NULL;
  17351. return E_NOINTERFACE;
  17352. }
  17353. /* Getting here means the IID is IUnknown or IMMNotificationClient. */
  17354. *ppObject = (void*)pThis;
  17355. ((ma_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis);
  17356. return S_OK;
  17357. }
  17358. static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_AddRef(ma_completion_handler_uwp* pThis)
  17359. {
  17360. return (ULONG)ma_atomic_fetch_add_32(&pThis->counter, 1) + 1;
  17361. }
  17362. static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_uwp* pThis)
  17363. {
  17364. ma_uint32 newRefCount = ma_atomic_fetch_sub_32(&pThis->counter, 1) - 1;
  17365. if (newRefCount == 0) {
  17366. return 0; /* We don't free anything here because we never allocate the object on the heap. */
  17367. }
  17368. return (ULONG)newRefCount;
  17369. }
  17370. static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_ActivateCompleted(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation)
  17371. {
  17372. (void)pActivateOperation;
  17373. SetEvent(pThis->hEvent);
  17374. return S_OK;
  17375. }
  17376. static ma_completion_handler_uwp_vtbl g_maCompletionHandlerVtblInstance = {
  17377. ma_completion_handler_uwp_QueryInterface,
  17378. ma_completion_handler_uwp_AddRef,
  17379. ma_completion_handler_uwp_Release,
  17380. ma_completion_handler_uwp_ActivateCompleted
  17381. };
  17382. static ma_result ma_completion_handler_uwp_init(ma_completion_handler_uwp* pHandler)
  17383. {
  17384. MA_ASSERT(pHandler != NULL);
  17385. MA_ZERO_OBJECT(pHandler);
  17386. pHandler->lpVtbl = &g_maCompletionHandlerVtblInstance;
  17387. pHandler->counter = 1;
  17388. pHandler->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
  17389. if (pHandler->hEvent == NULL) {
  17390. return ma_result_from_GetLastError(GetLastError());
  17391. }
  17392. return MA_SUCCESS;
  17393. }
  17394. static void ma_completion_handler_uwp_uninit(ma_completion_handler_uwp* pHandler)
  17395. {
  17396. if (pHandler->hEvent != NULL) {
  17397. CloseHandle(pHandler->hEvent);
  17398. }
  17399. }
  17400. static void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler)
  17401. {
  17402. WaitForSingleObject((HANDLE)pHandler->hEvent, INFINITE);
  17403. }
  17404. #endif /* !MA_WIN32_DESKTOP */
  17405. /* We need a virtual table for our notification client object that's used for detecting changes to the default device. */
  17406. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17407. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_QueryInterface(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject)
  17408. {
  17409. /*
  17410. We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else
  17411. we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK.
  17412. */
  17413. if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IMMNotificationClient)) {
  17414. *ppObject = NULL;
  17415. return E_NOINTERFACE;
  17416. }
  17417. /* Getting here means the IID is IUnknown or IMMNotificationClient. */
  17418. *ppObject = (void*)pThis;
  17419. ((ma_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis);
  17420. return S_OK;
  17421. }
  17422. static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_AddRef(ma_IMMNotificationClient* pThis)
  17423. {
  17424. return (ULONG)ma_atomic_fetch_add_32(&pThis->counter, 1) + 1;
  17425. }
  17426. static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClient* pThis)
  17427. {
  17428. ma_uint32 newRefCount = ma_atomic_fetch_sub_32(&pThis->counter, 1) - 1;
  17429. if (newRefCount == 0) {
  17430. return 0; /* We don't free anything here because we never allocate the object on the heap. */
  17431. }
  17432. return (ULONG)newRefCount;
  17433. }
  17434. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceStateChanged(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, DWORD dwNewState)
  17435. {
  17436. ma_bool32 isThisDevice = MA_FALSE;
  17437. ma_bool32 isCapture = MA_FALSE;
  17438. ma_bool32 isPlayback = MA_FALSE;
  17439. #ifdef MA_DEBUG_OUTPUT
  17440. /*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);*/
  17441. #endif
  17442. /*
  17443. 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
  17444. that the device is disabled or has been unplugged.
  17445. */
  17446. 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)) {
  17447. isCapture = MA_TRUE;
  17448. if (ma_strcmp_WCHAR(pThis->pDevice->capture.id.wasapi, pDeviceID) == 0) {
  17449. isThisDevice = MA_TRUE;
  17450. }
  17451. }
  17452. if (pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting && (pThis->pDevice->type == ma_device_type_playback || pThis->pDevice->type == ma_device_type_duplex)) {
  17453. isPlayback = MA_TRUE;
  17454. if (ma_strcmp_WCHAR(pThis->pDevice->playback.id.wasapi, pDeviceID) == 0) {
  17455. isThisDevice = MA_TRUE;
  17456. }
  17457. }
  17458. /*
  17459. If the device ID matches our device we need to mark our device as detached and stop it. When a
  17460. device is added in OnDeviceAdded(), we'll restart it. We only mark it as detached if the device
  17461. was started at the time of being removed.
  17462. */
  17463. if (isThisDevice) {
  17464. if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) == 0) {
  17465. /*
  17466. Unplugged or otherwise unavailable. Mark as detached if we were in a playing state. We'll
  17467. use this to determine whether or not we need to automatically start the device when it's
  17468. plugged back in again.
  17469. */
  17470. if (ma_device_get_state(pThis->pDevice) == ma_device_state_started) {
  17471. if (isPlayback) {
  17472. pThis->pDevice->wasapi.isDetachedPlayback = MA_TRUE;
  17473. }
  17474. if (isCapture) {
  17475. pThis->pDevice->wasapi.isDetachedCapture = MA_TRUE;
  17476. }
  17477. ma_device_stop(pThis->pDevice);
  17478. }
  17479. }
  17480. if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) != 0) {
  17481. /* The device was activated. If we were detached, we need to start it again. */
  17482. ma_bool8 tryRestartingDevice = MA_FALSE;
  17483. if (isPlayback) {
  17484. if (pThis->pDevice->wasapi.isDetachedPlayback) {
  17485. pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE;
  17486. ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback);
  17487. tryRestartingDevice = MA_TRUE;
  17488. }
  17489. }
  17490. if (isCapture) {
  17491. if (pThis->pDevice->wasapi.isDetachedCapture) {
  17492. pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE;
  17493. ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
  17494. tryRestartingDevice = MA_TRUE;
  17495. }
  17496. }
  17497. if (tryRestartingDevice) {
  17498. if (pThis->pDevice->wasapi.isDetachedPlayback == MA_FALSE && pThis->pDevice->wasapi.isDetachedCapture == MA_FALSE) {
  17499. ma_device_start(pThis->pDevice);
  17500. }
  17501. }
  17502. }
  17503. }
  17504. return S_OK;
  17505. }
  17506. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID)
  17507. {
  17508. #ifdef MA_DEBUG_OUTPUT
  17509. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  17510. #endif
  17511. /* We don't need to worry about this event for our purposes. */
  17512. (void)pThis;
  17513. (void)pDeviceID;
  17514. return S_OK;
  17515. }
  17516. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID)
  17517. {
  17518. #ifdef MA_DEBUG_OUTPUT
  17519. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  17520. #endif
  17521. /* We don't need to worry about this event for our purposes. */
  17522. (void)pThis;
  17523. (void)pDeviceID;
  17524. return S_OK;
  17525. }
  17526. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, const WCHAR* pDefaultDeviceID)
  17527. {
  17528. #ifdef MA_DEBUG_OUTPUT
  17529. /*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)");*/
  17530. #endif
  17531. (void)role;
  17532. /* We only care about devices with the same data flow as the current device. */
  17533. if ((pThis->pDevice->type == ma_device_type_playback && dataFlow != ma_eRender) ||
  17534. (pThis->pDevice->type == ma_device_type_capture && dataFlow != ma_eCapture) ||
  17535. (pThis->pDevice->type == ma_device_type_loopback && dataFlow != ma_eRender)) {
  17536. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because dataFlow does match device type.\n");
  17537. return S_OK;
  17538. }
  17539. /* We need to consider dataFlow as ma_eCapture if device is ma_device_type_loopback */
  17540. if (pThis->pDevice->type == ma_device_type_loopback) {
  17541. dataFlow = ma_eCapture;
  17542. }
  17543. /* Don't do automatic stream routing if we're not allowed. */
  17544. if ((dataFlow == ma_eRender && pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting == MA_FALSE) ||
  17545. (dataFlow == ma_eCapture && pThis->pDevice->wasapi.allowCaptureAutoStreamRouting == MA_FALSE)) {
  17546. 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");
  17547. return S_OK;
  17548. }
  17549. /*
  17550. Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to
  17551. AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once
  17552. it's fixed.
  17553. */
  17554. if ((dataFlow == ma_eRender && pThis->pDevice->playback.shareMode == ma_share_mode_exclusive) ||
  17555. (dataFlow == ma_eCapture && pThis->pDevice->capture.shareMode == ma_share_mode_exclusive)) {
  17556. 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");
  17557. return S_OK;
  17558. }
  17559. /*
  17560. Second attempt at device rerouting. We're going to retrieve the device's state at the time of
  17561. the route change. We're then going to stop the device, reinitialize the device, and then start
  17562. it again if the state before stopping was ma_device_state_started.
  17563. */
  17564. {
  17565. ma_uint32 previousState = ma_device_get_state(pThis->pDevice);
  17566. ma_bool8 restartDevice = MA_FALSE;
  17567. if (previousState == ma_device_state_uninitialized || previousState == ma_device_state_starting) {
  17568. 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");
  17569. return S_OK;
  17570. }
  17571. if (previousState == ma_device_state_started) {
  17572. ma_device_stop(pThis->pDevice);
  17573. restartDevice = MA_TRUE;
  17574. }
  17575. if (pDefaultDeviceID != NULL) { /* <-- The input device ID will be null if there's no other device available. */
  17576. ma_mutex_lock(&pThis->pDevice->wasapi.rerouteLock);
  17577. {
  17578. if (dataFlow == ma_eRender) {
  17579. ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback);
  17580. if (pThis->pDevice->wasapi.isDetachedPlayback) {
  17581. pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE;
  17582. if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedCapture) {
  17583. restartDevice = MA_FALSE; /* It's a duplex device and the capture side is detached. We cannot be restarting the device just yet. */
  17584. }
  17585. else {
  17586. 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. */
  17587. }
  17588. }
  17589. }
  17590. else {
  17591. ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
  17592. if (pThis->pDevice->wasapi.isDetachedCapture) {
  17593. pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE;
  17594. if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedPlayback) {
  17595. restartDevice = MA_FALSE; /* It's a duplex device and the playback side is detached. We cannot be restarting the device just yet. */
  17596. }
  17597. else {
  17598. 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. */
  17599. }
  17600. }
  17601. }
  17602. }
  17603. ma_mutex_unlock(&pThis->pDevice->wasapi.rerouteLock);
  17604. if (restartDevice) {
  17605. ma_device_start(pThis->pDevice);
  17606. }
  17607. }
  17608. }
  17609. return S_OK;
  17610. }
  17611. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnPropertyValueChanged(ma_IMMNotificationClient* pThis, const WCHAR* pDeviceID, const PROPERTYKEY key)
  17612. {
  17613. #ifdef MA_DEBUG_OUTPUT
  17614. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnPropertyValueChanged(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  17615. #endif
  17616. (void)pThis;
  17617. (void)pDeviceID;
  17618. (void)key;
  17619. return S_OK;
  17620. }
  17621. static ma_IMMNotificationClientVtbl g_maNotificationCientVtbl = {
  17622. ma_IMMNotificationClient_QueryInterface,
  17623. ma_IMMNotificationClient_AddRef,
  17624. ma_IMMNotificationClient_Release,
  17625. ma_IMMNotificationClient_OnDeviceStateChanged,
  17626. ma_IMMNotificationClient_OnDeviceAdded,
  17627. ma_IMMNotificationClient_OnDeviceRemoved,
  17628. ma_IMMNotificationClient_OnDefaultDeviceChanged,
  17629. ma_IMMNotificationClient_OnPropertyValueChanged
  17630. };
  17631. #endif /* MA_WIN32_DESKTOP */
  17632. static const char* ma_to_usage_string__wasapi(ma_wasapi_usage usage)
  17633. {
  17634. switch (usage)
  17635. {
  17636. case ma_wasapi_usage_default: return NULL;
  17637. case ma_wasapi_usage_games: return "Games";
  17638. case ma_wasapi_usage_pro_audio: return "Pro Audio";
  17639. default: break;
  17640. }
  17641. return NULL;
  17642. }
  17643. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17644. typedef ma_IMMDevice ma_WASAPIDeviceInterface;
  17645. #else
  17646. typedef ma_IUnknown ma_WASAPIDeviceInterface;
  17647. #endif
  17648. #define MA_CONTEXT_COMMAND_QUIT__WASAPI 1
  17649. #define MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI 2
  17650. #define MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI 3
  17651. static ma_context_command__wasapi ma_context_init_command__wasapi(int code)
  17652. {
  17653. ma_context_command__wasapi cmd;
  17654. MA_ZERO_OBJECT(&cmd);
  17655. cmd.code = code;
  17656. return cmd;
  17657. }
  17658. static ma_result ma_context_post_command__wasapi(ma_context* pContext, const ma_context_command__wasapi* pCmd)
  17659. {
  17660. /* For now we are doing everything synchronously, but I might relax this later if the need arises. */
  17661. ma_result result;
  17662. ma_bool32 isUsingLocalEvent = MA_FALSE;
  17663. ma_event localEvent;
  17664. MA_ASSERT(pContext != NULL);
  17665. MA_ASSERT(pCmd != NULL);
  17666. if (pCmd->pEvent == NULL) {
  17667. isUsingLocalEvent = MA_TRUE;
  17668. result = ma_event_init(&localEvent);
  17669. if (result != MA_SUCCESS) {
  17670. return result; /* Failed to create the event for this command. */
  17671. }
  17672. }
  17673. /* Here is where we add the command to the list. If there's not enough room we'll spin until there is. */
  17674. ma_mutex_lock(&pContext->wasapi.commandLock);
  17675. {
  17676. ma_uint32 index;
  17677. /* Spin until we've got some space available. */
  17678. while (pContext->wasapi.commandCount == ma_countof(pContext->wasapi.commands)) {
  17679. ma_yield();
  17680. }
  17681. /* Space is now available. Can safely add to the list. */
  17682. index = (pContext->wasapi.commandIndex + pContext->wasapi.commandCount) % ma_countof(pContext->wasapi.commands);
  17683. pContext->wasapi.commands[index] = *pCmd;
  17684. pContext->wasapi.commands[index].pEvent = &localEvent;
  17685. pContext->wasapi.commandCount += 1;
  17686. /* Now that the command has been added, release the semaphore so ma_context_next_command__wasapi() can return. */
  17687. ma_semaphore_release(&pContext->wasapi.commandSem);
  17688. }
  17689. ma_mutex_unlock(&pContext->wasapi.commandLock);
  17690. if (isUsingLocalEvent) {
  17691. ma_event_wait(&localEvent);
  17692. ma_event_uninit(&localEvent);
  17693. }
  17694. return MA_SUCCESS;
  17695. }
  17696. static ma_result ma_context_next_command__wasapi(ma_context* pContext, ma_context_command__wasapi* pCmd)
  17697. {
  17698. ma_result result = MA_SUCCESS;
  17699. MA_ASSERT(pContext != NULL);
  17700. MA_ASSERT(pCmd != NULL);
  17701. result = ma_semaphore_wait(&pContext->wasapi.commandSem);
  17702. if (result == MA_SUCCESS) {
  17703. ma_mutex_lock(&pContext->wasapi.commandLock);
  17704. {
  17705. *pCmd = pContext->wasapi.commands[pContext->wasapi.commandIndex];
  17706. pContext->wasapi.commandIndex = (pContext->wasapi.commandIndex + 1) % ma_countof(pContext->wasapi.commands);
  17707. pContext->wasapi.commandCount -= 1;
  17708. }
  17709. ma_mutex_unlock(&pContext->wasapi.commandLock);
  17710. }
  17711. return result;
  17712. }
  17713. static ma_thread_result MA_THREADCALL ma_context_command_thread__wasapi(void* pUserData)
  17714. {
  17715. ma_result result;
  17716. ma_context* pContext = (ma_context*)pUserData;
  17717. MA_ASSERT(pContext != NULL);
  17718. for (;;) {
  17719. ma_context_command__wasapi cmd;
  17720. result = ma_context_next_command__wasapi(pContext, &cmd);
  17721. if (result != MA_SUCCESS) {
  17722. break;
  17723. }
  17724. switch (cmd.code)
  17725. {
  17726. case MA_CONTEXT_COMMAND_QUIT__WASAPI:
  17727. {
  17728. /* Do nothing. Handled after the switch. */
  17729. } break;
  17730. case MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI:
  17731. {
  17732. if (cmd.data.createAudioClient.deviceType == ma_device_type_playback) {
  17733. *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioRenderClient, cmd.data.createAudioClient.ppAudioClientService));
  17734. } else {
  17735. *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioCaptureClient, cmd.data.createAudioClient.ppAudioClientService));
  17736. }
  17737. } break;
  17738. case MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI:
  17739. {
  17740. if (cmd.data.releaseAudioClient.deviceType == ma_device_type_playback) {
  17741. if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback != NULL) {
  17742. ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback);
  17743. cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback = NULL;
  17744. }
  17745. }
  17746. if (cmd.data.releaseAudioClient.deviceType == ma_device_type_capture) {
  17747. if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture != NULL) {
  17748. ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture);
  17749. cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture = NULL;
  17750. }
  17751. }
  17752. } break;
  17753. default:
  17754. {
  17755. /* Unknown command. Ignore it, but trigger an assert in debug mode so we're aware of it. */
  17756. MA_ASSERT(MA_FALSE);
  17757. } break;
  17758. }
  17759. if (cmd.pEvent != NULL) {
  17760. ma_event_signal(cmd.pEvent);
  17761. }
  17762. if (cmd.code == MA_CONTEXT_COMMAND_QUIT__WASAPI) {
  17763. break; /* Received a quit message. Get out of here. */
  17764. }
  17765. }
  17766. return (ma_thread_result)0;
  17767. }
  17768. static ma_result ma_device_create_IAudioClient_service__wasapi(ma_context* pContext, ma_device_type deviceType, ma_IAudioClient* pAudioClient, void** ppAudioClientService)
  17769. {
  17770. ma_result result;
  17771. ma_result cmdResult;
  17772. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI);
  17773. cmd.data.createAudioClient.deviceType = deviceType;
  17774. cmd.data.createAudioClient.pAudioClient = (void*)pAudioClient;
  17775. cmd.data.createAudioClient.ppAudioClientService = ppAudioClientService;
  17776. cmd.data.createAudioClient.pResult = &cmdResult; /* Declared locally, but won't be dereferenced after this function returns since execution of the command will wait here. */
  17777. result = ma_context_post_command__wasapi(pContext, &cmd); /* This will not return until the command has actually been run. */
  17778. if (result != MA_SUCCESS) {
  17779. return result;
  17780. }
  17781. return *cmd.data.createAudioClient.pResult;
  17782. }
  17783. #if 0 /* Not used at the moment, but leaving here for future use. */
  17784. static ma_result ma_device_release_IAudioClient_service__wasapi(ma_device* pDevice, ma_device_type deviceType)
  17785. {
  17786. ma_result result;
  17787. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI);
  17788. cmd.data.releaseAudioClient.pDevice = pDevice;
  17789. cmd.data.releaseAudioClient.deviceType = deviceType;
  17790. result = ma_context_post_command__wasapi(pDevice->pContext, &cmd); /* This will not return until the command has actually been run. */
  17791. if (result != MA_SUCCESS) {
  17792. return result;
  17793. }
  17794. return MA_SUCCESS;
  17795. }
  17796. #endif
  17797. static void ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(const MA_WAVEFORMATEX* pWF, ma_share_mode shareMode, ma_device_info* pInfo)
  17798. {
  17799. MA_ASSERT(pWF != NULL);
  17800. MA_ASSERT(pInfo != NULL);
  17801. if (pInfo->nativeDataFormatCount >= ma_countof(pInfo->nativeDataFormats)) {
  17802. return; /* Too many data formats. Need to ignore this one. Don't think this should ever happen with WASAPI. */
  17803. }
  17804. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].format = ma_format_from_WAVEFORMATEX(pWF);
  17805. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].channels = pWF->nChannels;
  17806. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].sampleRate = pWF->nSamplesPerSec;
  17807. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].flags = (shareMode == ma_share_mode_exclusive) ? MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE : 0;
  17808. pInfo->nativeDataFormatCount += 1;
  17809. }
  17810. 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)
  17811. {
  17812. HRESULT hr;
  17813. MA_WAVEFORMATEX* pWF = NULL;
  17814. MA_ASSERT(pAudioClient != NULL);
  17815. MA_ASSERT(pInfo != NULL);
  17816. /* Shared Mode. We use GetMixFormat() here. */
  17817. hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (MA_WAVEFORMATEX**)&pWF);
  17818. if (SUCCEEDED(hr)) {
  17819. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_shared, pInfo);
  17820. } else {
  17821. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.");
  17822. return ma_result_from_HRESULT(hr);
  17823. }
  17824. /*
  17825. Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently supported on
  17826. UWP. Failure to retrieve the exclusive mode format is not considered an error, so from here on
  17827. out, MA_SUCCESS is guaranteed to be returned.
  17828. */
  17829. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17830. {
  17831. ma_IPropertyStore *pProperties;
  17832. /*
  17833. The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is
  17834. correct which will simplify our searching.
  17835. */
  17836. hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties);
  17837. if (SUCCEEDED(hr)) {
  17838. MA_PROPVARIANT var;
  17839. ma_PropVariantInit(&var);
  17840. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_AudioEngine_DeviceFormat, &var);
  17841. if (SUCCEEDED(hr)) {
  17842. pWF = (MA_WAVEFORMATEX*)var.blob.pBlobData;
  17843. /*
  17844. In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format
  17845. first. If this fails, fall back to a search.
  17846. */
  17847. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL);
  17848. if (SUCCEEDED(hr)) {
  17849. /* The format returned by PKEY_AudioEngine_DeviceFormat is supported. */
  17850. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_exclusive, pInfo);
  17851. } else {
  17852. /*
  17853. The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel
  17854. count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format.
  17855. */
  17856. ma_uint32 channels = pWF->nChannels;
  17857. ma_channel defaultChannelMap[MA_MAX_CHANNELS];
  17858. MA_WAVEFORMATEXTENSIBLE wf;
  17859. ma_bool32 found;
  17860. ma_uint32 iFormat;
  17861. /* Make sure we don't overflow the channel map. */
  17862. if (channels > MA_MAX_CHANNELS) {
  17863. channels = MA_MAX_CHANNELS;
  17864. }
  17865. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, defaultChannelMap, ma_countof(defaultChannelMap), channels);
  17866. MA_ZERO_OBJECT(&wf);
  17867. wf.cbSize = sizeof(wf);
  17868. wf.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  17869. wf.nChannels = (WORD)channels;
  17870. wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels);
  17871. found = MA_FALSE;
  17872. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) {
  17873. ma_format format = g_maFormatPriorities[iFormat];
  17874. ma_uint32 iSampleRate;
  17875. wf.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
  17876. wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8);
  17877. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  17878. wf.Samples.wValidBitsPerSample = /*(format == ma_format_s24_32) ? 24 :*/ wf.wBitsPerSample;
  17879. if (format == ma_format_f32) {
  17880. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  17881. } else {
  17882. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  17883. }
  17884. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) {
  17885. wf.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate];
  17886. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (MA_WAVEFORMATEX*)&wf, NULL);
  17887. if (SUCCEEDED(hr)) {
  17888. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX((MA_WAVEFORMATEX*)&wf, ma_share_mode_exclusive, pInfo);
  17889. found = MA_TRUE;
  17890. break;
  17891. }
  17892. }
  17893. if (found) {
  17894. break;
  17895. }
  17896. }
  17897. ma_PropVariantClear(pContext, &var);
  17898. if (!found) {
  17899. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to find suitable device format for device info retrieval.");
  17900. }
  17901. }
  17902. } else {
  17903. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to retrieve device format for device info retrieval.");
  17904. }
  17905. ma_IPropertyStore_Release(pProperties);
  17906. } else {
  17907. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to open property store for device info retrieval.");
  17908. }
  17909. }
  17910. #else
  17911. {
  17912. (void)pMMDevice; /* Unused. */
  17913. }
  17914. #endif
  17915. return MA_SUCCESS;
  17916. }
  17917. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17918. static ma_EDataFlow ma_device_type_to_EDataFlow(ma_device_type deviceType)
  17919. {
  17920. if (deviceType == ma_device_type_playback) {
  17921. return ma_eRender;
  17922. } else if (deviceType == ma_device_type_capture) {
  17923. return ma_eCapture;
  17924. } else {
  17925. MA_ASSERT(MA_FALSE);
  17926. return ma_eRender; /* Should never hit this. */
  17927. }
  17928. }
  17929. static ma_result ma_context_create_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator** ppDeviceEnumerator)
  17930. {
  17931. HRESULT hr;
  17932. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17933. MA_ASSERT(pContext != NULL);
  17934. MA_ASSERT(ppDeviceEnumerator != NULL);
  17935. *ppDeviceEnumerator = NULL; /* Safety. */
  17936. hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17937. if (FAILED(hr)) {
  17938. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  17939. return ma_result_from_HRESULT(hr);
  17940. }
  17941. *ppDeviceEnumerator = pDeviceEnumerator;
  17942. return MA_SUCCESS;
  17943. }
  17944. static WCHAR* ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType)
  17945. {
  17946. HRESULT hr;
  17947. ma_IMMDevice* pMMDefaultDevice = NULL;
  17948. WCHAR* pDefaultDeviceID = NULL;
  17949. ma_EDataFlow dataFlow;
  17950. ma_ERole role;
  17951. MA_ASSERT(pContext != NULL);
  17952. MA_ASSERT(pDeviceEnumerator != NULL);
  17953. (void)pContext;
  17954. /* Grab the EDataFlow type from the device type. */
  17955. dataFlow = ma_device_type_to_EDataFlow(deviceType);
  17956. /* The role is always eConsole, but we may make this configurable later. */
  17957. role = ma_eConsole;
  17958. hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, dataFlow, role, &pMMDefaultDevice);
  17959. if (FAILED(hr)) {
  17960. return NULL;
  17961. }
  17962. hr = ma_IMMDevice_GetId(pMMDefaultDevice, &pDefaultDeviceID);
  17963. ma_IMMDevice_Release(pMMDefaultDevice);
  17964. pMMDefaultDevice = NULL;
  17965. if (FAILED(hr)) {
  17966. return NULL;
  17967. }
  17968. return pDefaultDeviceID;
  17969. }
  17970. static WCHAR* ma_context_get_default_device_id__wasapi(ma_context* pContext, ma_device_type deviceType) /* Free the returned pointer with ma_CoTaskMemFree() */
  17971. {
  17972. ma_result result;
  17973. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17974. WCHAR* pDefaultDeviceID = NULL;
  17975. MA_ASSERT(pContext != NULL);
  17976. result = ma_context_create_IMMDeviceEnumerator__wasapi(pContext, &pDeviceEnumerator);
  17977. if (result != MA_SUCCESS) {
  17978. return NULL;
  17979. }
  17980. pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
  17981. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  17982. return pDefaultDeviceID;
  17983. }
  17984. static ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IMMDevice** ppMMDevice)
  17985. {
  17986. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17987. HRESULT hr;
  17988. MA_ASSERT(pContext != NULL);
  17989. MA_ASSERT(ppMMDevice != NULL);
  17990. hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17991. if (FAILED(hr)) {
  17992. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.\n");
  17993. return ma_result_from_HRESULT(hr);
  17994. }
  17995. if (pDeviceID == NULL) {
  17996. hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == ma_device_type_capture) ? ma_eCapture : ma_eRender, ma_eConsole, ppMMDevice);
  17997. } else {
  17998. hr = ma_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice);
  17999. }
  18000. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  18001. if (FAILED(hr)) {
  18002. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.\n");
  18003. return ma_result_from_HRESULT(hr);
  18004. }
  18005. return MA_SUCCESS;
  18006. }
  18007. static ma_result ma_context_get_device_id_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, ma_device_id* pDeviceID)
  18008. {
  18009. WCHAR* pDeviceIDString;
  18010. HRESULT hr;
  18011. MA_ASSERT(pDeviceID != NULL);
  18012. hr = ma_IMMDevice_GetId(pMMDevice, &pDeviceIDString);
  18013. if (SUCCEEDED(hr)) {
  18014. size_t idlen = ma_strlen_WCHAR(pDeviceIDString);
  18015. if (idlen+1 > ma_countof(pDeviceID->wasapi)) {
  18016. ma_CoTaskMemFree(pContext, pDeviceIDString);
  18017. 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. */
  18018. return MA_ERROR;
  18019. }
  18020. MA_COPY_MEMORY(pDeviceID->wasapi, pDeviceIDString, idlen * sizeof(wchar_t));
  18021. pDeviceID->wasapi[idlen] = '\0';
  18022. ma_CoTaskMemFree(pContext, pDeviceIDString);
  18023. return MA_SUCCESS;
  18024. }
  18025. return MA_ERROR;
  18026. }
  18027. 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)
  18028. {
  18029. ma_result result;
  18030. HRESULT hr;
  18031. MA_ASSERT(pContext != NULL);
  18032. MA_ASSERT(pMMDevice != NULL);
  18033. MA_ASSERT(pInfo != NULL);
  18034. /* ID. */
  18035. result = ma_context_get_device_id_from_MMDevice__wasapi(pContext, pMMDevice, &pInfo->id);
  18036. if (result == MA_SUCCESS) {
  18037. if (pDefaultDeviceID != NULL) {
  18038. if (ma_strcmp_WCHAR(pInfo->id.wasapi, pDefaultDeviceID) == 0) {
  18039. pInfo->isDefault = MA_TRUE;
  18040. }
  18041. }
  18042. }
  18043. /* Description / Friendly Name */
  18044. {
  18045. ma_IPropertyStore *pProperties;
  18046. hr = ma_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties);
  18047. if (SUCCEEDED(hr)) {
  18048. MA_PROPVARIANT var;
  18049. ma_PropVariantInit(&var);
  18050. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &var);
  18051. if (SUCCEEDED(hr)) {
  18052. WideCharToMultiByte(CP_UTF8, 0, var.pwszVal, -1, pInfo->name, sizeof(pInfo->name), 0, FALSE);
  18053. ma_PropVariantClear(pContext, &var);
  18054. }
  18055. ma_IPropertyStore_Release(pProperties);
  18056. }
  18057. }
  18058. /* Format */
  18059. if (!onlySimpleInfo) {
  18060. ma_IAudioClient* pAudioClient;
  18061. hr = ma_IMMDevice_Activate(pMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient);
  18062. if (SUCCEEDED(hr)) {
  18063. result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, pInfo);
  18064. ma_IAudioClient_Release(pAudioClient);
  18065. return result;
  18066. } else {
  18067. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval.");
  18068. return ma_result_from_HRESULT(hr);
  18069. }
  18070. }
  18071. return MA_SUCCESS;
  18072. }
  18073. 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)
  18074. {
  18075. ma_result result = MA_SUCCESS;
  18076. UINT deviceCount;
  18077. HRESULT hr;
  18078. ma_uint32 iDevice;
  18079. WCHAR* pDefaultDeviceID = NULL;
  18080. ma_IMMDeviceCollection* pDeviceCollection = NULL;
  18081. MA_ASSERT(pContext != NULL);
  18082. MA_ASSERT(callback != NULL);
  18083. /* Grab the default device. We use this to know whether or not flag the returned device info as being the default. */
  18084. pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
  18085. /* We need to enumerate the devices which returns a device collection. */
  18086. hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_device_type_to_EDataFlow(deviceType), MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection);
  18087. if (SUCCEEDED(hr)) {
  18088. hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount);
  18089. if (FAILED(hr)) {
  18090. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get device count.\n");
  18091. result = ma_result_from_HRESULT(hr);
  18092. goto done;
  18093. }
  18094. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  18095. ma_device_info deviceInfo;
  18096. ma_IMMDevice* pMMDevice;
  18097. MA_ZERO_OBJECT(&deviceInfo);
  18098. hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice);
  18099. if (SUCCEEDED(hr)) {
  18100. result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_TRUE, &deviceInfo); /* MA_TRUE = onlySimpleInfo. */
  18101. ma_IMMDevice_Release(pMMDevice);
  18102. if (result == MA_SUCCESS) {
  18103. ma_bool32 cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
  18104. if (cbResult == MA_FALSE) {
  18105. break;
  18106. }
  18107. }
  18108. }
  18109. }
  18110. }
  18111. done:
  18112. if (pDefaultDeviceID != NULL) {
  18113. ma_CoTaskMemFree(pContext, pDefaultDeviceID);
  18114. pDefaultDeviceID = NULL;
  18115. }
  18116. if (pDeviceCollection != NULL) {
  18117. ma_IMMDeviceCollection_Release(pDeviceCollection);
  18118. pDeviceCollection = NULL;
  18119. }
  18120. return result;
  18121. }
  18122. 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)
  18123. {
  18124. ma_result result;
  18125. HRESULT hr;
  18126. MA_ASSERT(pContext != NULL);
  18127. MA_ASSERT(ppAudioClient != NULL);
  18128. MA_ASSERT(ppMMDevice != NULL);
  18129. result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, ppMMDevice);
  18130. if (result != MA_SUCCESS) {
  18131. return result;
  18132. }
  18133. hr = ma_IMMDevice_Activate(*ppMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, pActivationParams, (void**)ppAudioClient);
  18134. if (FAILED(hr)) {
  18135. return ma_result_from_HRESULT(hr);
  18136. }
  18137. return MA_SUCCESS;
  18138. }
  18139. #else
  18140. 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)
  18141. {
  18142. ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL;
  18143. ma_completion_handler_uwp completionHandler;
  18144. IID iid;
  18145. WCHAR* iidStr;
  18146. HRESULT hr;
  18147. ma_result result;
  18148. HRESULT activateResult;
  18149. ma_IUnknown* pActivatedInterface;
  18150. MA_ASSERT(pContext != NULL);
  18151. MA_ASSERT(ppAudioClient != NULL);
  18152. if (pDeviceID != NULL) {
  18153. iidStr = (WCHAR*)pDeviceID->wasapi;
  18154. } else {
  18155. if (deviceType == ma_device_type_capture) {
  18156. iid = MA_IID_DEVINTERFACE_AUDIO_CAPTURE;
  18157. } else {
  18158. iid = MA_IID_DEVINTERFACE_AUDIO_RENDER;
  18159. }
  18160. #if defined(__cplusplus)
  18161. hr = StringFromIID(iid, &iidStr);
  18162. #else
  18163. hr = StringFromIID(&iid, &iidStr);
  18164. #endif
  18165. if (FAILED(hr)) {
  18166. 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");
  18167. return ma_result_from_HRESULT(hr);
  18168. }
  18169. }
  18170. result = ma_completion_handler_uwp_init(&completionHandler);
  18171. if (result != MA_SUCCESS) {
  18172. ma_CoTaskMemFree(pContext, iidStr);
  18173. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().\n");
  18174. return result;
  18175. }
  18176. hr = ((MA_PFN_ActivateAudioInterfaceAsync)pContext->wasapi.ActivateAudioInterfaceAsync)(iidStr, &MA_IID_IAudioClient, pActivationParams, (ma_IActivateAudioInterfaceCompletionHandler*)&completionHandler, (ma_IActivateAudioInterfaceAsyncOperation**)&pAsyncOp);
  18177. if (FAILED(hr)) {
  18178. ma_completion_handler_uwp_uninit(&completionHandler);
  18179. ma_CoTaskMemFree(pContext, iidStr);
  18180. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.\n");
  18181. return ma_result_from_HRESULT(hr);
  18182. }
  18183. if (pDeviceID == NULL) {
  18184. ma_CoTaskMemFree(pContext, iidStr);
  18185. }
  18186. /* Wait for the async operation for finish. */
  18187. ma_completion_handler_uwp_wait(&completionHandler);
  18188. ma_completion_handler_uwp_uninit(&completionHandler);
  18189. hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface);
  18190. ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp);
  18191. if (FAILED(hr) || FAILED(activateResult)) {
  18192. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.\n");
  18193. return FAILED(hr) ? ma_result_from_HRESULT(hr) : ma_result_from_HRESULT(activateResult);
  18194. }
  18195. /* Here is where we grab the IAudioClient interface. */
  18196. hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient);
  18197. if (FAILED(hr)) {
  18198. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.\n");
  18199. return ma_result_from_HRESULT(hr);
  18200. }
  18201. if (ppActivatedInterface) {
  18202. *ppActivatedInterface = pActivatedInterface;
  18203. } else {
  18204. ma_IUnknown_Release(pActivatedInterface);
  18205. }
  18206. return MA_SUCCESS;
  18207. }
  18208. #endif
  18209. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-audioclient_activation_type */
  18210. typedef enum
  18211. {
  18212. MA_AUDIOCLIENT_ACTIVATION_TYPE_DEFAULT,
  18213. MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK
  18214. } MA_AUDIOCLIENT_ACTIVATION_TYPE;
  18215. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-process_loopback_mode */
  18216. typedef enum
  18217. {
  18218. MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
  18219. MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE
  18220. } MA_PROCESS_LOOPBACK_MODE;
  18221. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params */
  18222. typedef struct
  18223. {
  18224. DWORD TargetProcessId;
  18225. MA_PROCESS_LOOPBACK_MODE ProcessLoopbackMode;
  18226. } MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS;
  18227. #if defined(_MSC_VER) && !defined(__clang__)
  18228. #pragma warning(push)
  18229. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  18230. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  18231. #pragma GCC diagnostic push
  18232. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  18233. #if defined(__clang__)
  18234. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  18235. #endif
  18236. #endif
  18237. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_activation_params */
  18238. typedef struct
  18239. {
  18240. MA_AUDIOCLIENT_ACTIVATION_TYPE ActivationType;
  18241. union
  18242. {
  18243. MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS ProcessLoopbackParams;
  18244. };
  18245. } MA_AUDIOCLIENT_ACTIVATION_PARAMS;
  18246. #if defined(_MSC_VER) && !defined(__clang__)
  18247. #pragma warning(pop)
  18248. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  18249. #pragma GCC diagnostic pop
  18250. #endif
  18251. #define MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK L"VAD\\Process_Loopback"
  18252. 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)
  18253. {
  18254. ma_result result;
  18255. ma_bool32 usingProcessLoopback = MA_FALSE;
  18256. MA_AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams;
  18257. MA_PROPVARIANT activationParams;
  18258. MA_PROPVARIANT* pActivationParams = NULL;
  18259. ma_device_id virtualDeviceID;
  18260. /* Activation parameters specific to loopback mode. Note that process-specific loopback will only work when a default device ID is specified. */
  18261. if (deviceType == ma_device_type_loopback && loopbackProcessID != 0 && pDeviceID == NULL) {
  18262. usingProcessLoopback = MA_TRUE;
  18263. }
  18264. if (usingProcessLoopback) {
  18265. MA_ZERO_OBJECT(&audioclientActivationParams);
  18266. audioclientActivationParams.ActivationType = MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK;
  18267. audioclientActivationParams.ProcessLoopbackParams.ProcessLoopbackMode = (loopbackProcessExclude) ? MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE : MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE;
  18268. audioclientActivationParams.ProcessLoopbackParams.TargetProcessId = (DWORD)loopbackProcessID;
  18269. ma_PropVariantInit(&activationParams);
  18270. activationParams.vt = MA_VT_BLOB;
  18271. activationParams.blob.cbSize = sizeof(audioclientActivationParams);
  18272. activationParams.blob.pBlobData = (BYTE*)&audioclientActivationParams;
  18273. pActivationParams = &activationParams;
  18274. /* When requesting a specific device ID we need to use a special device ID. */
  18275. 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. */
  18276. pDeviceID = &virtualDeviceID;
  18277. } else {
  18278. pActivationParams = NULL; /* No activation parameters required. */
  18279. }
  18280. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18281. result = ma_context_get_IAudioClient_Desktop__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface);
  18282. #else
  18283. result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface);
  18284. #endif
  18285. /*
  18286. If loopback mode was requested with a process ID and initialization failed, it could be because it's
  18287. trying to run on an older version of Windows where it's not supported. We need to let the caller
  18288. know about this with a log message.
  18289. */
  18290. if (result != MA_SUCCESS) {
  18291. if (usingProcessLoopback) {
  18292. 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);
  18293. }
  18294. }
  18295. return result;
  18296. }
  18297. static ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  18298. {
  18299. /* Different enumeration for desktop and UWP. */
  18300. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18301. /* Desktop */
  18302. HRESULT hr;
  18303. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  18304. hr = ma_CoCreateInstance(pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  18305. if (FAILED(hr)) {
  18306. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  18307. return ma_result_from_HRESULT(hr);
  18308. }
  18309. ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_playback, callback, pUserData);
  18310. ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_capture, callback, pUserData);
  18311. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  18312. #else
  18313. /*
  18314. UWP
  18315. The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate
  18316. over devices without using MMDevice, I'm restricting devices to defaults.
  18317. 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/
  18318. */
  18319. if (callback) {
  18320. ma_bool32 cbResult = MA_TRUE;
  18321. /* Playback. */
  18322. if (cbResult) {
  18323. ma_device_info deviceInfo;
  18324. MA_ZERO_OBJECT(&deviceInfo);
  18325. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  18326. deviceInfo.isDefault = MA_TRUE;
  18327. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  18328. }
  18329. /* Capture. */
  18330. if (cbResult) {
  18331. ma_device_info deviceInfo;
  18332. MA_ZERO_OBJECT(&deviceInfo);
  18333. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  18334. deviceInfo.isDefault = MA_TRUE;
  18335. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  18336. }
  18337. }
  18338. #endif
  18339. return MA_SUCCESS;
  18340. }
  18341. 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)
  18342. {
  18343. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18344. ma_result result;
  18345. ma_IMMDevice* pMMDevice = NULL;
  18346. WCHAR* pDefaultDeviceID = NULL;
  18347. result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice);
  18348. if (result != MA_SUCCESS) {
  18349. return result;
  18350. }
  18351. /* We need the default device ID so we can set the isDefault flag in the device info. */
  18352. pDefaultDeviceID = ma_context_get_default_device_id__wasapi(pContext, deviceType);
  18353. result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_FALSE, pDeviceInfo); /* MA_FALSE = !onlySimpleInfo. */
  18354. if (pDefaultDeviceID != NULL) {
  18355. ma_CoTaskMemFree(pContext, pDefaultDeviceID);
  18356. pDefaultDeviceID = NULL;
  18357. }
  18358. ma_IMMDevice_Release(pMMDevice);
  18359. return result;
  18360. #else
  18361. ma_IAudioClient* pAudioClient;
  18362. ma_result result;
  18363. /* UWP currently only uses default devices. */
  18364. if (deviceType == ma_device_type_playback) {
  18365. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  18366. } else {
  18367. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  18368. }
  18369. result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, NULL, &pAudioClient, NULL);
  18370. if (result != MA_SUCCESS) {
  18371. return result;
  18372. }
  18373. result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, pDeviceInfo);
  18374. pDeviceInfo->isDefault = MA_TRUE; /* UWP only supports default devices. */
  18375. ma_IAudioClient_Release(pAudioClient);
  18376. return result;
  18377. #endif
  18378. }
  18379. static ma_result ma_device_uninit__wasapi(ma_device* pDevice)
  18380. {
  18381. MA_ASSERT(pDevice != NULL);
  18382. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18383. if (pDevice->wasapi.pDeviceEnumerator) {
  18384. ((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator)->lpVtbl->UnregisterEndpointNotificationCallback((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator, &pDevice->wasapi.notificationClient);
  18385. ma_IMMDeviceEnumerator_Release((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator);
  18386. }
  18387. #endif
  18388. if (pDevice->wasapi.pRenderClient) {
  18389. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  18390. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  18391. pDevice->wasapi.pMappedBufferPlayback = NULL;
  18392. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  18393. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  18394. }
  18395. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  18396. }
  18397. if (pDevice->wasapi.pCaptureClient) {
  18398. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  18399. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  18400. pDevice->wasapi.pMappedBufferCapture = NULL;
  18401. pDevice->wasapi.mappedBufferCaptureCap = 0;
  18402. pDevice->wasapi.mappedBufferCaptureLen = 0;
  18403. }
  18404. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18405. }
  18406. if (pDevice->wasapi.pAudioClientPlayback) {
  18407. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  18408. }
  18409. if (pDevice->wasapi.pAudioClientCapture) {
  18410. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18411. }
  18412. if (pDevice->wasapi.hEventPlayback) {
  18413. CloseHandle((HANDLE)pDevice->wasapi.hEventPlayback);
  18414. }
  18415. if (pDevice->wasapi.hEventCapture) {
  18416. CloseHandle((HANDLE)pDevice->wasapi.hEventCapture);
  18417. }
  18418. return MA_SUCCESS;
  18419. }
  18420. typedef struct
  18421. {
  18422. /* Input. */
  18423. ma_format formatIn;
  18424. ma_uint32 channelsIn;
  18425. ma_uint32 sampleRateIn;
  18426. ma_channel channelMapIn[MA_MAX_CHANNELS];
  18427. ma_uint32 periodSizeInFramesIn;
  18428. ma_uint32 periodSizeInMillisecondsIn;
  18429. ma_uint32 periodsIn;
  18430. ma_share_mode shareMode;
  18431. ma_performance_profile performanceProfile;
  18432. ma_bool32 noAutoConvertSRC;
  18433. ma_bool32 noDefaultQualitySRC;
  18434. ma_bool32 noHardwareOffloading;
  18435. ma_uint32 loopbackProcessID;
  18436. ma_bool32 loopbackProcessExclude;
  18437. /* Output. */
  18438. ma_IAudioClient* pAudioClient;
  18439. ma_IAudioRenderClient* pRenderClient;
  18440. ma_IAudioCaptureClient* pCaptureClient;
  18441. ma_format formatOut;
  18442. ma_uint32 channelsOut;
  18443. ma_uint32 sampleRateOut;
  18444. ma_channel channelMapOut[MA_MAX_CHANNELS];
  18445. ma_uint32 periodSizeInFramesOut;
  18446. ma_uint32 periodsOut;
  18447. ma_bool32 usingAudioClient3;
  18448. char deviceName[256];
  18449. ma_device_id id;
  18450. } ma_device_init_internal_data__wasapi;
  18451. 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)
  18452. {
  18453. HRESULT hr;
  18454. ma_result result = MA_SUCCESS;
  18455. const char* errorMsg = "";
  18456. MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
  18457. DWORD streamFlags = 0;
  18458. MA_REFERENCE_TIME periodDurationInMicroseconds;
  18459. ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE;
  18460. MA_WAVEFORMATEXTENSIBLE wf;
  18461. ma_WASAPIDeviceInterface* pDeviceInterface = NULL;
  18462. ma_IAudioClient2* pAudioClient2;
  18463. ma_uint32 nativeSampleRate;
  18464. ma_bool32 usingProcessLoopback = MA_FALSE;
  18465. MA_ASSERT(pContext != NULL);
  18466. MA_ASSERT(pData != NULL);
  18467. /* This function is only used to initialize one device type: either playback, capture or loopback. Never full-duplex. */
  18468. if (deviceType == ma_device_type_duplex) {
  18469. return MA_INVALID_ARGS;
  18470. }
  18471. usingProcessLoopback = deviceType == ma_device_type_loopback && pData->loopbackProcessID != 0 && pDeviceID == NULL;
  18472. pData->pAudioClient = NULL;
  18473. pData->pRenderClient = NULL;
  18474. pData->pCaptureClient = NULL;
  18475. streamFlags = MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  18476. if (!pData->noAutoConvertSRC && pData->sampleRateIn != 0 && pData->shareMode != ma_share_mode_exclusive) { /* <-- Exclusive streams must use the native sample rate. */
  18477. streamFlags |= MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;
  18478. }
  18479. if (!pData->noDefaultQualitySRC && pData->sampleRateIn != 0 && (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) != 0) {
  18480. streamFlags |= MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
  18481. }
  18482. if (deviceType == ma_device_type_loopback) {
  18483. streamFlags |= MA_AUDCLNT_STREAMFLAGS_LOOPBACK;
  18484. }
  18485. result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, pData->loopbackProcessID, pData->loopbackProcessExclude, &pData->pAudioClient, &pDeviceInterface);
  18486. if (result != MA_SUCCESS) {
  18487. goto done;
  18488. }
  18489. MA_ZERO_OBJECT(&wf);
  18490. /* Try enabling hardware offloading. */
  18491. if (!pData->noHardwareOffloading) {
  18492. hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient2, (void**)&pAudioClient2);
  18493. if (SUCCEEDED(hr)) {
  18494. BOOL isHardwareOffloadingSupported = 0;
  18495. hr = ma_IAudioClient2_IsOffloadCapable(pAudioClient2, MA_AudioCategory_Other, &isHardwareOffloadingSupported);
  18496. if (SUCCEEDED(hr) && isHardwareOffloadingSupported) {
  18497. ma_AudioClientProperties clientProperties;
  18498. MA_ZERO_OBJECT(&clientProperties);
  18499. clientProperties.cbSize = sizeof(clientProperties);
  18500. clientProperties.bIsOffload = 1;
  18501. clientProperties.eCategory = MA_AudioCategory_Other;
  18502. ma_IAudioClient2_SetClientProperties(pAudioClient2, &clientProperties);
  18503. }
  18504. pAudioClient2->lpVtbl->Release(pAudioClient2);
  18505. }
  18506. }
  18507. /* 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. */
  18508. result = MA_FORMAT_NOT_SUPPORTED;
  18509. if (pData->shareMode == ma_share_mode_exclusive) {
  18510. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18511. /* In exclusive mode on desktop we always use the backend's native format. */
  18512. ma_IPropertyStore* pStore = NULL;
  18513. hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pStore);
  18514. if (SUCCEEDED(hr)) {
  18515. MA_PROPVARIANT prop;
  18516. ma_PropVariantInit(&prop);
  18517. hr = ma_IPropertyStore_GetValue(pStore, &MA_PKEY_AudioEngine_DeviceFormat, &prop);
  18518. if (SUCCEEDED(hr)) {
  18519. MA_WAVEFORMATEX* pActualFormat = (MA_WAVEFORMATEX*)prop.blob.pBlobData;
  18520. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pData->pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pActualFormat, NULL);
  18521. if (SUCCEEDED(hr)) {
  18522. MA_COPY_MEMORY(&wf, pActualFormat, sizeof(MA_WAVEFORMATEXTENSIBLE));
  18523. }
  18524. ma_PropVariantClear(pContext, &prop);
  18525. }
  18526. ma_IPropertyStore_Release(pStore);
  18527. }
  18528. #else
  18529. /*
  18530. I do not know how to query the device's native format on UWP so for now I'm just disabling support for
  18531. exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported()
  18532. until you find one that works.
  18533. TODO: Add support for exclusive mode to UWP.
  18534. */
  18535. hr = S_FALSE;
  18536. #endif
  18537. if (hr == S_OK) {
  18538. shareMode = MA_AUDCLNT_SHAREMODE_EXCLUSIVE;
  18539. result = MA_SUCCESS;
  18540. } else {
  18541. result = MA_SHARE_MODE_NOT_SUPPORTED;
  18542. }
  18543. } else {
  18544. /* In shared mode we are always using the format reported by the operating system. */
  18545. MA_WAVEFORMATEXTENSIBLE* pNativeFormat = NULL;
  18546. hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (MA_WAVEFORMATEX**)&pNativeFormat);
  18547. if (hr != S_OK) {
  18548. /* When using process-specific loopback, GetMixFormat() seems to always fail. */
  18549. if (usingProcessLoopback) {
  18550. wf.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
  18551. wf.nChannels = 2;
  18552. wf.nSamplesPerSec = 44100;
  18553. wf.wBitsPerSample = 32;
  18554. wf.nBlockAlign = wf.nChannels * wf.wBitsPerSample / 8;
  18555. wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  18556. wf.cbSize = sizeof(MA_WAVEFORMATEX);
  18557. result = MA_SUCCESS;
  18558. } else {
  18559. result = MA_FORMAT_NOT_SUPPORTED;
  18560. }
  18561. } else {
  18562. /*
  18563. I've seen cases where cbSize will be set to sizeof(WAVEFORMATEX) even though the structure itself
  18564. is given the format tag of WAVE_FORMAT_EXTENSIBLE. If the format tag is WAVE_FORMAT_EXTENSIBLE
  18565. want to make sure we copy the whole WAVEFORMATEXTENSIBLE structure. Otherwise we'll have to be
  18566. safe and only copy the WAVEFORMATEX part.
  18567. */
  18568. if (pNativeFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  18569. MA_COPY_MEMORY(&wf, pNativeFormat, sizeof(MA_WAVEFORMATEXTENSIBLE));
  18570. } else {
  18571. /* I've seen a case where cbSize was set to 0. Assume sizeof(WAVEFORMATEX) in this case. */
  18572. size_t cbSize = pNativeFormat->cbSize;
  18573. if (cbSize == 0) {
  18574. cbSize = sizeof(MA_WAVEFORMATEX);
  18575. }
  18576. /* Make sure we don't copy more than the capacity of `wf`. */
  18577. if (cbSize > sizeof(wf)) {
  18578. cbSize = sizeof(wf);
  18579. }
  18580. MA_COPY_MEMORY(&wf, pNativeFormat, cbSize);
  18581. }
  18582. result = MA_SUCCESS;
  18583. }
  18584. ma_CoTaskMemFree(pContext, pNativeFormat);
  18585. shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
  18586. }
  18587. /* Return an error if we still haven't found a format. */
  18588. if (result != MA_SUCCESS) {
  18589. errorMsg = "[WASAPI] Failed to find best device mix format.";
  18590. goto done;
  18591. }
  18592. /*
  18593. 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
  18594. WASAPI to perform the sample rate conversion.
  18595. */
  18596. nativeSampleRate = wf.nSamplesPerSec;
  18597. if (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) {
  18598. wf.nSamplesPerSec = (pData->sampleRateIn != 0) ? pData->sampleRateIn : MA_DEFAULT_SAMPLE_RATE;
  18599. wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  18600. }
  18601. pData->formatOut = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)&wf);
  18602. if (pData->formatOut == ma_format_unknown) {
  18603. /*
  18604. 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
  18605. 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
  18606. completeness we'll check for it and return MA_FORMAT_NOT_SUPPORTED.
  18607. */
  18608. if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
  18609. result = MA_SHARE_MODE_NOT_SUPPORTED;
  18610. } else {
  18611. result = MA_FORMAT_NOT_SUPPORTED;
  18612. }
  18613. errorMsg = "[WASAPI] Native format not supported.";
  18614. goto done;
  18615. }
  18616. pData->channelsOut = wf.nChannels;
  18617. pData->sampleRateOut = wf.nSamplesPerSec;
  18618. /*
  18619. Get the internal channel map based on the channel mask. There is a possibility that GetMixFormat() returns
  18620. a WAVEFORMATEX instead of a WAVEFORMATEXTENSIBLE, in which case the channel mask will be undefined. In this
  18621. case we'll just use the default channel map.
  18622. */
  18623. if (wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE || wf.cbSize >= sizeof(MA_WAVEFORMATEXTENSIBLE)) {
  18624. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut);
  18625. } else {
  18626. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  18627. }
  18628. /* Period size. */
  18629. pData->periodsOut = (pData->periodsIn != 0) ? pData->periodsIn : MA_DEFAULT_PERIODS;
  18630. pData->periodSizeInFramesOut = pData->periodSizeInFramesIn;
  18631. if (pData->periodSizeInFramesOut == 0) {
  18632. if (pData->periodSizeInMillisecondsIn == 0) {
  18633. if (pData->performanceProfile == ma_performance_profile_low_latency) {
  18634. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, wf.nSamplesPerSec);
  18635. } else {
  18636. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, wf.nSamplesPerSec);
  18637. }
  18638. } else {
  18639. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, wf.nSamplesPerSec);
  18640. }
  18641. }
  18642. periodDurationInMicroseconds = ((ma_uint64)pData->periodSizeInFramesOut * 1000 * 1000) / wf.nSamplesPerSec;
  18643. /* Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. */
  18644. if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
  18645. MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10;
  18646. /*
  18647. If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing
  18648. it and trying it again.
  18649. */
  18650. hr = E_FAIL;
  18651. for (;;) {
  18652. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (MA_WAVEFORMATEX*)&wf, NULL);
  18653. if (hr == MA_AUDCLNT_E_INVALID_DEVICE_PERIOD) {
  18654. if (bufferDuration > 500*10000) {
  18655. break;
  18656. } else {
  18657. if (bufferDuration == 0) { /* <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. */
  18658. break;
  18659. }
  18660. bufferDuration = bufferDuration * 2;
  18661. continue;
  18662. }
  18663. } else {
  18664. break;
  18665. }
  18666. }
  18667. if (hr == MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) {
  18668. ma_uint32 bufferSizeInFrames;
  18669. hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
  18670. if (SUCCEEDED(hr)) {
  18671. bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.nSamplesPerSec * bufferSizeInFrames) + 0.5);
  18672. /* Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! */
  18673. ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
  18674. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18675. hr = ma_IMMDevice_Activate(pDeviceInterface, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient);
  18676. #else
  18677. hr = ma_IUnknown_QueryInterface(pDeviceInterface, &MA_IID_IAudioClient, (void**)&pData->pAudioClient);
  18678. #endif
  18679. if (SUCCEEDED(hr)) {
  18680. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (MA_WAVEFORMATEX*)&wf, NULL);
  18681. }
  18682. }
  18683. }
  18684. if (FAILED(hr)) {
  18685. /* 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. */
  18686. if (hr == E_ACCESSDENIED) {
  18687. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Access denied.", result = MA_ACCESS_DENIED;
  18688. } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
  18689. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Device in use.", result = MA_BUSY;
  18690. } else {
  18691. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode."; result = ma_result_from_HRESULT(hr);
  18692. }
  18693. goto done;
  18694. }
  18695. }
  18696. if (shareMode == MA_AUDCLNT_SHAREMODE_SHARED) {
  18697. /*
  18698. Low latency shared mode via IAudioClient3.
  18699. NOTE
  18700. ====
  18701. Contrary to the documentation on MSDN (https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream), the
  18702. use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM and AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY with IAudioClient3_InitializeSharedAudioStream() absolutely does not work. Using
  18703. any of these flags will result in HRESULT code 0x88890021. The other problem is that calling IAudioClient3_GetSharedModeEnginePeriod() with a sample rate different to
  18704. that returned by IAudioClient_GetMixFormat() also results in an error. I'm therefore disabling low-latency shared mode with AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM.
  18705. */
  18706. #ifndef MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE
  18707. {
  18708. if ((streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) == 0 || nativeSampleRate == wf.nSamplesPerSec) {
  18709. ma_IAudioClient3* pAudioClient3 = NULL;
  18710. hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient3, (void**)&pAudioClient3);
  18711. if (SUCCEEDED(hr)) {
  18712. ma_uint32 defaultPeriodInFrames;
  18713. ma_uint32 fundamentalPeriodInFrames;
  18714. ma_uint32 minPeriodInFrames;
  18715. ma_uint32 maxPeriodInFrames;
  18716. hr = ma_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (MA_WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames);
  18717. if (SUCCEEDED(hr)) {
  18718. ma_uint32 desiredPeriodInFrames = pData->periodSizeInFramesOut;
  18719. ma_uint32 actualPeriodInFrames = desiredPeriodInFrames;
  18720. /* Make sure the period size is a multiple of fundamentalPeriodInFrames. */
  18721. actualPeriodInFrames = actualPeriodInFrames / fundamentalPeriodInFrames;
  18722. actualPeriodInFrames = actualPeriodInFrames * fundamentalPeriodInFrames;
  18723. /* The period needs to be clamped between minPeriodInFrames and maxPeriodInFrames. */
  18724. actualPeriodInFrames = ma_clamp(actualPeriodInFrames, minPeriodInFrames, maxPeriodInFrames);
  18725. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=%d)\n", actualPeriodInFrames);
  18726. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " defaultPeriodInFrames=%d\n", defaultPeriodInFrames);
  18727. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " fundamentalPeriodInFrames=%d\n", fundamentalPeriodInFrames);
  18728. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " minPeriodInFrames=%d\n", minPeriodInFrames);
  18729. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " maxPeriodInFrames=%d\n", maxPeriodInFrames);
  18730. /* If the client requested a largish buffer than we don't actually want to use low latency shared mode because it forces small buffers. */
  18731. if (actualPeriodInFrames >= desiredPeriodInFrames) {
  18732. /*
  18733. MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY must not be in the stream flags. If either of these are specified,
  18734. IAudioClient3_InitializeSharedAudioStream() will fail.
  18735. */
  18736. hr = ma_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, streamFlags & ~(MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY), actualPeriodInFrames, (MA_WAVEFORMATEX*)&wf, NULL);
  18737. if (SUCCEEDED(hr)) {
  18738. wasInitializedUsingIAudioClient3 = MA_TRUE;
  18739. pData->periodSizeInFramesOut = actualPeriodInFrames;
  18740. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Using IAudioClient3\n");
  18741. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " periodSizeInFramesOut=%d\n", pData->periodSizeInFramesOut);
  18742. } else {
  18743. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_InitializeSharedAudioStream failed. Falling back to IAudioClient.\n");
  18744. }
  18745. } else {
  18746. 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");
  18747. }
  18748. } else {
  18749. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_GetSharedModeEnginePeriod failed. Falling back to IAudioClient.\n");
  18750. }
  18751. ma_IAudioClient3_Release(pAudioClient3);
  18752. pAudioClient3 = NULL;
  18753. }
  18754. }
  18755. }
  18756. #else
  18757. {
  18758. 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");
  18759. }
  18760. #endif
  18761. /* If we don't have an IAudioClient3 then we need to use the normal initialization routine. */
  18762. if (!wasInitializedUsingIAudioClient3) {
  18763. MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10; /* <-- Multiply by 10 for microseconds to 100-nanoseconds. */
  18764. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, 0, (const MA_WAVEFORMATEX*)&wf, NULL);
  18765. if (FAILED(hr)) {
  18766. if (hr == E_ACCESSDENIED) {
  18767. errorMsg = "[WASAPI] Failed to initialize device. Access denied.", result = MA_ACCESS_DENIED;
  18768. } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
  18769. errorMsg = "[WASAPI] Failed to initialize device. Device in use.", result = MA_BUSY;
  18770. } else {
  18771. errorMsg = "[WASAPI] Failed to initialize device.", result = ma_result_from_HRESULT(hr);
  18772. }
  18773. goto done;
  18774. }
  18775. }
  18776. }
  18777. if (!wasInitializedUsingIAudioClient3) {
  18778. ma_uint32 bufferSizeInFrames = 0;
  18779. hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
  18780. if (FAILED(hr)) {
  18781. errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = ma_result_from_HRESULT(hr);
  18782. goto done;
  18783. }
  18784. /*
  18785. When using process loopback mode, retrieval of the buffer size seems to result in totally
  18786. incorrect values. In this case we'll just assume it's the same size as what we requested
  18787. when we initialized the client.
  18788. */
  18789. if (usingProcessLoopback) {
  18790. bufferSizeInFrames = (ma_uint32)((periodDurationInMicroseconds * pData->periodsOut) * pData->sampleRateOut / 1000000);
  18791. }
  18792. pData->periodSizeInFramesOut = bufferSizeInFrames / pData->periodsOut;
  18793. }
  18794. pData->usingAudioClient3 = wasInitializedUsingIAudioClient3;
  18795. if (deviceType == ma_device_type_playback) {
  18796. result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pRenderClient);
  18797. } else {
  18798. result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pCaptureClient);
  18799. }
  18800. /*if (FAILED(hr)) {*/
  18801. if (result != MA_SUCCESS) {
  18802. errorMsg = "[WASAPI] Failed to get audio client service.";
  18803. goto done;
  18804. }
  18805. /* Grab the name of the device. */
  18806. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18807. {
  18808. ma_IPropertyStore *pProperties;
  18809. hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties);
  18810. if (SUCCEEDED(hr)) {
  18811. MA_PROPVARIANT varName;
  18812. ma_PropVariantInit(&varName);
  18813. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName);
  18814. if (SUCCEEDED(hr)) {
  18815. WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE);
  18816. ma_PropVariantClear(pContext, &varName);
  18817. }
  18818. ma_IPropertyStore_Release(pProperties);
  18819. }
  18820. }
  18821. #endif
  18822. /*
  18823. For the WASAPI backend we need to know the actual IDs of the device in order to do automatic
  18824. stream routing so that IDs can be compared and we can determine which device has been detached
  18825. and whether or not it matches with our ma_device.
  18826. */
  18827. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18828. {
  18829. /* Desktop */
  18830. ma_context_get_device_id_from_MMDevice__wasapi(pContext, pDeviceInterface, &pData->id);
  18831. }
  18832. #else
  18833. {
  18834. /* UWP */
  18835. /* TODO: Implement me. Need to figure out how to get the ID of the default device. */
  18836. }
  18837. #endif
  18838. done:
  18839. /* Clean up. */
  18840. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18841. if (pDeviceInterface != NULL) {
  18842. ma_IMMDevice_Release(pDeviceInterface);
  18843. }
  18844. #else
  18845. if (pDeviceInterface != NULL) {
  18846. ma_IUnknown_Release(pDeviceInterface);
  18847. }
  18848. #endif
  18849. if (result != MA_SUCCESS) {
  18850. if (pData->pRenderClient) {
  18851. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pData->pRenderClient);
  18852. pData->pRenderClient = NULL;
  18853. }
  18854. if (pData->pCaptureClient) {
  18855. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pData->pCaptureClient);
  18856. pData->pCaptureClient = NULL;
  18857. }
  18858. if (pData->pAudioClient) {
  18859. ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
  18860. pData->pAudioClient = NULL;
  18861. }
  18862. if (errorMsg != NULL && errorMsg[0] != '\0') {
  18863. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "%s\n", errorMsg);
  18864. }
  18865. return result;
  18866. } else {
  18867. return MA_SUCCESS;
  18868. }
  18869. }
  18870. static ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType)
  18871. {
  18872. ma_device_init_internal_data__wasapi data;
  18873. ma_result result;
  18874. MA_ASSERT(pDevice != NULL);
  18875. /* We only re-initialize the playback or capture device. Never a full-duplex device. */
  18876. if (deviceType == ma_device_type_duplex) {
  18877. return MA_INVALID_ARGS;
  18878. }
  18879. /*
  18880. Before reinitializing the device we need to free the previous audio clients.
  18881. There's a known memory leak here. We will be calling this from the routing change callback that
  18882. is fired by WASAPI. If we attempt to release the IAudioClient we will deadlock. In my opinion
  18883. this is a bug. I'm not sure what I need to do to handle this cleanly, but I think we'll probably
  18884. need some system where we post an event, but delay the execution of it until the callback has
  18885. returned. I'm not sure how to do this reliably, however. I have set up some infrastructure for
  18886. a command thread which might be useful for this.
  18887. */
  18888. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
  18889. if (pDevice->wasapi.pCaptureClient) {
  18890. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18891. pDevice->wasapi.pCaptureClient = NULL;
  18892. }
  18893. if (pDevice->wasapi.pAudioClientCapture) {
  18894. /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_capture);*/
  18895. pDevice->wasapi.pAudioClientCapture = NULL;
  18896. }
  18897. }
  18898. if (deviceType == ma_device_type_playback) {
  18899. if (pDevice->wasapi.pRenderClient) {
  18900. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  18901. pDevice->wasapi.pRenderClient = NULL;
  18902. }
  18903. if (pDevice->wasapi.pAudioClientPlayback) {
  18904. /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_playback);*/
  18905. pDevice->wasapi.pAudioClientPlayback = NULL;
  18906. }
  18907. }
  18908. if (deviceType == ma_device_type_playback) {
  18909. data.formatIn = pDevice->playback.format;
  18910. data.channelsIn = pDevice->playback.channels;
  18911. MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
  18912. data.shareMode = pDevice->playback.shareMode;
  18913. } else {
  18914. data.formatIn = pDevice->capture.format;
  18915. data.channelsIn = pDevice->capture.channels;
  18916. MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
  18917. data.shareMode = pDevice->capture.shareMode;
  18918. }
  18919. data.sampleRateIn = pDevice->sampleRate;
  18920. data.periodSizeInFramesIn = pDevice->wasapi.originalPeriodSizeInFrames;
  18921. data.periodSizeInMillisecondsIn = pDevice->wasapi.originalPeriodSizeInMilliseconds;
  18922. data.periodsIn = pDevice->wasapi.originalPeriods;
  18923. data.performanceProfile = pDevice->wasapi.originalPerformanceProfile;
  18924. data.noAutoConvertSRC = pDevice->wasapi.noAutoConvertSRC;
  18925. data.noDefaultQualitySRC = pDevice->wasapi.noDefaultQualitySRC;
  18926. data.noHardwareOffloading = pDevice->wasapi.noHardwareOffloading;
  18927. data.loopbackProcessID = pDevice->wasapi.loopbackProcessID;
  18928. data.loopbackProcessExclude = pDevice->wasapi.loopbackProcessExclude;
  18929. result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data);
  18930. if (result != MA_SUCCESS) {
  18931. return result;
  18932. }
  18933. /* At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. */
  18934. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
  18935. pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
  18936. pDevice->wasapi.pCaptureClient = data.pCaptureClient;
  18937. pDevice->capture.internalFormat = data.formatOut;
  18938. pDevice->capture.internalChannels = data.channelsOut;
  18939. pDevice->capture.internalSampleRate = data.sampleRateOut;
  18940. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18941. pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  18942. pDevice->capture.internalPeriods = data.periodsOut;
  18943. ma_strcpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), data.deviceName);
  18944. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, (HANDLE)pDevice->wasapi.hEventCapture);
  18945. pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
  18946. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture);
  18947. /* We must always have a valid ID. */
  18948. ma_strcpy_s_WCHAR(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi);
  18949. }
  18950. if (deviceType == ma_device_type_playback) {
  18951. pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
  18952. pDevice->wasapi.pRenderClient = data.pRenderClient;
  18953. pDevice->playback.internalFormat = data.formatOut;
  18954. pDevice->playback.internalChannels = data.channelsOut;
  18955. pDevice->playback.internalSampleRate = data.sampleRateOut;
  18956. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18957. pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  18958. pDevice->playback.internalPeriods = data.periodsOut;
  18959. ma_strcpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), data.deviceName);
  18960. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, (HANDLE)pDevice->wasapi.hEventPlayback);
  18961. pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
  18962. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback);
  18963. /* We must always have a valid ID because rerouting will look at it. */
  18964. ma_strcpy_s_WCHAR(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi);
  18965. }
  18966. return MA_SUCCESS;
  18967. }
  18968. static ma_result ma_device_init__wasapi(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  18969. {
  18970. ma_result result = MA_SUCCESS;
  18971. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18972. HRESULT hr;
  18973. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  18974. #endif
  18975. MA_ASSERT(pDevice != NULL);
  18976. MA_ZERO_OBJECT(&pDevice->wasapi);
  18977. pDevice->wasapi.usage = pConfig->wasapi.usage;
  18978. pDevice->wasapi.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18979. pDevice->wasapi.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  18980. pDevice->wasapi.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  18981. pDevice->wasapi.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  18982. pDevice->wasapi.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  18983. /* Exclusive mode is not allowed with loopback. */
  18984. if (pConfig->deviceType == ma_device_type_loopback && pConfig->playback.shareMode == ma_share_mode_exclusive) {
  18985. return MA_INVALID_DEVICE_CONFIG;
  18986. }
  18987. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  18988. ma_device_init_internal_data__wasapi data;
  18989. data.formatIn = pDescriptorCapture->format;
  18990. data.channelsIn = pDescriptorCapture->channels;
  18991. data.sampleRateIn = pDescriptorCapture->sampleRate;
  18992. MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  18993. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  18994. data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
  18995. data.periodsIn = pDescriptorCapture->periodCount;
  18996. data.shareMode = pDescriptorCapture->shareMode;
  18997. data.performanceProfile = pConfig->performanceProfile;
  18998. data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18999. data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  19000. data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  19001. data.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  19002. data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  19003. 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);
  19004. if (result != MA_SUCCESS) {
  19005. return result;
  19006. }
  19007. pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
  19008. pDevice->wasapi.pCaptureClient = data.pCaptureClient;
  19009. pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
  19010. pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  19011. pDevice->wasapi.originalPeriods = pDescriptorCapture->periodCount;
  19012. pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
  19013. /*
  19014. The event for capture needs to be manual reset for the same reason as playback. We keep the initial state set to unsignaled,
  19015. however, because we want to block until we actually have something for the first call to ma_device_read().
  19016. */
  19017. pDevice->wasapi.hEventCapture = (ma_handle)CreateEventA(NULL, FALSE, FALSE, NULL); /* Auto reset, unsignaled by default. */
  19018. if (pDevice->wasapi.hEventCapture == NULL) {
  19019. result = ma_result_from_GetLastError(GetLastError());
  19020. if (pDevice->wasapi.pCaptureClient != NULL) {
  19021. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  19022. pDevice->wasapi.pCaptureClient = NULL;
  19023. }
  19024. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  19025. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19026. pDevice->wasapi.pAudioClientCapture = NULL;
  19027. }
  19028. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for capture.");
  19029. return result;
  19030. }
  19031. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, (HANDLE)pDevice->wasapi.hEventCapture);
  19032. pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
  19033. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture);
  19034. /* We must always have a valid ID. */
  19035. ma_strcpy_s_WCHAR(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi);
  19036. /* The descriptor needs to be updated with actual values. */
  19037. pDescriptorCapture->format = data.formatOut;
  19038. pDescriptorCapture->channels = data.channelsOut;
  19039. pDescriptorCapture->sampleRate = data.sampleRateOut;
  19040. MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  19041. pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
  19042. pDescriptorCapture->periodCount = data.periodsOut;
  19043. }
  19044. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  19045. ma_device_init_internal_data__wasapi data;
  19046. data.formatIn = pDescriptorPlayback->format;
  19047. data.channelsIn = pDescriptorPlayback->channels;
  19048. data.sampleRateIn = pDescriptorPlayback->sampleRate;
  19049. MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  19050. data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
  19051. data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
  19052. data.periodsIn = pDescriptorPlayback->periodCount;
  19053. data.shareMode = pDescriptorPlayback->shareMode;
  19054. data.performanceProfile = pConfig->performanceProfile;
  19055. data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  19056. data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  19057. data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  19058. data.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  19059. data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  19060. result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data);
  19061. if (result != MA_SUCCESS) {
  19062. if (pConfig->deviceType == ma_device_type_duplex) {
  19063. if (pDevice->wasapi.pCaptureClient != NULL) {
  19064. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  19065. pDevice->wasapi.pCaptureClient = NULL;
  19066. }
  19067. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  19068. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19069. pDevice->wasapi.pAudioClientCapture = NULL;
  19070. }
  19071. CloseHandle((HANDLE)pDevice->wasapi.hEventCapture);
  19072. pDevice->wasapi.hEventCapture = NULL;
  19073. }
  19074. return result;
  19075. }
  19076. pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
  19077. pDevice->wasapi.pRenderClient = data.pRenderClient;
  19078. pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
  19079. pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  19080. pDevice->wasapi.originalPeriods = pDescriptorPlayback->periodCount;
  19081. pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
  19082. /*
  19083. The event for playback is needs to be manual reset because we want to explicitly control the fact that it becomes signalled
  19084. only after the whole available space has been filled, never before.
  19085. The playback event also needs to be initially set to a signaled state so that the first call to ma_device_write() is able
  19086. to get passed WaitForMultipleObjects().
  19087. */
  19088. pDevice->wasapi.hEventPlayback = (ma_handle)CreateEventA(NULL, FALSE, TRUE, NULL); /* Auto reset, signaled by default. */
  19089. if (pDevice->wasapi.hEventPlayback == NULL) {
  19090. result = ma_result_from_GetLastError(GetLastError());
  19091. if (pConfig->deviceType == ma_device_type_duplex) {
  19092. if (pDevice->wasapi.pCaptureClient != NULL) {
  19093. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  19094. pDevice->wasapi.pCaptureClient = NULL;
  19095. }
  19096. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  19097. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19098. pDevice->wasapi.pAudioClientCapture = NULL;
  19099. }
  19100. CloseHandle((HANDLE)pDevice->wasapi.hEventCapture);
  19101. pDevice->wasapi.hEventCapture = NULL;
  19102. }
  19103. if (pDevice->wasapi.pRenderClient != NULL) {
  19104. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  19105. pDevice->wasapi.pRenderClient = NULL;
  19106. }
  19107. if (pDevice->wasapi.pAudioClientPlayback != NULL) {
  19108. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19109. pDevice->wasapi.pAudioClientPlayback = NULL;
  19110. }
  19111. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for playback.");
  19112. return result;
  19113. }
  19114. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, (HANDLE)pDevice->wasapi.hEventPlayback);
  19115. pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
  19116. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback);
  19117. /* We must always have a valid ID because rerouting will look at it. */
  19118. ma_strcpy_s_WCHAR(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi);
  19119. /* The descriptor needs to be updated with actual values. */
  19120. pDescriptorPlayback->format = data.formatOut;
  19121. pDescriptorPlayback->channels = data.channelsOut;
  19122. pDescriptorPlayback->sampleRate = data.sampleRateOut;
  19123. MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  19124. pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
  19125. pDescriptorPlayback->periodCount = data.periodsOut;
  19126. }
  19127. /*
  19128. 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
  19129. 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
  19130. stop the device outright and let the application handle it.
  19131. */
  19132. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  19133. if (pConfig->wasapi.noAutoStreamRouting == MA_FALSE) {
  19134. if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) && pConfig->capture.pDeviceID == NULL) {
  19135. pDevice->wasapi.allowCaptureAutoStreamRouting = MA_TRUE;
  19136. }
  19137. if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID == NULL) {
  19138. pDevice->wasapi.allowPlaybackAutoStreamRouting = MA_TRUE;
  19139. }
  19140. }
  19141. ma_mutex_init(&pDevice->wasapi.rerouteLock);
  19142. hr = ma_CoCreateInstance(pDevice->pContext, &MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  19143. if (FAILED(hr)) {
  19144. ma_device_uninit__wasapi(pDevice);
  19145. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  19146. return ma_result_from_HRESULT(hr);
  19147. }
  19148. pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl;
  19149. pDevice->wasapi.notificationClient.counter = 1;
  19150. pDevice->wasapi.notificationClient.pDevice = pDevice;
  19151. hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient);
  19152. if (SUCCEEDED(hr)) {
  19153. pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator;
  19154. } else {
  19155. /* Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. */
  19156. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  19157. }
  19158. #endif
  19159. ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_FALSE);
  19160. ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
  19161. return MA_SUCCESS;
  19162. }
  19163. static ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioClient* pAudioClient, ma_uint32* pFrameCount)
  19164. {
  19165. ma_uint32 paddingFramesCount;
  19166. HRESULT hr;
  19167. ma_share_mode shareMode;
  19168. MA_ASSERT(pDevice != NULL);
  19169. MA_ASSERT(pFrameCount != NULL);
  19170. *pFrameCount = 0;
  19171. if ((ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientPlayback && (ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientCapture) {
  19172. return MA_INVALID_OPERATION;
  19173. }
  19174. /*
  19175. I've had a report that GetCurrentPadding() is returning a frame count of 0 which is preventing
  19176. higher level function calls from doing anything because it thinks nothing is available. I have
  19177. taken a look at the documentation and it looks like this is unnecessary in exclusive mode.
  19178. From Microsoft's documentation:
  19179. For an exclusive-mode rendering or capture stream that was initialized with the
  19180. AUDCLNT_STREAMFLAGS_EVENTCALLBACK flag, the client typically has no use for the padding
  19181. value reported by GetCurrentPadding. Instead, the client accesses an entire buffer during
  19182. each processing pass.
  19183. Considering this, I'm going to skip GetCurrentPadding() for exclusive mode and just report the
  19184. entire buffer. This depends on the caller making sure they wait on the event handler.
  19185. */
  19186. shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode;
  19187. if (shareMode == ma_share_mode_shared) {
  19188. /* Shared mode. */
  19189. hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount);
  19190. if (FAILED(hr)) {
  19191. return ma_result_from_HRESULT(hr);
  19192. }
  19193. if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
  19194. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback - paddingFramesCount;
  19195. } else {
  19196. *pFrameCount = paddingFramesCount;
  19197. }
  19198. } else {
  19199. /* Exclusive mode. */
  19200. if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
  19201. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback;
  19202. } else {
  19203. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesCapture;
  19204. }
  19205. }
  19206. return MA_SUCCESS;
  19207. }
  19208. static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType)
  19209. {
  19210. ma_result result;
  19211. if (deviceType == ma_device_type_duplex) {
  19212. return MA_INVALID_ARGS;
  19213. }
  19214. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== CHANGING DEVICE ===\n");
  19215. result = ma_device_reinit__wasapi(pDevice, deviceType);
  19216. if (result != MA_SUCCESS) {
  19217. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WASAPI] Reinitializing device after route change failed.\n");
  19218. return result;
  19219. }
  19220. ma_device__post_init_setup(pDevice, deviceType);
  19221. ma_device__on_notification_rerouted(pDevice);
  19222. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== DEVICE CHANGED ===\n");
  19223. return MA_SUCCESS;
  19224. }
  19225. static ma_result ma_device_start__wasapi_nolock(ma_device* pDevice)
  19226. {
  19227. HRESULT hr;
  19228. if (pDevice->pContext->wasapi.hAvrt) {
  19229. const char* pTaskName = ma_to_usage_string__wasapi(pDevice->wasapi.usage);
  19230. if (pTaskName) {
  19231. DWORD idx = 0;
  19232. pDevice->wasapi.hAvrtHandle = (ma_handle)((MA_PFN_AvSetMmThreadCharacteristicsA)pDevice->pContext->wasapi.AvSetMmThreadCharacteristicsA)(pTaskName, &idx);
  19233. }
  19234. }
  19235. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  19236. hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19237. if (FAILED(hr)) {
  19238. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device. HRESULT = %d.", (int)hr);
  19239. return ma_result_from_HRESULT(hr);
  19240. }
  19241. ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_TRUE);
  19242. }
  19243. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  19244. hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19245. if (FAILED(hr)) {
  19246. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device. HRESULT = %d.", (int)hr);
  19247. return ma_result_from_HRESULT(hr);
  19248. }
  19249. ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_TRUE);
  19250. }
  19251. return MA_SUCCESS;
  19252. }
  19253. static ma_result ma_device_start__wasapi(ma_device* pDevice)
  19254. {
  19255. ma_result result;
  19256. MA_ASSERT(pDevice != NULL);
  19257. /* Wait for any rerouting to finish before attempting to start the device. */
  19258. ma_mutex_lock(&pDevice->wasapi.rerouteLock);
  19259. {
  19260. result = ma_device_start__wasapi_nolock(pDevice);
  19261. }
  19262. ma_mutex_unlock(&pDevice->wasapi.rerouteLock);
  19263. return result;
  19264. }
  19265. static ma_result ma_device_stop__wasapi_nolock(ma_device* pDevice)
  19266. {
  19267. ma_result result;
  19268. HRESULT hr;
  19269. MA_ASSERT(pDevice != NULL);
  19270. if (pDevice->wasapi.hAvrtHandle) {
  19271. ((MA_PFN_AvRevertMmThreadCharacteristics)pDevice->pContext->wasapi.AvRevertMmThreadcharacteristics)((HANDLE)pDevice->wasapi.hAvrtHandle);
  19272. pDevice->wasapi.hAvrtHandle = NULL;
  19273. }
  19274. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  19275. hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19276. if (FAILED(hr)) {
  19277. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal capture device.");
  19278. return ma_result_from_HRESULT(hr);
  19279. }
  19280. /* The audio client needs to be reset otherwise restarting will fail. */
  19281. hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  19282. if (FAILED(hr)) {
  19283. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal capture device.");
  19284. return ma_result_from_HRESULT(hr);
  19285. }
  19286. /* If we have a mapped buffer we need to release it. */
  19287. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  19288. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19289. pDevice->wasapi.pMappedBufferCapture = NULL;
  19290. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19291. pDevice->wasapi.mappedBufferCaptureLen = 0;
  19292. }
  19293. ma_atomic_bool32_set(&pDevice->wasapi.isStartedCapture, MA_FALSE);
  19294. }
  19295. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  19296. /*
  19297. The buffer needs to be drained before stopping the device. Not doing this will result in the last few frames not getting output to
  19298. the speakers. This is a problem for very short sounds because it'll result in a significant portion of it not getting played.
  19299. */
  19300. if (ma_atomic_bool32_get(&pDevice->wasapi.isStartedPlayback)) {
  19301. /* We need to make sure we put a timeout here or else we'll risk getting stuck in a deadlock in some cases. */
  19302. DWORD waitTime = pDevice->wasapi.actualBufferSizeInFramesPlayback / pDevice->playback.internalSampleRate;
  19303. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  19304. WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, waitTime);
  19305. }
  19306. else {
  19307. ma_uint32 prevFramesAvaialablePlayback = (ma_uint32)-1;
  19308. ma_uint32 framesAvailablePlayback;
  19309. for (;;) {
  19310. result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback);
  19311. if (result != MA_SUCCESS) {
  19312. break;
  19313. }
  19314. if (framesAvailablePlayback >= pDevice->wasapi.actualBufferSizeInFramesPlayback) {
  19315. break;
  19316. }
  19317. /*
  19318. Just a safety check to avoid an infinite loop. If this iteration results in a situation where the number of available frames
  19319. 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.
  19320. */
  19321. if (framesAvailablePlayback == prevFramesAvaialablePlayback) {
  19322. break;
  19323. }
  19324. prevFramesAvaialablePlayback = framesAvailablePlayback;
  19325. WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, waitTime * 1000);
  19326. ResetEvent((HANDLE)pDevice->wasapi.hEventPlayback); /* Manual reset. */
  19327. }
  19328. }
  19329. }
  19330. hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19331. if (FAILED(hr)) {
  19332. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal playback device.");
  19333. return ma_result_from_HRESULT(hr);
  19334. }
  19335. /* The audio client needs to be reset otherwise restarting will fail. */
  19336. hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  19337. if (FAILED(hr)) {
  19338. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal playback device.");
  19339. return ma_result_from_HRESULT(hr);
  19340. }
  19341. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  19342. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  19343. pDevice->wasapi.pMappedBufferPlayback = NULL;
  19344. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  19345. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  19346. }
  19347. ma_atomic_bool32_set(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
  19348. }
  19349. return MA_SUCCESS;
  19350. }
  19351. static ma_result ma_device_stop__wasapi(ma_device* pDevice)
  19352. {
  19353. ma_result result;
  19354. MA_ASSERT(pDevice != NULL);
  19355. /* Wait for any rerouting to finish before attempting to stop the device. */
  19356. ma_mutex_lock(&pDevice->wasapi.rerouteLock);
  19357. {
  19358. result = ma_device_stop__wasapi_nolock(pDevice);
  19359. }
  19360. ma_mutex_unlock(&pDevice->wasapi.rerouteLock);
  19361. return result;
  19362. }
  19363. #ifndef MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS
  19364. #define MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS 5000
  19365. #endif
  19366. static ma_result ma_device_read__wasapi(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  19367. {
  19368. ma_result result = MA_SUCCESS;
  19369. ma_uint32 totalFramesProcessed = 0;
  19370. /*
  19371. When reading, we need to get a buffer and process all of it before releasing it. Because the
  19372. frame count (frameCount) can be different to the size of the buffer, we'll need to cache the
  19373. pointer to the buffer.
  19374. */
  19375. /* Keep running until we've processed the requested number of frames. */
  19376. while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) {
  19377. ma_uint32 framesRemaining = frameCount - totalFramesProcessed;
  19378. /* If we have a mapped data buffer, consume that first. */
  19379. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  19380. /* We have a cached data pointer so consume that before grabbing another one from WASAPI. */
  19381. ma_uint32 framesToProcessNow = framesRemaining;
  19382. if (framesToProcessNow > pDevice->wasapi.mappedBufferCaptureLen) {
  19383. framesToProcessNow = pDevice->wasapi.mappedBufferCaptureLen;
  19384. }
  19385. /* Now just copy the data over to the output buffer. */
  19386. ma_copy_pcm_frames(
  19387. ma_offset_pcm_frames_ptr(pFrames, totalFramesProcessed, pDevice->capture.internalFormat, pDevice->capture.internalChannels),
  19388. ma_offset_pcm_frames_const_ptr(pDevice->wasapi.pMappedBufferCapture, pDevice->wasapi.mappedBufferCaptureCap - pDevice->wasapi.mappedBufferCaptureLen, pDevice->capture.internalFormat, pDevice->capture.internalChannels),
  19389. framesToProcessNow,
  19390. pDevice->capture.internalFormat, pDevice->capture.internalChannels
  19391. );
  19392. totalFramesProcessed += framesToProcessNow;
  19393. pDevice->wasapi.mappedBufferCaptureLen -= framesToProcessNow;
  19394. /* If the data buffer has been fully consumed we need to release it. */
  19395. if (pDevice->wasapi.mappedBufferCaptureLen == 0) {
  19396. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19397. pDevice->wasapi.pMappedBufferCapture = NULL;
  19398. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19399. }
  19400. } else {
  19401. /* We don't have any cached data pointer, so grab another one. */
  19402. HRESULT hr;
  19403. DWORD flags = 0;
  19404. /* First just ask WASAPI for a data buffer. If it's not available, we'll wait for more. */
  19405. hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL);
  19406. if (hr == S_OK) {
  19407. /* We got a data buffer. Continue to the next loop iteration which will then read from the mapped pointer. */
  19408. pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap;
  19409. /*
  19410. There have been reports that indicate that at times the AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY is reported for every
  19411. call to IAudioCaptureClient_GetBuffer() above which results in spamming of the debug messages below. To partially
  19412. work around this, I'm only outputting these messages when MA_DEBUG_OUTPUT is explicitly defined. The better solution
  19413. would be to figure out why the flag is always getting reported.
  19414. */
  19415. #if defined(MA_DEBUG_OUTPUT)
  19416. {
  19417. if (flags != 0) {
  19418. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Capture Flags: %ld\n", flags);
  19419. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  19420. 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);
  19421. }
  19422. }
  19423. }
  19424. #endif
  19425. /* Overrun detection. */
  19426. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  19427. /* Glitched. Probably due to an overrun. */
  19428. /*
  19429. If we got an overrun it probably means we're straddling the end of the buffer. In normal capture
  19430. mode this is the fault of the client application because they're responsible for ensuring data is
  19431. processed fast enough. In duplex mode, however, the processing of audio is tied to the playback
  19432. device, so this can possibly be the result of a timing de-sync.
  19433. In capture mode we're not going to do any kind of recovery because the real fix is for the client
  19434. application to process faster. In duplex mode, we'll treat this as a desync and reset the buffers
  19435. to prevent a never-ending sequence of glitches due to straddling the end of the buffer.
  19436. */
  19437. if (pDevice->type == ma_device_type_duplex) {
  19438. /*
  19439. Experiment:
  19440. If we empty out the *entire* buffer we may end up putting ourselves into an underrun position
  19441. which isn't really any better than the overrun we're probably in right now. Instead we'll just
  19442. empty out about half.
  19443. */
  19444. ma_uint32 i;
  19445. ma_uint32 periodCount = (pDevice->wasapi.actualBufferSizeInFramesCapture / pDevice->wasapi.periodSizeInFramesCapture);
  19446. ma_uint32 iterationCount = periodCount / 2;
  19447. if ((periodCount % 2) > 0) {
  19448. iterationCount += 1;
  19449. }
  19450. for (i = 0; i < iterationCount; i += 1) {
  19451. hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19452. if (FAILED(hr)) {
  19453. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_ReleaseBuffer() failed with %ld.\n", hr);
  19454. break;
  19455. }
  19456. flags = 0;
  19457. hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL);
  19458. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || FAILED(hr)) {
  19459. /*
  19460. The buffer has been completely emptied or an error occurred. In this case we'll need
  19461. to reset the state of the mapped buffer which will trigger the next iteration to get
  19462. a fresh buffer from WASAPI.
  19463. */
  19464. pDevice->wasapi.pMappedBufferCapture = NULL;
  19465. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19466. pDevice->wasapi.mappedBufferCaptureLen = 0;
  19467. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY) {
  19468. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  19469. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied, and data discontinuity still reported.\n");
  19470. } else {
  19471. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied.\n");
  19472. }
  19473. }
  19474. if (FAILED(hr)) {
  19475. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_GetBuffer() failed with %ld.\n", hr);
  19476. }
  19477. break;
  19478. }
  19479. }
  19480. /* If at this point we have a valid buffer mapped, make sure the buffer length is set appropriately. */
  19481. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  19482. pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap;
  19483. }
  19484. }
  19485. }
  19486. continue;
  19487. } else {
  19488. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || hr == MA_AUDCLNT_E_BUFFER_ERROR) {
  19489. /*
  19490. No data is available. We need to wait for more. There's two situations to consider
  19491. here. The first is normal capture mode. If this times out it probably means the
  19492. microphone isn't delivering data for whatever reason. In this case we'll just
  19493. abort the read and return whatever we were able to get. The other situations is
  19494. loopback mode, in which case a timeout probably just means the nothing is playing
  19495. through the speakers.
  19496. */
  19497. /* Experiment: Use a shorter timeout for loopback mode. */
  19498. DWORD timeoutInMilliseconds = MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS;
  19499. if (pDevice->type == ma_device_type_loopback) {
  19500. timeoutInMilliseconds = 10;
  19501. }
  19502. if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventCapture, timeoutInMilliseconds) != WAIT_OBJECT_0) {
  19503. if (pDevice->type == ma_device_type_loopback) {
  19504. continue; /* Keep waiting in loopback mode. */
  19505. } else {
  19506. result = MA_ERROR;
  19507. break; /* Wait failed. */
  19508. }
  19509. }
  19510. /* At this point we should be able to loop back to the start of the loop and try retrieving a data buffer again. */
  19511. } else {
  19512. /* An error occurred and we need to abort. */
  19513. 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);
  19514. result = ma_result_from_HRESULT(hr);
  19515. break;
  19516. }
  19517. }
  19518. }
  19519. }
  19520. /*
  19521. If we were unable to process the entire requested frame count, but we still have a mapped buffer,
  19522. there's a good chance either an error occurred or the device was stopped mid-read. In this case
  19523. we'll need to make sure the buffer is released.
  19524. */
  19525. if (totalFramesProcessed < frameCount && pDevice->wasapi.pMappedBufferCapture != NULL) {
  19526. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  19527. pDevice->wasapi.pMappedBufferCapture = NULL;
  19528. pDevice->wasapi.mappedBufferCaptureCap = 0;
  19529. pDevice->wasapi.mappedBufferCaptureLen = 0;
  19530. }
  19531. if (pFramesRead != NULL) {
  19532. *pFramesRead = totalFramesProcessed;
  19533. }
  19534. return result;
  19535. }
  19536. static ma_result ma_device_write__wasapi(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  19537. {
  19538. ma_result result = MA_SUCCESS;
  19539. ma_uint32 totalFramesProcessed = 0;
  19540. /* Keep writing to the device until it's stopped or we've consumed all of our input. */
  19541. while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) {
  19542. ma_uint32 framesRemaining = frameCount - totalFramesProcessed;
  19543. /*
  19544. We're going to do this in a similar way to capture. We'll first check if the cached data pointer
  19545. is valid, and if so, read from that. Otherwise We will call IAudioRenderClient_GetBuffer() with
  19546. a requested buffer size equal to our actual period size. If it returns AUDCLNT_E_BUFFER_TOO_LARGE
  19547. it means we need to wait for some data to become available.
  19548. */
  19549. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  19550. /* We still have some space available in the mapped data buffer. Write to it. */
  19551. ma_uint32 framesToProcessNow = framesRemaining;
  19552. if (framesToProcessNow > (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen)) {
  19553. framesToProcessNow = (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen);
  19554. }
  19555. /* Now just copy the data over to the output buffer. */
  19556. ma_copy_pcm_frames(
  19557. ma_offset_pcm_frames_ptr(pDevice->wasapi.pMappedBufferPlayback, pDevice->wasapi.mappedBufferPlaybackLen, pDevice->playback.internalFormat, pDevice->playback.internalChannels),
  19558. ma_offset_pcm_frames_const_ptr(pFrames, totalFramesProcessed, pDevice->playback.internalFormat, pDevice->playback.internalChannels),
  19559. framesToProcessNow,
  19560. pDevice->playback.internalFormat, pDevice->playback.internalChannels
  19561. );
  19562. totalFramesProcessed += framesToProcessNow;
  19563. pDevice->wasapi.mappedBufferPlaybackLen += framesToProcessNow;
  19564. /* If the data buffer has been fully consumed we need to release it. */
  19565. if (pDevice->wasapi.mappedBufferPlaybackLen == pDevice->wasapi.mappedBufferPlaybackCap) {
  19566. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  19567. pDevice->wasapi.pMappedBufferPlayback = NULL;
  19568. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  19569. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  19570. /*
  19571. In exclusive mode we need to wait here. Exclusive mode is weird because GetBuffer() never
  19572. seems to return AUDCLNT_E_BUFFER_TOO_LARGE, which is what we normally use to determine
  19573. whether or not we need to wait for more data.
  19574. */
  19575. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  19576. if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) {
  19577. result = MA_ERROR;
  19578. break; /* Wait failed. Probably timed out. */
  19579. }
  19580. }
  19581. }
  19582. } else {
  19583. /* We don't have a mapped data buffer so we'll need to get one. */
  19584. HRESULT hr;
  19585. ma_uint32 bufferSizeInFrames;
  19586. /* Special rules for exclusive mode. */
  19587. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  19588. bufferSizeInFrames = pDevice->wasapi.actualBufferSizeInFramesPlayback;
  19589. } else {
  19590. bufferSizeInFrames = pDevice->wasapi.periodSizeInFramesPlayback;
  19591. }
  19592. hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, bufferSizeInFrames, (BYTE**)&pDevice->wasapi.pMappedBufferPlayback);
  19593. if (hr == S_OK) {
  19594. /* We have data available. */
  19595. pDevice->wasapi.mappedBufferPlaybackCap = bufferSizeInFrames;
  19596. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  19597. } else {
  19598. if (hr == MA_AUDCLNT_E_BUFFER_TOO_LARGE || hr == MA_AUDCLNT_E_BUFFER_ERROR) {
  19599. /* Not enough data available. We need to wait for more. */
  19600. if (WaitForSingleObject((HANDLE)pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) {
  19601. result = MA_ERROR;
  19602. break; /* Wait failed. Probably timed out. */
  19603. }
  19604. } else {
  19605. /* Some error occurred. We'll need to abort. */
  19606. 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);
  19607. result = ma_result_from_HRESULT(hr);
  19608. break;
  19609. }
  19610. }
  19611. }
  19612. }
  19613. if (pFramesWritten != NULL) {
  19614. *pFramesWritten = totalFramesProcessed;
  19615. }
  19616. return result;
  19617. }
  19618. static ma_result ma_device_data_loop_wakeup__wasapi(ma_device* pDevice)
  19619. {
  19620. MA_ASSERT(pDevice != NULL);
  19621. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  19622. SetEvent((HANDLE)pDevice->wasapi.hEventCapture);
  19623. }
  19624. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  19625. SetEvent((HANDLE)pDevice->wasapi.hEventPlayback);
  19626. }
  19627. return MA_SUCCESS;
  19628. }
  19629. static ma_result ma_context_uninit__wasapi(ma_context* pContext)
  19630. {
  19631. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_QUIT__WASAPI);
  19632. MA_ASSERT(pContext != NULL);
  19633. MA_ASSERT(pContext->backend == ma_backend_wasapi);
  19634. ma_context_post_command__wasapi(pContext, &cmd);
  19635. ma_thread_wait(&pContext->wasapi.commandThread);
  19636. if (pContext->wasapi.hAvrt) {
  19637. ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hAvrt);
  19638. pContext->wasapi.hAvrt = NULL;
  19639. }
  19640. #if defined(MA_WIN32_UWP)
  19641. {
  19642. if (pContext->wasapi.hMMDevapi) {
  19643. ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hMMDevapi);
  19644. pContext->wasapi.hMMDevapi = NULL;
  19645. }
  19646. }
  19647. #endif
  19648. /* Only after the thread has been terminated can we uninitialize the sync objects for the command thread. */
  19649. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19650. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19651. return MA_SUCCESS;
  19652. }
  19653. static ma_result ma_context_init__wasapi(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  19654. {
  19655. ma_result result = MA_SUCCESS;
  19656. MA_ASSERT(pContext != NULL);
  19657. (void)pConfig;
  19658. #ifdef MA_WIN32_DESKTOP
  19659. /*
  19660. WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven
  19661. exclusive mode does not work until SP1.
  19662. Unfortunately older compilers don't define these functions so we need to dynamically load them in order to avoid a link error.
  19663. */
  19664. {
  19665. ma_OSVERSIONINFOEXW osvi;
  19666. ma_handle kernel32DLL;
  19667. ma_PFNVerifyVersionInfoW _VerifyVersionInfoW;
  19668. ma_PFNVerSetConditionMask _VerSetConditionMask;
  19669. kernel32DLL = ma_dlopen(ma_context_get_log(pContext), "kernel32.dll");
  19670. if (kernel32DLL == NULL) {
  19671. return MA_NO_BACKEND;
  19672. }
  19673. _VerifyVersionInfoW = (ma_PFNVerifyVersionInfoW )ma_dlsym(ma_context_get_log(pContext), kernel32DLL, "VerifyVersionInfoW");
  19674. _VerSetConditionMask = (ma_PFNVerSetConditionMask)ma_dlsym(ma_context_get_log(pContext), kernel32DLL, "VerSetConditionMask");
  19675. if (_VerifyVersionInfoW == NULL || _VerSetConditionMask == NULL) {
  19676. ma_dlclose(ma_context_get_log(pContext), kernel32DLL);
  19677. return MA_NO_BACKEND;
  19678. }
  19679. MA_ZERO_OBJECT(&osvi);
  19680. osvi.dwOSVersionInfoSize = sizeof(osvi);
  19681. osvi.dwMajorVersion = ((MA_WIN32_WINNT_VISTA >> 8) & 0xFF);
  19682. osvi.dwMinorVersion = ((MA_WIN32_WINNT_VISTA >> 0) & 0xFF);
  19683. osvi.wServicePackMajor = 1;
  19684. 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))) {
  19685. result = MA_SUCCESS;
  19686. } else {
  19687. result = MA_NO_BACKEND;
  19688. }
  19689. ma_dlclose(ma_context_get_log(pContext), kernel32DLL);
  19690. }
  19691. #endif
  19692. if (result != MA_SUCCESS) {
  19693. return result;
  19694. }
  19695. MA_ZERO_OBJECT(&pContext->wasapi);
  19696. /*
  19697. Annoyingly, WASAPI does not allow you to release an IAudioClient object from a different thread
  19698. than the one that retrieved it with GetService(). This can result in a deadlock in two
  19699. situations:
  19700. 1) When calling ma_device_uninit() from a different thread to ma_device_init(); and
  19701. 2) When uninitializing and reinitializing the internal IAudioClient object in response to
  19702. automatic stream routing.
  19703. We could define ma_device_uninit() such that it must be called on the same thread as
  19704. ma_device_init(). We could also just not release the IAudioClient when performing automatic
  19705. stream routing to avoid the deadlock. Neither of these are acceptable solutions in my view so
  19706. we're going to have to work around this with a worker thread. This is not ideal, but I can't
  19707. think of a better way to do this.
  19708. More information about this can be found here:
  19709. https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nn-audioclient-iaudiorenderclient
  19710. Note this section:
  19711. When releasing an IAudioRenderClient interface instance, the client must call the interface's
  19712. Release method from the same thread as the call to IAudioClient::GetService that created the
  19713. object.
  19714. */
  19715. {
  19716. result = ma_mutex_init(&pContext->wasapi.commandLock);
  19717. if (result != MA_SUCCESS) {
  19718. return result;
  19719. }
  19720. result = ma_semaphore_init(0, &pContext->wasapi.commandSem);
  19721. if (result != MA_SUCCESS) {
  19722. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19723. return result;
  19724. }
  19725. result = ma_thread_create(&pContext->wasapi.commandThread, ma_thread_priority_normal, 0, ma_context_command_thread__wasapi, pContext, &pContext->allocationCallbacks);
  19726. if (result != MA_SUCCESS) {
  19727. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19728. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19729. return result;
  19730. }
  19731. #if defined(MA_WIN32_UWP)
  19732. {
  19733. /* Link to mmdevapi so we can get access to ActivateAudioInterfaceAsync(). */
  19734. pContext->wasapi.hMMDevapi = ma_dlopen(ma_context_get_log(pContext), "mmdevapi.dll");
  19735. if (pContext->wasapi.hMMDevapi) {
  19736. pContext->wasapi.ActivateAudioInterfaceAsync = ma_dlsym(ma_context_get_log(pContext), pContext->wasapi.hMMDevapi, "ActivateAudioInterfaceAsync");
  19737. if (pContext->wasapi.ActivateAudioInterfaceAsync == NULL) {
  19738. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19739. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19740. ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hMMDevapi);
  19741. return MA_NO_BACKEND; /* ActivateAudioInterfaceAsync() could not be loaded. */
  19742. }
  19743. } else {
  19744. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  19745. ma_mutex_uninit(&pContext->wasapi.commandLock);
  19746. return MA_NO_BACKEND; /* Failed to load mmdevapi.dll which is required for ActivateAudioInterfaceAsync() */
  19747. }
  19748. }
  19749. #endif
  19750. /* Optionally use the Avrt API to specify the audio thread's latency sensitivity requirements */
  19751. pContext->wasapi.hAvrt = ma_dlopen(ma_context_get_log(pContext), "avrt.dll");
  19752. if (pContext->wasapi.hAvrt) {
  19753. pContext->wasapi.AvSetMmThreadCharacteristicsA = ma_dlsym(ma_context_get_log(pContext), pContext->wasapi.hAvrt, "AvSetMmThreadCharacteristicsA");
  19754. pContext->wasapi.AvRevertMmThreadcharacteristics = ma_dlsym(ma_context_get_log(pContext), pContext->wasapi.hAvrt, "AvRevertMmThreadCharacteristics");
  19755. /* If either function could not be found, disable use of avrt entirely. */
  19756. if (!pContext->wasapi.AvSetMmThreadCharacteristicsA || !pContext->wasapi.AvRevertMmThreadcharacteristics) {
  19757. pContext->wasapi.AvSetMmThreadCharacteristicsA = NULL;
  19758. pContext->wasapi.AvRevertMmThreadcharacteristics = NULL;
  19759. ma_dlclose(ma_context_get_log(pContext), pContext->wasapi.hAvrt);
  19760. pContext->wasapi.hAvrt = NULL;
  19761. }
  19762. }
  19763. }
  19764. pCallbacks->onContextInit = ma_context_init__wasapi;
  19765. pCallbacks->onContextUninit = ma_context_uninit__wasapi;
  19766. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__wasapi;
  19767. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__wasapi;
  19768. pCallbacks->onDeviceInit = ma_device_init__wasapi;
  19769. pCallbacks->onDeviceUninit = ma_device_uninit__wasapi;
  19770. pCallbacks->onDeviceStart = ma_device_start__wasapi;
  19771. pCallbacks->onDeviceStop = ma_device_stop__wasapi;
  19772. pCallbacks->onDeviceRead = ma_device_read__wasapi;
  19773. pCallbacks->onDeviceWrite = ma_device_write__wasapi;
  19774. pCallbacks->onDeviceDataLoop = NULL;
  19775. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__wasapi;
  19776. return MA_SUCCESS;
  19777. }
  19778. #endif
  19779. /******************************************************************************
  19780. DirectSound Backend
  19781. ******************************************************************************/
  19782. #ifdef MA_HAS_DSOUND
  19783. /*#include <dsound.h>*/
  19784. /*static const GUID MA_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}};*/
  19785. /* miniaudio only uses priority or exclusive modes. */
  19786. #define MA_DSSCL_NORMAL 1
  19787. #define MA_DSSCL_PRIORITY 2
  19788. #define MA_DSSCL_EXCLUSIVE 3
  19789. #define MA_DSSCL_WRITEPRIMARY 4
  19790. #define MA_DSCAPS_PRIMARYMONO 0x00000001
  19791. #define MA_DSCAPS_PRIMARYSTEREO 0x00000002
  19792. #define MA_DSCAPS_PRIMARY8BIT 0x00000004
  19793. #define MA_DSCAPS_PRIMARY16BIT 0x00000008
  19794. #define MA_DSCAPS_CONTINUOUSRATE 0x00000010
  19795. #define MA_DSCAPS_EMULDRIVER 0x00000020
  19796. #define MA_DSCAPS_CERTIFIED 0x00000040
  19797. #define MA_DSCAPS_SECONDARYMONO 0x00000100
  19798. #define MA_DSCAPS_SECONDARYSTEREO 0x00000200
  19799. #define MA_DSCAPS_SECONDARY8BIT 0x00000400
  19800. #define MA_DSCAPS_SECONDARY16BIT 0x00000800
  19801. #define MA_DSBCAPS_PRIMARYBUFFER 0x00000001
  19802. #define MA_DSBCAPS_STATIC 0x00000002
  19803. #define MA_DSBCAPS_LOCHARDWARE 0x00000004
  19804. #define MA_DSBCAPS_LOCSOFTWARE 0x00000008
  19805. #define MA_DSBCAPS_CTRL3D 0x00000010
  19806. #define MA_DSBCAPS_CTRLFREQUENCY 0x00000020
  19807. #define MA_DSBCAPS_CTRLPAN 0x00000040
  19808. #define MA_DSBCAPS_CTRLVOLUME 0x00000080
  19809. #define MA_DSBCAPS_CTRLPOSITIONNOTIFY 0x00000100
  19810. #define MA_DSBCAPS_CTRLFX 0x00000200
  19811. #define MA_DSBCAPS_STICKYFOCUS 0x00004000
  19812. #define MA_DSBCAPS_GLOBALFOCUS 0x00008000
  19813. #define MA_DSBCAPS_GETCURRENTPOSITION2 0x00010000
  19814. #define MA_DSBCAPS_MUTE3DATMAXDISTANCE 0x00020000
  19815. #define MA_DSBCAPS_LOCDEFER 0x00040000
  19816. #define MA_DSBCAPS_TRUEPLAYPOSITION 0x00080000
  19817. #define MA_DSBPLAY_LOOPING 0x00000001
  19818. #define MA_DSBPLAY_LOCHARDWARE 0x00000002
  19819. #define MA_DSBPLAY_LOCSOFTWARE 0x00000004
  19820. #define MA_DSBPLAY_TERMINATEBY_TIME 0x00000008
  19821. #define MA_DSBPLAY_TERMINATEBY_DISTANCE 0x00000010
  19822. #define MA_DSBPLAY_TERMINATEBY_PRIORITY 0x00000020
  19823. #define MA_DSCBSTART_LOOPING 0x00000001
  19824. typedef struct
  19825. {
  19826. DWORD dwSize;
  19827. DWORD dwFlags;
  19828. DWORD dwBufferBytes;
  19829. DWORD dwReserved;
  19830. MA_WAVEFORMATEX* lpwfxFormat;
  19831. GUID guid3DAlgorithm;
  19832. } MA_DSBUFFERDESC;
  19833. typedef struct
  19834. {
  19835. DWORD dwSize;
  19836. DWORD dwFlags;
  19837. DWORD dwBufferBytes;
  19838. DWORD dwReserved;
  19839. MA_WAVEFORMATEX* lpwfxFormat;
  19840. DWORD dwFXCount;
  19841. void* lpDSCFXDesc; /* <-- miniaudio doesn't use this, so set to void*. */
  19842. } MA_DSCBUFFERDESC;
  19843. typedef struct
  19844. {
  19845. DWORD dwSize;
  19846. DWORD dwFlags;
  19847. DWORD dwMinSecondarySampleRate;
  19848. DWORD dwMaxSecondarySampleRate;
  19849. DWORD dwPrimaryBuffers;
  19850. DWORD dwMaxHwMixingAllBuffers;
  19851. DWORD dwMaxHwMixingStaticBuffers;
  19852. DWORD dwMaxHwMixingStreamingBuffers;
  19853. DWORD dwFreeHwMixingAllBuffers;
  19854. DWORD dwFreeHwMixingStaticBuffers;
  19855. DWORD dwFreeHwMixingStreamingBuffers;
  19856. DWORD dwMaxHw3DAllBuffers;
  19857. DWORD dwMaxHw3DStaticBuffers;
  19858. DWORD dwMaxHw3DStreamingBuffers;
  19859. DWORD dwFreeHw3DAllBuffers;
  19860. DWORD dwFreeHw3DStaticBuffers;
  19861. DWORD dwFreeHw3DStreamingBuffers;
  19862. DWORD dwTotalHwMemBytes;
  19863. DWORD dwFreeHwMemBytes;
  19864. DWORD dwMaxContigFreeHwMemBytes;
  19865. DWORD dwUnlockTransferRateHwBuffers;
  19866. DWORD dwPlayCpuOverheadSwBuffers;
  19867. DWORD dwReserved1;
  19868. DWORD dwReserved2;
  19869. } MA_DSCAPS;
  19870. typedef struct
  19871. {
  19872. DWORD dwSize;
  19873. DWORD dwFlags;
  19874. DWORD dwBufferBytes;
  19875. DWORD dwUnlockTransferRate;
  19876. DWORD dwPlayCpuOverhead;
  19877. } MA_DSBCAPS;
  19878. typedef struct
  19879. {
  19880. DWORD dwSize;
  19881. DWORD dwFlags;
  19882. DWORD dwFormats;
  19883. DWORD dwChannels;
  19884. } MA_DSCCAPS;
  19885. typedef struct
  19886. {
  19887. DWORD dwSize;
  19888. DWORD dwFlags;
  19889. DWORD dwBufferBytes;
  19890. DWORD dwReserved;
  19891. } MA_DSCBCAPS;
  19892. typedef struct
  19893. {
  19894. DWORD dwOffset;
  19895. HANDLE hEventNotify;
  19896. } MA_DSBPOSITIONNOTIFY;
  19897. typedef struct ma_IDirectSound ma_IDirectSound;
  19898. typedef struct ma_IDirectSoundBuffer ma_IDirectSoundBuffer;
  19899. typedef struct ma_IDirectSoundCapture ma_IDirectSoundCapture;
  19900. typedef struct ma_IDirectSoundCaptureBuffer ma_IDirectSoundCaptureBuffer;
  19901. typedef struct ma_IDirectSoundNotify ma_IDirectSoundNotify;
  19902. /*
  19903. COM objects. The way these work is that you have a vtable (a list of function pointers, kind of
  19904. like how C++ works internally), and then you have a structure with a single member, which is a
  19905. pointer to the vtable. The vtable is where the methods of the object are defined. Methods need
  19906. to be in a specific order, and parent classes need to have their methods declared first.
  19907. */
  19908. /* IDirectSound */
  19909. typedef struct
  19910. {
  19911. /* IUnknown */
  19912. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSound* pThis, const IID* const riid, void** ppObject);
  19913. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSound* pThis);
  19914. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSound* pThis);
  19915. /* IDirectSound */
  19916. HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter);
  19917. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps);
  19918. HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate);
  19919. HRESULT (STDMETHODCALLTYPE * SetCooperativeLevel) (ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel);
  19920. HRESULT (STDMETHODCALLTYPE * Compact) (ma_IDirectSound* pThis);
  19921. HRESULT (STDMETHODCALLTYPE * GetSpeakerConfig) (ma_IDirectSound* pThis, DWORD* pSpeakerConfig);
  19922. HRESULT (STDMETHODCALLTYPE * SetSpeakerConfig) (ma_IDirectSound* pThis, DWORD dwSpeakerConfig);
  19923. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSound* pThis, const GUID* pGuidDevice);
  19924. } ma_IDirectSoundVtbl;
  19925. struct ma_IDirectSound
  19926. {
  19927. ma_IDirectSoundVtbl* lpVtbl;
  19928. };
  19929. static MA_INLINE HRESULT ma_IDirectSound_QueryInterface(ma_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19930. static MA_INLINE ULONG ma_IDirectSound_AddRef(ma_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19931. static MA_INLINE ULONG ma_IDirectSound_Release(ma_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); }
  19932. 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); }
  19933. static MA_INLINE HRESULT ma_IDirectSound_GetCaps(ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); }
  19934. static MA_INLINE HRESULT ma_IDirectSound_DuplicateSoundBuffer(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); }
  19935. static MA_INLINE HRESULT ma_IDirectSound_SetCooperativeLevel(ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); }
  19936. static MA_INLINE HRESULT ma_IDirectSound_Compact(ma_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); }
  19937. static MA_INLINE HRESULT ma_IDirectSound_GetSpeakerConfig(ma_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); }
  19938. static MA_INLINE HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); }
  19939. static MA_INLINE HRESULT ma_IDirectSound_Initialize(ma_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
  19940. /* IDirectSoundBuffer */
  19941. typedef struct
  19942. {
  19943. /* IUnknown */
  19944. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject);
  19945. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundBuffer* pThis);
  19946. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundBuffer* pThis);
  19947. /* IDirectSoundBuffer */
  19948. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps);
  19949. HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor);
  19950. HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
  19951. HRESULT (STDMETHODCALLTYPE * GetVolume) (ma_IDirectSoundBuffer* pThis, LONG* pVolume);
  19952. HRESULT (STDMETHODCALLTYPE * GetPan) (ma_IDirectSoundBuffer* pThis, LONG* pPan);
  19953. HRESULT (STDMETHODCALLTYPE * GetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD* pFrequency);
  19954. HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundBuffer* pThis, DWORD* pStatus);
  19955. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc);
  19956. HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
  19957. HRESULT (STDMETHODCALLTYPE * Play) (ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags);
  19958. HRESULT (STDMETHODCALLTYPE * SetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition);
  19959. HRESULT (STDMETHODCALLTYPE * SetFormat) (ma_IDirectSoundBuffer* pThis, const MA_WAVEFORMATEX* pFormat);
  19960. HRESULT (STDMETHODCALLTYPE * SetVolume) (ma_IDirectSoundBuffer* pThis, LONG volume);
  19961. HRESULT (STDMETHODCALLTYPE * SetPan) (ma_IDirectSoundBuffer* pThis, LONG pan);
  19962. HRESULT (STDMETHODCALLTYPE * SetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD dwFrequency);
  19963. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundBuffer* pThis);
  19964. HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
  19965. HRESULT (STDMETHODCALLTYPE * Restore) (ma_IDirectSoundBuffer* pThis);
  19966. } ma_IDirectSoundBufferVtbl;
  19967. struct ma_IDirectSoundBuffer
  19968. {
  19969. ma_IDirectSoundBufferVtbl* lpVtbl;
  19970. };
  19971. static MA_INLINE HRESULT ma_IDirectSoundBuffer_QueryInterface(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19972. static MA_INLINE ULONG ma_IDirectSoundBuffer_AddRef(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19973. static MA_INLINE ULONG ma_IDirectSoundBuffer_Release(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
  19974. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCaps(ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); }
  19975. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); }
  19976. 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); }
  19977. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetVolume(ma_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); }
  19978. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetPan(ma_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); }
  19979. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFrequency(ma_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); }
  19980. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetStatus(ma_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
  19981. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Initialize(ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); }
  19982. 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); }
  19983. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Play(ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); }
  19984. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); }
  19985. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFormat(ma_IDirectSoundBuffer* pThis, const MA_WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); }
  19986. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetVolume(ma_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); }
  19987. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetPan(ma_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); }
  19988. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFrequency(ma_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); }
  19989. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Stop(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
  19990. 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); }
  19991. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Restore(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); }
  19992. /* IDirectSoundCapture */
  19993. typedef struct
  19994. {
  19995. /* IUnknown */
  19996. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject);
  19997. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCapture* pThis);
  19998. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCapture* pThis);
  19999. /* IDirectSoundCapture */
  20000. HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter);
  20001. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps);
  20002. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice);
  20003. } ma_IDirectSoundCaptureVtbl;
  20004. struct ma_IDirectSoundCapture
  20005. {
  20006. ma_IDirectSoundCaptureVtbl* lpVtbl;
  20007. };
  20008. static MA_INLINE HRESULT ma_IDirectSoundCapture_QueryInterface (ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  20009. static MA_INLINE ULONG ma_IDirectSoundCapture_AddRef (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  20010. static MA_INLINE ULONG ma_IDirectSoundCapture_Release (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); }
  20011. 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); }
  20012. static MA_INLINE HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); }
  20013. static MA_INLINE HRESULT ma_IDirectSoundCapture_Initialize (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
  20014. /* IDirectSoundCaptureBuffer */
  20015. typedef struct
  20016. {
  20017. /* IUnknown */
  20018. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject);
  20019. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCaptureBuffer* pThis);
  20020. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCaptureBuffer* pThis);
  20021. /* IDirectSoundCaptureBuffer */
  20022. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps);
  20023. HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition);
  20024. HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundCaptureBuffer* pThis, MA_WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
  20025. HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus);
  20026. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc);
  20027. HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
  20028. HRESULT (STDMETHODCALLTYPE * Start) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags);
  20029. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundCaptureBuffer* pThis);
  20030. HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
  20031. } ma_IDirectSoundCaptureBufferVtbl;
  20032. struct ma_IDirectSoundCaptureBuffer
  20033. {
  20034. ma_IDirectSoundCaptureBufferVtbl* lpVtbl;
  20035. };
  20036. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_QueryInterface(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  20037. static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_AddRef(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  20038. static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_Release(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
  20039. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCaps(ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); }
  20040. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCurrentPosition(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); }
  20041. 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); }
  20042. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetStatus(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
  20043. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Initialize(ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); }
  20044. 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); }
  20045. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Start(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); }
  20046. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
  20047. 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); }
  20048. /* IDirectSoundNotify */
  20049. typedef struct
  20050. {
  20051. /* IUnknown */
  20052. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject);
  20053. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundNotify* pThis);
  20054. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundNotify* pThis);
  20055. /* IDirectSoundNotify */
  20056. HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies);
  20057. } ma_IDirectSoundNotifyVtbl;
  20058. struct ma_IDirectSoundNotify
  20059. {
  20060. ma_IDirectSoundNotifyVtbl* lpVtbl;
  20061. };
  20062. static MA_INLINE HRESULT ma_IDirectSoundNotify_QueryInterface(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  20063. static MA_INLINE ULONG ma_IDirectSoundNotify_AddRef(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  20064. static MA_INLINE ULONG ma_IDirectSoundNotify_Release(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); }
  20065. static MA_INLINE HRESULT ma_IDirectSoundNotify_SetNotificationPositions(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies) { return pThis->lpVtbl->SetNotificationPositions(pThis, dwPositionNotifies, pPositionNotifies); }
  20066. typedef BOOL (CALLBACK * ma_DSEnumCallbackAProc) (GUID* pDeviceGUID, const char* pDeviceDescription, const char* pModule, void* pContext);
  20067. typedef HRESULT (WINAPI * ma_DirectSoundCreateProc) (const GUID* pcGuidDevice, ma_IDirectSound** ppDS8, ma_IUnknown* pUnkOuter);
  20068. typedef HRESULT (WINAPI * ma_DirectSoundEnumerateAProc) (ma_DSEnumCallbackAProc pDSEnumCallback, void* pContext);
  20069. typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, ma_IDirectSoundCapture** ppDSC8, ma_IUnknown* pUnkOuter);
  20070. typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, void* pContext);
  20071. static ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint32 sampleRateMax)
  20072. {
  20073. /* Normalize the range in case we were given something stupid. */
  20074. if (sampleRateMin < (ma_uint32)ma_standard_sample_rate_min) {
  20075. sampleRateMin = (ma_uint32)ma_standard_sample_rate_min;
  20076. }
  20077. if (sampleRateMax > (ma_uint32)ma_standard_sample_rate_max) {
  20078. sampleRateMax = (ma_uint32)ma_standard_sample_rate_max;
  20079. }
  20080. if (sampleRateMin > sampleRateMax) {
  20081. sampleRateMin = sampleRateMax;
  20082. }
  20083. if (sampleRateMin == sampleRateMax) {
  20084. return sampleRateMax;
  20085. } else {
  20086. size_t iStandardRate;
  20087. for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
  20088. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
  20089. if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) {
  20090. return standardRate;
  20091. }
  20092. }
  20093. }
  20094. /* Should never get here. */
  20095. MA_ASSERT(MA_FALSE);
  20096. return 0;
  20097. }
  20098. /*
  20099. Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown,
  20100. the channel count and channel map will be left unmodified.
  20101. */
  20102. static void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut)
  20103. {
  20104. WORD channels;
  20105. DWORD channelMap;
  20106. channels = 0;
  20107. if (pChannelsOut != NULL) {
  20108. channels = *pChannelsOut;
  20109. }
  20110. channelMap = 0;
  20111. if (pChannelMapOut != NULL) {
  20112. channelMap = *pChannelMapOut;
  20113. }
  20114. /*
  20115. The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper
  20116. 16 bits is for the geometry.
  20117. */
  20118. switch ((BYTE)(speakerConfig)) {
  20119. case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  20120. case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break;
  20121. case 3 /*DSSPEAKER_QUAD*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  20122. case 4 /*DSSPEAKER_STEREO*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  20123. case 5 /*DSSPEAKER_SURROUND*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER; break;
  20124. 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;
  20125. 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;
  20126. 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;
  20127. 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;
  20128. default: break;
  20129. }
  20130. if (pChannelsOut != NULL) {
  20131. *pChannelsOut = channels;
  20132. }
  20133. if (pChannelMapOut != NULL) {
  20134. *pChannelMapOut = channelMap;
  20135. }
  20136. }
  20137. static ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSound** ppDirectSound)
  20138. {
  20139. ma_IDirectSound* pDirectSound;
  20140. HWND hWnd;
  20141. HRESULT hr;
  20142. MA_ASSERT(pContext != NULL);
  20143. MA_ASSERT(ppDirectSound != NULL);
  20144. *ppDirectSound = NULL;
  20145. pDirectSound = NULL;
  20146. if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) {
  20147. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.");
  20148. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  20149. }
  20150. /* The cooperative level must be set before doing anything else. */
  20151. hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)();
  20152. if (hWnd == 0) {
  20153. hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)();
  20154. }
  20155. hr = ma_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == ma_share_mode_exclusive) ? MA_DSSCL_EXCLUSIVE : MA_DSSCL_PRIORITY);
  20156. if (FAILED(hr)) {
  20157. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device.");
  20158. return ma_result_from_HRESULT(hr);
  20159. }
  20160. *ppDirectSound = pDirectSound;
  20161. return MA_SUCCESS;
  20162. }
  20163. static ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSoundCapture** ppDirectSoundCapture)
  20164. {
  20165. ma_IDirectSoundCapture* pDirectSoundCapture;
  20166. HRESULT hr;
  20167. MA_ASSERT(pContext != NULL);
  20168. MA_ASSERT(ppDirectSoundCapture != NULL);
  20169. /* DirectSound does not support exclusive mode for capture. */
  20170. if (shareMode == ma_share_mode_exclusive) {
  20171. return MA_SHARE_MODE_NOT_SUPPORTED;
  20172. }
  20173. *ppDirectSoundCapture = NULL;
  20174. pDirectSoundCapture = NULL;
  20175. hr = ((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL);
  20176. if (FAILED(hr)) {
  20177. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.");
  20178. return ma_result_from_HRESULT(hr);
  20179. }
  20180. *ppDirectSoundCapture = pDirectSoundCapture;
  20181. return MA_SUCCESS;
  20182. }
  20183. static ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate)
  20184. {
  20185. HRESULT hr;
  20186. MA_DSCCAPS caps;
  20187. WORD bitsPerSample;
  20188. DWORD sampleRate;
  20189. MA_ASSERT(pContext != NULL);
  20190. MA_ASSERT(pDirectSoundCapture != NULL);
  20191. if (pChannels) {
  20192. *pChannels = 0;
  20193. }
  20194. if (pBitsPerSample) {
  20195. *pBitsPerSample = 0;
  20196. }
  20197. if (pSampleRate) {
  20198. *pSampleRate = 0;
  20199. }
  20200. MA_ZERO_OBJECT(&caps);
  20201. caps.dwSize = sizeof(caps);
  20202. hr = ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps);
  20203. if (FAILED(hr)) {
  20204. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device.");
  20205. return ma_result_from_HRESULT(hr);
  20206. }
  20207. if (pChannels) {
  20208. *pChannels = (WORD)caps.dwChannels;
  20209. }
  20210. /* 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. */
  20211. bitsPerSample = 16;
  20212. sampleRate = 48000;
  20213. if (caps.dwChannels == 1) {
  20214. if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) {
  20215. sampleRate = 48000;
  20216. } else if ((caps.dwFormats & WAVE_FORMAT_44M16) != 0) {
  20217. sampleRate = 44100;
  20218. } else if ((caps.dwFormats & WAVE_FORMAT_2M16) != 0) {
  20219. sampleRate = 22050;
  20220. } else if ((caps.dwFormats & WAVE_FORMAT_1M16) != 0) {
  20221. sampleRate = 11025;
  20222. } else if ((caps.dwFormats & WAVE_FORMAT_96M16) != 0) {
  20223. sampleRate = 96000;
  20224. } else {
  20225. bitsPerSample = 8;
  20226. if ((caps.dwFormats & WAVE_FORMAT_48M08) != 0) {
  20227. sampleRate = 48000;
  20228. } else if ((caps.dwFormats & WAVE_FORMAT_44M08) != 0) {
  20229. sampleRate = 44100;
  20230. } else if ((caps.dwFormats & WAVE_FORMAT_2M08) != 0) {
  20231. sampleRate = 22050;
  20232. } else if ((caps.dwFormats & WAVE_FORMAT_1M08) != 0) {
  20233. sampleRate = 11025;
  20234. } else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) {
  20235. sampleRate = 96000;
  20236. } else {
  20237. bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
  20238. }
  20239. }
  20240. } else if (caps.dwChannels == 2) {
  20241. if ((caps.dwFormats & WAVE_FORMAT_48S16) != 0) {
  20242. sampleRate = 48000;
  20243. } else if ((caps.dwFormats & WAVE_FORMAT_44S16) != 0) {
  20244. sampleRate = 44100;
  20245. } else if ((caps.dwFormats & WAVE_FORMAT_2S16) != 0) {
  20246. sampleRate = 22050;
  20247. } else if ((caps.dwFormats & WAVE_FORMAT_1S16) != 0) {
  20248. sampleRate = 11025;
  20249. } else if ((caps.dwFormats & WAVE_FORMAT_96S16) != 0) {
  20250. sampleRate = 96000;
  20251. } else {
  20252. bitsPerSample = 8;
  20253. if ((caps.dwFormats & WAVE_FORMAT_48S08) != 0) {
  20254. sampleRate = 48000;
  20255. } else if ((caps.dwFormats & WAVE_FORMAT_44S08) != 0) {
  20256. sampleRate = 44100;
  20257. } else if ((caps.dwFormats & WAVE_FORMAT_2S08) != 0) {
  20258. sampleRate = 22050;
  20259. } else if ((caps.dwFormats & WAVE_FORMAT_1S08) != 0) {
  20260. sampleRate = 11025;
  20261. } else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) {
  20262. sampleRate = 96000;
  20263. } else {
  20264. bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
  20265. }
  20266. }
  20267. }
  20268. if (pBitsPerSample) {
  20269. *pBitsPerSample = bitsPerSample;
  20270. }
  20271. if (pSampleRate) {
  20272. *pSampleRate = sampleRate;
  20273. }
  20274. return MA_SUCCESS;
  20275. }
  20276. typedef struct
  20277. {
  20278. ma_context* pContext;
  20279. ma_device_type deviceType;
  20280. ma_enum_devices_callback_proc callback;
  20281. void* pUserData;
  20282. ma_bool32 terminated;
  20283. } ma_context_enumerate_devices_callback_data__dsound;
  20284. static BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(GUID* lpGuid, const char* lpcstrDescription, const char* lpcstrModule, void* lpContext)
  20285. {
  20286. ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext;
  20287. ma_device_info deviceInfo;
  20288. (void)lpcstrModule;
  20289. MA_ZERO_OBJECT(&deviceInfo);
  20290. /* ID. */
  20291. if (lpGuid != NULL) {
  20292. MA_COPY_MEMORY(deviceInfo.id.dsound, lpGuid, 16);
  20293. } else {
  20294. MA_ZERO_MEMORY(deviceInfo.id.dsound, 16);
  20295. deviceInfo.isDefault = MA_TRUE;
  20296. }
  20297. /* Name / Description */
  20298. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1);
  20299. /* Call the callback function, but make sure we stop enumerating if the callee requested so. */
  20300. MA_ASSERT(pData != NULL);
  20301. pData->terminated = (pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData) == MA_FALSE);
  20302. if (pData->terminated) {
  20303. return FALSE; /* Stop enumeration. */
  20304. } else {
  20305. return TRUE; /* Continue enumeration. */
  20306. }
  20307. }
  20308. static ma_result ma_context_enumerate_devices__dsound(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  20309. {
  20310. ma_context_enumerate_devices_callback_data__dsound data;
  20311. MA_ASSERT(pContext != NULL);
  20312. MA_ASSERT(callback != NULL);
  20313. data.pContext = pContext;
  20314. data.callback = callback;
  20315. data.pUserData = pUserData;
  20316. data.terminated = MA_FALSE;
  20317. /* Playback. */
  20318. if (!data.terminated) {
  20319. data.deviceType = ma_device_type_playback;
  20320. ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
  20321. }
  20322. /* Capture. */
  20323. if (!data.terminated) {
  20324. data.deviceType = ma_device_type_capture;
  20325. ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
  20326. }
  20327. return MA_SUCCESS;
  20328. }
  20329. typedef struct
  20330. {
  20331. const ma_device_id* pDeviceID;
  20332. ma_device_info* pDeviceInfo;
  20333. ma_bool32 found;
  20334. } ma_context_get_device_info_callback_data__dsound;
  20335. static BOOL CALLBACK ma_context_get_device_info_callback__dsound(GUID* lpGuid, const char* lpcstrDescription, const char* lpcstrModule, void* lpContext)
  20336. {
  20337. ma_context_get_device_info_callback_data__dsound* pData = (ma_context_get_device_info_callback_data__dsound*)lpContext;
  20338. MA_ASSERT(pData != NULL);
  20339. if ((pData->pDeviceID == NULL || ma_is_guid_null(pData->pDeviceID->dsound)) && (lpGuid == NULL || ma_is_guid_null(lpGuid))) {
  20340. /* Default device. */
  20341. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
  20342. pData->pDeviceInfo->isDefault = MA_TRUE;
  20343. pData->found = MA_TRUE;
  20344. return FALSE; /* Stop enumeration. */
  20345. } else {
  20346. /* Not the default device. */
  20347. if (lpGuid != NULL && pData->pDeviceID != NULL) {
  20348. if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) {
  20349. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
  20350. pData->found = MA_TRUE;
  20351. return FALSE; /* Stop enumeration. */
  20352. }
  20353. }
  20354. }
  20355. (void)lpcstrModule;
  20356. return TRUE;
  20357. }
  20358. 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)
  20359. {
  20360. ma_result result;
  20361. HRESULT hr;
  20362. if (pDeviceID != NULL) {
  20363. ma_context_get_device_info_callback_data__dsound data;
  20364. /* ID. */
  20365. MA_COPY_MEMORY(pDeviceInfo->id.dsound, pDeviceID->dsound, 16);
  20366. /* Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. */
  20367. data.pDeviceID = pDeviceID;
  20368. data.pDeviceInfo = pDeviceInfo;
  20369. data.found = MA_FALSE;
  20370. if (deviceType == ma_device_type_playback) {
  20371. ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
  20372. } else {
  20373. ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
  20374. }
  20375. if (!data.found) {
  20376. return MA_NO_DEVICE;
  20377. }
  20378. } else {
  20379. /* 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. */
  20380. /* ID */
  20381. MA_ZERO_MEMORY(pDeviceInfo->id.dsound, 16);
  20382. /* Name / Description */
  20383. if (deviceType == ma_device_type_playback) {
  20384. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  20385. } else {
  20386. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  20387. }
  20388. pDeviceInfo->isDefault = MA_TRUE;
  20389. }
  20390. /* Retrieving detailed information is slightly different depending on the device type. */
  20391. if (deviceType == ma_device_type_playback) {
  20392. /* Playback. */
  20393. ma_IDirectSound* pDirectSound;
  20394. MA_DSCAPS caps;
  20395. WORD channels;
  20396. result = ma_context_create_IDirectSound__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSound);
  20397. if (result != MA_SUCCESS) {
  20398. return result;
  20399. }
  20400. MA_ZERO_OBJECT(&caps);
  20401. caps.dwSize = sizeof(caps);
  20402. hr = ma_IDirectSound_GetCaps(pDirectSound, &caps);
  20403. if (FAILED(hr)) {
  20404. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.");
  20405. return ma_result_from_HRESULT(hr);
  20406. }
  20407. /* Channels. Only a single channel count is reported for DirectSound. */
  20408. if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
  20409. /* It supports at least stereo, but could support more. */
  20410. DWORD speakerConfig;
  20411. channels = 2;
  20412. /* Look at the speaker configuration to get a better idea on the channel count. */
  20413. hr = ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig);
  20414. if (SUCCEEDED(hr)) {
  20415. ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL);
  20416. }
  20417. } else {
  20418. /* It does not support stereo, which means we are stuck with mono. */
  20419. channels = 1;
  20420. }
  20421. /*
  20422. In DirectSound, our native formats are centered around sample rates. All formats are supported, and we're only reporting a single channel
  20423. count. However, DirectSound can report a range of supported sample rates. We're only going to include standard rates known by miniaudio
  20424. in order to keep the size of this within reason.
  20425. */
  20426. if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
  20427. /* Multiple sample rates are supported. We'll report in order of our preferred sample rates. */
  20428. size_t iStandardSampleRate;
  20429. for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
  20430. ma_uint32 sampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
  20431. if (sampleRate >= caps.dwMinSecondarySampleRate && sampleRate <= caps.dwMaxSecondarySampleRate) {
  20432. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
  20433. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  20434. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  20435. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  20436. pDeviceInfo->nativeDataFormatCount += 1;
  20437. }
  20438. }
  20439. } else {
  20440. /* Only a single sample rate is supported. */
  20441. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
  20442. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  20443. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = caps.dwMaxSecondarySampleRate;
  20444. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  20445. pDeviceInfo->nativeDataFormatCount += 1;
  20446. }
  20447. ma_IDirectSound_Release(pDirectSound);
  20448. } else {
  20449. /*
  20450. Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture
  20451. devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just
  20452. reporting the best format.
  20453. */
  20454. ma_IDirectSoundCapture* pDirectSoundCapture;
  20455. WORD channels;
  20456. WORD bitsPerSample;
  20457. DWORD sampleRate;
  20458. result = ma_context_create_IDirectSoundCapture__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSoundCapture);
  20459. if (result != MA_SUCCESS) {
  20460. return result;
  20461. }
  20462. result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate);
  20463. if (result != MA_SUCCESS) {
  20464. ma_IDirectSoundCapture_Release(pDirectSoundCapture);
  20465. return result;
  20466. }
  20467. ma_IDirectSoundCapture_Release(pDirectSoundCapture);
  20468. /* The format is always an integer format and is based on the bits per sample. */
  20469. if (bitsPerSample == 8) {
  20470. pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
  20471. } else if (bitsPerSample == 16) {
  20472. pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
  20473. } else if (bitsPerSample == 24) {
  20474. pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
  20475. } else if (bitsPerSample == 32) {
  20476. pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
  20477. } else {
  20478. return MA_FORMAT_NOT_SUPPORTED;
  20479. }
  20480. pDeviceInfo->nativeDataFormats[0].channels = channels;
  20481. pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
  20482. pDeviceInfo->nativeDataFormats[0].flags = 0;
  20483. pDeviceInfo->nativeDataFormatCount = 1;
  20484. }
  20485. return MA_SUCCESS;
  20486. }
  20487. static ma_result ma_device_uninit__dsound(ma_device* pDevice)
  20488. {
  20489. MA_ASSERT(pDevice != NULL);
  20490. if (pDevice->dsound.pCaptureBuffer != NULL) {
  20491. ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20492. }
  20493. if (pDevice->dsound.pCapture != NULL) {
  20494. ma_IDirectSoundCapture_Release((ma_IDirectSoundCapture*)pDevice->dsound.pCapture);
  20495. }
  20496. if (pDevice->dsound.pPlaybackBuffer != NULL) {
  20497. ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
  20498. }
  20499. if (pDevice->dsound.pPlaybackPrimaryBuffer != NULL) {
  20500. ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer);
  20501. }
  20502. if (pDevice->dsound.pPlayback != NULL) {
  20503. ma_IDirectSound_Release((ma_IDirectSound*)pDevice->dsound.pPlayback);
  20504. }
  20505. return MA_SUCCESS;
  20506. }
  20507. static ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, MA_WAVEFORMATEXTENSIBLE* pWF)
  20508. {
  20509. GUID subformat;
  20510. if (format == ma_format_unknown) {
  20511. format = MA_DEFAULT_FORMAT;
  20512. }
  20513. if (channels == 0) {
  20514. channels = MA_DEFAULT_CHANNELS;
  20515. }
  20516. if (sampleRate == 0) {
  20517. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  20518. }
  20519. switch (format)
  20520. {
  20521. case ma_format_u8:
  20522. case ma_format_s16:
  20523. case ma_format_s24:
  20524. /*case ma_format_s24_32:*/
  20525. case ma_format_s32:
  20526. {
  20527. subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  20528. } break;
  20529. case ma_format_f32:
  20530. {
  20531. subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  20532. } break;
  20533. default:
  20534. return MA_FORMAT_NOT_SUPPORTED;
  20535. }
  20536. MA_ZERO_OBJECT(pWF);
  20537. pWF->cbSize = sizeof(*pWF);
  20538. pWF->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  20539. pWF->nChannels = (WORD)channels;
  20540. pWF->nSamplesPerSec = (DWORD)sampleRate;
  20541. pWF->wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
  20542. pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8);
  20543. pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec;
  20544. pWF->Samples.wValidBitsPerSample = pWF->wBitsPerSample;
  20545. pWF->dwChannelMask = ma_channel_map_to_channel_mask__win32(pChannelMap, channels);
  20546. pWF->SubFormat = subformat;
  20547. return MA_SUCCESS;
  20548. }
  20549. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__dsound(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  20550. {
  20551. /*
  20552. DirectSound has a minimum period size of 20ms. In practice, this doesn't seem to be enough for
  20553. reliable glitch-free processing so going to use 30ms instead.
  20554. */
  20555. ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(30, nativeSampleRate);
  20556. ma_uint32 periodSizeInFrames;
  20557. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile);
  20558. if (periodSizeInFrames < minPeriodSizeInFrames) {
  20559. periodSizeInFrames = minPeriodSizeInFrames;
  20560. }
  20561. return periodSizeInFrames;
  20562. }
  20563. static ma_result ma_device_init__dsound(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  20564. {
  20565. ma_result result;
  20566. HRESULT hr;
  20567. MA_ASSERT(pDevice != NULL);
  20568. MA_ZERO_OBJECT(&pDevice->dsound);
  20569. if (pConfig->deviceType == ma_device_type_loopback) {
  20570. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  20571. }
  20572. /*
  20573. Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize
  20574. 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
  20575. full-duplex mode.
  20576. */
  20577. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  20578. MA_WAVEFORMATEXTENSIBLE wf;
  20579. MA_DSCBUFFERDESC descDS;
  20580. ma_uint32 periodSizeInFrames;
  20581. ma_uint32 periodCount;
  20582. char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
  20583. MA_WAVEFORMATEXTENSIBLE* pActualFormat;
  20584. result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &wf);
  20585. if (result != MA_SUCCESS) {
  20586. return result;
  20587. }
  20588. result = ma_context_create_IDirectSoundCapture__dsound(pDevice->pContext, pDescriptorCapture->shareMode, pDescriptorCapture->pDeviceID, (ma_IDirectSoundCapture**)&pDevice->dsound.pCapture);
  20589. if (result != MA_SUCCESS) {
  20590. ma_device_uninit__dsound(pDevice);
  20591. return result;
  20592. }
  20593. result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pDevice->pContext, (ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.nChannels, &wf.wBitsPerSample, &wf.nSamplesPerSec);
  20594. if (result != MA_SUCCESS) {
  20595. ma_device_uninit__dsound(pDevice);
  20596. return result;
  20597. }
  20598. wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8);
  20599. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  20600. wf.Samples.wValidBitsPerSample = wf.wBitsPerSample;
  20601. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  20602. /* The size of the buffer must be a clean multiple of the period count. */
  20603. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorCapture, wf.nSamplesPerSec, pConfig->performanceProfile);
  20604. periodCount = (pDescriptorCapture->periodCount > 0) ? pDescriptorCapture->periodCount : MA_DEFAULT_PERIODS;
  20605. MA_ZERO_OBJECT(&descDS);
  20606. descDS.dwSize = sizeof(descDS);
  20607. descDS.dwFlags = 0;
  20608. descDS.dwBufferBytes = periodSizeInFrames * periodCount * wf.nBlockAlign;
  20609. descDS.lpwfxFormat = (MA_WAVEFORMATEX*)&wf;
  20610. hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
  20611. if (FAILED(hr)) {
  20612. ma_device_uninit__dsound(pDevice);
  20613. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.");
  20614. return ma_result_from_HRESULT(hr);
  20615. }
  20616. /* Get the _actual_ properties of the buffer. */
  20617. pActualFormat = (MA_WAVEFORMATEXTENSIBLE*)rawdata;
  20618. hr = ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (MA_WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
  20619. if (FAILED(hr)) {
  20620. ma_device_uninit__dsound(pDevice);
  20621. 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.");
  20622. return ma_result_from_HRESULT(hr);
  20623. }
  20624. /* We can now start setting the output data formats. */
  20625. pDescriptorCapture->format = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)pActualFormat);
  20626. pDescriptorCapture->channels = pActualFormat->nChannels;
  20627. pDescriptorCapture->sampleRate = pActualFormat->nSamplesPerSec;
  20628. /* Get the native channel map based on the channel mask. */
  20629. if (pActualFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  20630. ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
  20631. } else {
  20632. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
  20633. }
  20634. /*
  20635. 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
  20636. 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.
  20637. */
  20638. if (periodSizeInFrames != (descDS.dwBufferBytes / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / periodCount)) {
  20639. descDS.dwBufferBytes = periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * periodCount;
  20640. ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20641. hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
  20642. if (FAILED(hr)) {
  20643. ma_device_uninit__dsound(pDevice);
  20644. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Second attempt at IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.");
  20645. return ma_result_from_HRESULT(hr);
  20646. }
  20647. }
  20648. /* DirectSound should give us a buffer exactly the size we asked for. */
  20649. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  20650. pDescriptorCapture->periodCount = periodCount;
  20651. }
  20652. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  20653. MA_WAVEFORMATEXTENSIBLE wf;
  20654. MA_DSBUFFERDESC descDSPrimary;
  20655. MA_DSCAPS caps;
  20656. char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
  20657. MA_WAVEFORMATEXTENSIBLE* pActualFormat;
  20658. ma_uint32 periodSizeInFrames;
  20659. ma_uint32 periodCount;
  20660. MA_DSBUFFERDESC descDS;
  20661. WORD nativeChannelCount;
  20662. DWORD nativeChannelMask = 0;
  20663. result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &wf);
  20664. if (result != MA_SUCCESS) {
  20665. return result;
  20666. }
  20667. result = ma_context_create_IDirectSound__dsound(pDevice->pContext, pDescriptorPlayback->shareMode, pDescriptorPlayback->pDeviceID, (ma_IDirectSound**)&pDevice->dsound.pPlayback);
  20668. if (result != MA_SUCCESS) {
  20669. ma_device_uninit__dsound(pDevice);
  20670. return result;
  20671. }
  20672. MA_ZERO_OBJECT(&descDSPrimary);
  20673. descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC);
  20674. descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME;
  20675. hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL);
  20676. if (FAILED(hr)) {
  20677. ma_device_uninit__dsound(pDevice);
  20678. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer.");
  20679. return ma_result_from_HRESULT(hr);
  20680. }
  20681. /* We may want to make some adjustments to the format if we are using defaults. */
  20682. MA_ZERO_OBJECT(&caps);
  20683. caps.dwSize = sizeof(caps);
  20684. hr = ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps);
  20685. if (FAILED(hr)) {
  20686. ma_device_uninit__dsound(pDevice);
  20687. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.");
  20688. return ma_result_from_HRESULT(hr);
  20689. }
  20690. if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
  20691. DWORD speakerConfig;
  20692. /* It supports at least stereo, but could support more. */
  20693. nativeChannelCount = 2;
  20694. /* Look at the speaker configuration to get a better idea on the channel count. */
  20695. if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig((ma_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) {
  20696. ma_get_channels_from_speaker_config__dsound(speakerConfig, &nativeChannelCount, &nativeChannelMask);
  20697. }
  20698. } else {
  20699. /* It does not support stereo, which means we are stuck with mono. */
  20700. nativeChannelCount = 1;
  20701. nativeChannelMask = 0x00000001;
  20702. }
  20703. if (pDescriptorPlayback->channels == 0) {
  20704. wf.nChannels = nativeChannelCount;
  20705. wf.dwChannelMask = nativeChannelMask;
  20706. }
  20707. if (pDescriptorPlayback->sampleRate == 0) {
  20708. /* We base the sample rate on the values returned by GetCaps(). */
  20709. if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
  20710. wf.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate);
  20711. } else {
  20712. wf.nSamplesPerSec = caps.dwMaxSecondarySampleRate;
  20713. }
  20714. }
  20715. wf.nBlockAlign = (WORD)(wf.nChannels * wf.wBitsPerSample / 8);
  20716. wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
  20717. /*
  20718. From MSDN:
  20719. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest
  20720. supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer
  20721. and compare the result with the format that was requested with the SetFormat method.
  20722. */
  20723. hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)&wf);
  20724. if (FAILED(hr)) {
  20725. /*
  20726. If setting of the format failed we'll try again with some fallback settings. On Windows 98 I have
  20727. observed that IEEE_FLOAT does not work. We'll therefore enforce PCM. I also had issues where a
  20728. sample rate of 48000 did not work correctly. Not sure if it was a driver issue or not, but will
  20729. use 44100 for the sample rate.
  20730. */
  20731. wf.cbSize = 18; /* NOTE: Don't use sizeof(MA_WAVEFORMATEX) here because it's got an extra 2 bytes due to padding. */
  20732. wf.wFormatTag = WAVE_FORMAT_PCM;
  20733. wf.wBitsPerSample = 16;
  20734. wf.nChannels = nativeChannelCount;
  20735. wf.nSamplesPerSec = 44100;
  20736. wf.nBlockAlign = wf.nChannels * (wf.wBitsPerSample / 8);
  20737. wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
  20738. hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)&wf);
  20739. if (FAILED(hr)) {
  20740. ma_device_uninit__dsound(pDevice);
  20741. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.");
  20742. return ma_result_from_HRESULT(hr);
  20743. }
  20744. }
  20745. /* Get the _actual_ properties of the buffer. */
  20746. pActualFormat = (MA_WAVEFORMATEXTENSIBLE*)rawdata;
  20747. hr = ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (MA_WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
  20748. if (FAILED(hr)) {
  20749. ma_device_uninit__dsound(pDevice);
  20750. 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.");
  20751. return ma_result_from_HRESULT(hr);
  20752. }
  20753. /* We now have enough information to start setting some output properties. */
  20754. pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX((MA_WAVEFORMATEX*)pActualFormat);
  20755. pDescriptorPlayback->channels = pActualFormat->nChannels;
  20756. pDescriptorPlayback->sampleRate = pActualFormat->nSamplesPerSec;
  20757. /* Get the internal channel map based on the channel mask. */
  20758. if (pActualFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  20759. ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
  20760. } else {
  20761. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
  20762. }
  20763. /* The size of the buffer must be a clean multiple of the period count. */
  20764. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  20765. periodCount = (pDescriptorPlayback->periodCount > 0) ? pDescriptorPlayback->periodCount : MA_DEFAULT_PERIODS;
  20766. /*
  20767. Meaning of dwFlags (from MSDN):
  20768. DSBCAPS_CTRLPOSITIONNOTIFY
  20769. The buffer has position notification capability.
  20770. DSBCAPS_GLOBALFOCUS
  20771. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to
  20772. another application, even if the new application uses DirectSound.
  20773. DSBCAPS_GETCURRENTPOSITION2
  20774. In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated
  20775. sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the
  20776. application can get a more accurate play cursor.
  20777. */
  20778. MA_ZERO_OBJECT(&descDS);
  20779. descDS.dwSize = sizeof(descDS);
  20780. descDS.dwFlags = MA_DSBCAPS_CTRLPOSITIONNOTIFY | MA_DSBCAPS_GLOBALFOCUS | MA_DSBCAPS_GETCURRENTPOSITION2;
  20781. descDS.dwBufferBytes = periodSizeInFrames * periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels);
  20782. descDS.lpwfxFormat = (MA_WAVEFORMATEX*)pActualFormat;
  20783. hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL);
  20784. if (FAILED(hr)) {
  20785. ma_device_uninit__dsound(pDevice);
  20786. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer.");
  20787. return ma_result_from_HRESULT(hr);
  20788. }
  20789. /* DirectSound should give us a buffer exactly the size we asked for. */
  20790. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  20791. pDescriptorPlayback->periodCount = periodCount;
  20792. }
  20793. return MA_SUCCESS;
  20794. }
  20795. static ma_result ma_device_data_loop__dsound(ma_device* pDevice)
  20796. {
  20797. ma_result result = MA_SUCCESS;
  20798. ma_uint32 bpfDeviceCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  20799. ma_uint32 bpfDevicePlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  20800. HRESULT hr;
  20801. DWORD lockOffsetInBytesCapture;
  20802. DWORD lockSizeInBytesCapture;
  20803. DWORD mappedSizeInBytesCapture;
  20804. DWORD mappedDeviceFramesProcessedCapture;
  20805. void* pMappedDeviceBufferCapture;
  20806. DWORD lockOffsetInBytesPlayback;
  20807. DWORD lockSizeInBytesPlayback;
  20808. DWORD mappedSizeInBytesPlayback;
  20809. void* pMappedDeviceBufferPlayback;
  20810. DWORD prevReadCursorInBytesCapture = 0;
  20811. DWORD prevPlayCursorInBytesPlayback = 0;
  20812. ma_bool32 physicalPlayCursorLoopFlagPlayback = 0;
  20813. DWORD virtualWriteCursorInBytesPlayback = 0;
  20814. ma_bool32 virtualWriteCursorLoopFlagPlayback = 0;
  20815. ma_bool32 isPlaybackDeviceStarted = MA_FALSE;
  20816. ma_uint32 framesWrittenToPlaybackDevice = 0; /* For knowing whether or not the playback device needs to be started. */
  20817. ma_uint32 waitTimeInMilliseconds = 1;
  20818. MA_ASSERT(pDevice != NULL);
  20819. /* The first thing to do is start the capture device. The playback device is only started after the first period is written. */
  20820. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  20821. hr = ma_IDirectSoundCaptureBuffer_Start((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MA_DSCBSTART_LOOPING);
  20822. if (FAILED(hr)) {
  20823. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed.");
  20824. return ma_result_from_HRESULT(hr);
  20825. }
  20826. }
  20827. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  20828. switch (pDevice->type)
  20829. {
  20830. case ma_device_type_duplex:
  20831. {
  20832. DWORD physicalCaptureCursorInBytes;
  20833. DWORD physicalReadCursorInBytes;
  20834. hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
  20835. if (FAILED(hr)) {
  20836. return ma_result_from_HRESULT(hr);
  20837. }
  20838. /* If nothing is available we just sleep for a bit and return from this iteration. */
  20839. if (physicalReadCursorInBytes == prevReadCursorInBytesCapture) {
  20840. ma_sleep(waitTimeInMilliseconds);
  20841. continue; /* Nothing is available in the capture buffer. */
  20842. }
  20843. /*
  20844. The current position has moved. We need to map all of the captured samples and write them to the playback device, making sure
  20845. we don't return until every frame has been copied over.
  20846. */
  20847. if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
  20848. /* The capture position has not looped. This is the simple case. */
  20849. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20850. lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
  20851. } else {
  20852. /*
  20853. The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
  20854. do it again from the start.
  20855. */
  20856. if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
  20857. /* Lock up to the end of the buffer. */
  20858. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20859. lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
  20860. } else {
  20861. /* Lock starting from the start of the buffer. */
  20862. lockOffsetInBytesCapture = 0;
  20863. lockSizeInBytesCapture = physicalReadCursorInBytes;
  20864. }
  20865. }
  20866. if (lockSizeInBytesCapture == 0) {
  20867. ma_sleep(waitTimeInMilliseconds);
  20868. continue; /* Nothing is available in the capture buffer. */
  20869. }
  20870. hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
  20871. if (FAILED(hr)) {
  20872. 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.");
  20873. return ma_result_from_HRESULT(hr);
  20874. }
  20875. /* 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. */
  20876. mappedDeviceFramesProcessedCapture = 0;
  20877. for (;;) { /* Keep writing to the playback device. */
  20878. ma_uint8 inputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  20879. ma_uint32 inputFramesInClientFormatCap = sizeof(inputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  20880. ma_uint8 outputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  20881. ma_uint32 outputFramesInClientFormatCap = sizeof(outputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  20882. ma_uint32 outputFramesInClientFormatCount;
  20883. ma_uint32 outputFramesInClientFormatConsumed = 0;
  20884. ma_uint64 clientCapturedFramesToProcess = ma_min(inputFramesInClientFormatCap, outputFramesInClientFormatCap);
  20885. ma_uint64 deviceCapturedFramesToProcess = (mappedSizeInBytesCapture / bpfDeviceCapture) - mappedDeviceFramesProcessedCapture;
  20886. void* pRunningMappedDeviceBufferCapture = ma_offset_ptr(pMappedDeviceBufferCapture, mappedDeviceFramesProcessedCapture * bpfDeviceCapture);
  20887. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningMappedDeviceBufferCapture, &deviceCapturedFramesToProcess, inputFramesInClientFormat, &clientCapturedFramesToProcess);
  20888. if (result != MA_SUCCESS) {
  20889. break;
  20890. }
  20891. outputFramesInClientFormatCount = (ma_uint32)clientCapturedFramesToProcess;
  20892. mappedDeviceFramesProcessedCapture += (ma_uint32)deviceCapturedFramesToProcess;
  20893. ma_device__handle_data_callback(pDevice, outputFramesInClientFormat, inputFramesInClientFormat, (ma_uint32)clientCapturedFramesToProcess);
  20894. /* 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. */
  20895. for (;;) {
  20896. ma_uint32 framesWrittenThisIteration;
  20897. DWORD physicalPlayCursorInBytes;
  20898. DWORD physicalWriteCursorInBytes;
  20899. DWORD availableBytesPlayback;
  20900. DWORD silentPaddingInBytes = 0; /* <-- Must be initialized to 0. */
  20901. /* We need the physical play and write cursors. */
  20902. if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) {
  20903. break;
  20904. }
  20905. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  20906. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  20907. }
  20908. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  20909. /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
  20910. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20911. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  20912. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  20913. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20914. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  20915. } else {
  20916. /* This is an error. */
  20917. 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);
  20918. availableBytesPlayback = 0;
  20919. }
  20920. } else {
  20921. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  20922. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  20923. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20924. } else {
  20925. /* This is an error. */
  20926. 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);
  20927. availableBytesPlayback = 0;
  20928. }
  20929. }
  20930. /* If there's no room available for writing we need to wait for more. */
  20931. if (availableBytesPlayback == 0) {
  20932. /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
  20933. if (!isPlaybackDeviceStarted) {
  20934. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20935. if (FAILED(hr)) {
  20936. ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20937. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  20938. return ma_result_from_HRESULT(hr);
  20939. }
  20940. isPlaybackDeviceStarted = MA_TRUE;
  20941. } else {
  20942. ma_sleep(waitTimeInMilliseconds);
  20943. continue;
  20944. }
  20945. }
  20946. /* 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. */
  20947. lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
  20948. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20949. /* Same loop iteration. Go up to the end of the buffer. */
  20950. lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20951. } else {
  20952. /* Different loop iterations. Go up to the physical play cursor. */
  20953. lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20954. }
  20955. hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
  20956. if (FAILED(hr)) {
  20957. 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.");
  20958. result = ma_result_from_HRESULT(hr);
  20959. break;
  20960. }
  20961. /*
  20962. 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
  20963. endless glitching due to it constantly running out of data.
  20964. */
  20965. if (isPlaybackDeviceStarted) {
  20966. DWORD bytesQueuedForPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - availableBytesPlayback;
  20967. if (bytesQueuedForPlayback < (pDevice->playback.internalPeriodSizeInFrames*bpfDevicePlayback)) {
  20968. silentPaddingInBytes = (pDevice->playback.internalPeriodSizeInFrames*2*bpfDevicePlayback) - bytesQueuedForPlayback;
  20969. if (silentPaddingInBytes > lockSizeInBytesPlayback) {
  20970. silentPaddingInBytes = lockSizeInBytesPlayback;
  20971. }
  20972. 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);
  20973. }
  20974. }
  20975. /* At this point we have a buffer for output. */
  20976. if (silentPaddingInBytes > 0) {
  20977. MA_ZERO_MEMORY(pMappedDeviceBufferPlayback, silentPaddingInBytes);
  20978. framesWrittenThisIteration = silentPaddingInBytes/bpfDevicePlayback;
  20979. } else {
  20980. ma_uint64 convertedFrameCountIn = (outputFramesInClientFormatCount - outputFramesInClientFormatConsumed);
  20981. ma_uint64 convertedFrameCountOut = mappedSizeInBytesPlayback/bpfDevicePlayback;
  20982. void* pConvertedFramesIn = ma_offset_ptr(outputFramesInClientFormat, outputFramesInClientFormatConsumed * bpfDevicePlayback);
  20983. void* pConvertedFramesOut = pMappedDeviceBufferPlayback;
  20984. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pConvertedFramesIn, &convertedFrameCountIn, pConvertedFramesOut, &convertedFrameCountOut);
  20985. if (result != MA_SUCCESS) {
  20986. break;
  20987. }
  20988. outputFramesInClientFormatConsumed += (ma_uint32)convertedFrameCountOut;
  20989. framesWrittenThisIteration = (ma_uint32)convertedFrameCountOut;
  20990. }
  20991. hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, framesWrittenThisIteration*bpfDevicePlayback, NULL, 0);
  20992. if (FAILED(hr)) {
  20993. 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.");
  20994. result = ma_result_from_HRESULT(hr);
  20995. break;
  20996. }
  20997. virtualWriteCursorInBytesPlayback += framesWrittenThisIteration*bpfDevicePlayback;
  20998. if ((virtualWriteCursorInBytesPlayback/bpfDevicePlayback) == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods) {
  20999. virtualWriteCursorInBytesPlayback = 0;
  21000. virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
  21001. }
  21002. /*
  21003. 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
  21004. a bit of a buffer to prevent the playback buffer from getting starved.
  21005. */
  21006. framesWrittenToPlaybackDevice += framesWrittenThisIteration;
  21007. if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= (pDevice->playback.internalPeriodSizeInFrames*2)) {
  21008. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  21009. if (FAILED(hr)) {
  21010. ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  21011. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  21012. return ma_result_from_HRESULT(hr);
  21013. }
  21014. isPlaybackDeviceStarted = MA_TRUE;
  21015. }
  21016. if (framesWrittenThisIteration < mappedSizeInBytesPlayback/bpfDevicePlayback) {
  21017. break; /* We're finished with the output data.*/
  21018. }
  21019. }
  21020. if (clientCapturedFramesToProcess == 0) {
  21021. break; /* We just consumed every input sample. */
  21022. }
  21023. }
  21024. /* At this point we're done with the mapped portion of the capture buffer. */
  21025. hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
  21026. if (FAILED(hr)) {
  21027. 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.");
  21028. return ma_result_from_HRESULT(hr);
  21029. }
  21030. prevReadCursorInBytesCapture = (lockOffsetInBytesCapture + mappedSizeInBytesCapture);
  21031. } break;
  21032. case ma_device_type_capture:
  21033. {
  21034. DWORD physicalCaptureCursorInBytes;
  21035. DWORD physicalReadCursorInBytes;
  21036. hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
  21037. if (FAILED(hr)) {
  21038. return MA_ERROR;
  21039. }
  21040. /* If the previous capture position is the same as the current position we need to wait a bit longer. */
  21041. if (prevReadCursorInBytesCapture == physicalReadCursorInBytes) {
  21042. ma_sleep(waitTimeInMilliseconds);
  21043. continue;
  21044. }
  21045. /* Getting here means we have capture data available. */
  21046. if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
  21047. /* The capture position has not looped. This is the simple case. */
  21048. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  21049. lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
  21050. } else {
  21051. /*
  21052. The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
  21053. do it again from the start.
  21054. */
  21055. if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
  21056. /* Lock up to the end of the buffer. */
  21057. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  21058. lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
  21059. } else {
  21060. /* Lock starting from the start of the buffer. */
  21061. lockOffsetInBytesCapture = 0;
  21062. lockSizeInBytesCapture = physicalReadCursorInBytes;
  21063. }
  21064. }
  21065. if (lockSizeInBytesCapture < pDevice->capture.internalPeriodSizeInFrames) {
  21066. ma_sleep(waitTimeInMilliseconds);
  21067. continue; /* Nothing is available in the capture buffer. */
  21068. }
  21069. hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
  21070. if (FAILED(hr)) {
  21071. 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.");
  21072. result = ma_result_from_HRESULT(hr);
  21073. }
  21074. if (lockSizeInBytesCapture != mappedSizeInBytesCapture) {
  21075. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[DirectSound] (Capture) lockSizeInBytesCapture=%ld != mappedSizeInBytesCapture=%ld\n", lockSizeInBytesCapture, mappedSizeInBytesCapture);
  21076. }
  21077. ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfDeviceCapture, pMappedDeviceBufferCapture);
  21078. hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
  21079. if (FAILED(hr)) {
  21080. 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.");
  21081. return ma_result_from_HRESULT(hr);
  21082. }
  21083. prevReadCursorInBytesCapture = lockOffsetInBytesCapture + mappedSizeInBytesCapture;
  21084. if (prevReadCursorInBytesCapture == (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture)) {
  21085. prevReadCursorInBytesCapture = 0;
  21086. }
  21087. } break;
  21088. case ma_device_type_playback:
  21089. {
  21090. DWORD availableBytesPlayback;
  21091. DWORD physicalPlayCursorInBytes;
  21092. DWORD physicalWriteCursorInBytes;
  21093. hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
  21094. if (FAILED(hr)) {
  21095. break;
  21096. }
  21097. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  21098. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  21099. }
  21100. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  21101. /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
  21102. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  21103. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  21104. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  21105. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  21106. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  21107. } else {
  21108. /* This is an error. */
  21109. 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);
  21110. availableBytesPlayback = 0;
  21111. }
  21112. } else {
  21113. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  21114. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  21115. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  21116. } else {
  21117. /* This is an error. */
  21118. 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);
  21119. availableBytesPlayback = 0;
  21120. }
  21121. }
  21122. /* If there's no room available for writing we need to wait for more. */
  21123. if (availableBytesPlayback < pDevice->playback.internalPeriodSizeInFrames) {
  21124. /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
  21125. if (availableBytesPlayback == 0 && !isPlaybackDeviceStarted) {
  21126. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  21127. if (FAILED(hr)) {
  21128. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  21129. return ma_result_from_HRESULT(hr);
  21130. }
  21131. isPlaybackDeviceStarted = MA_TRUE;
  21132. } else {
  21133. ma_sleep(waitTimeInMilliseconds);
  21134. continue;
  21135. }
  21136. }
  21137. /* 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. */
  21138. lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
  21139. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  21140. /* Same loop iteration. Go up to the end of the buffer. */
  21141. lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  21142. } else {
  21143. /* Different loop iterations. Go up to the physical play cursor. */
  21144. lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  21145. }
  21146. hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
  21147. if (FAILED(hr)) {
  21148. 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.");
  21149. result = ma_result_from_HRESULT(hr);
  21150. break;
  21151. }
  21152. /* At this point we have a buffer for output. */
  21153. ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfDevicePlayback), pMappedDeviceBufferPlayback);
  21154. hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, mappedSizeInBytesPlayback, NULL, 0);
  21155. if (FAILED(hr)) {
  21156. 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.");
  21157. result = ma_result_from_HRESULT(hr);
  21158. break;
  21159. }
  21160. virtualWriteCursorInBytesPlayback += mappedSizeInBytesPlayback;
  21161. if (virtualWriteCursorInBytesPlayback == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) {
  21162. virtualWriteCursorInBytesPlayback = 0;
  21163. virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
  21164. }
  21165. /*
  21166. 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
  21167. a bit of a buffer to prevent the playback buffer from getting starved.
  21168. */
  21169. framesWrittenToPlaybackDevice += mappedSizeInBytesPlayback/bpfDevicePlayback;
  21170. if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= pDevice->playback.internalPeriodSizeInFrames) {
  21171. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  21172. if (FAILED(hr)) {
  21173. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  21174. return ma_result_from_HRESULT(hr);
  21175. }
  21176. isPlaybackDeviceStarted = MA_TRUE;
  21177. }
  21178. } break;
  21179. default: return MA_INVALID_ARGS; /* Invalid device type. */
  21180. }
  21181. if (result != MA_SUCCESS) {
  21182. return result;
  21183. }
  21184. }
  21185. /* Getting here means the device is being stopped. */
  21186. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21187. hr = ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  21188. if (FAILED(hr)) {
  21189. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed.");
  21190. return ma_result_from_HRESULT(hr);
  21191. }
  21192. }
  21193. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21194. /* 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. */
  21195. if (isPlaybackDeviceStarted) {
  21196. for (;;) {
  21197. DWORD availableBytesPlayback = 0;
  21198. DWORD physicalPlayCursorInBytes;
  21199. DWORD physicalWriteCursorInBytes;
  21200. hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
  21201. if (FAILED(hr)) {
  21202. break;
  21203. }
  21204. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  21205. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  21206. }
  21207. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  21208. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  21209. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  21210. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  21211. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  21212. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  21213. } else {
  21214. break;
  21215. }
  21216. } else {
  21217. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  21218. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  21219. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  21220. } else {
  21221. break;
  21222. }
  21223. }
  21224. if (availableBytesPlayback >= (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback)) {
  21225. break;
  21226. }
  21227. ma_sleep(waitTimeInMilliseconds);
  21228. }
  21229. }
  21230. hr = ma_IDirectSoundBuffer_Stop((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
  21231. if (FAILED(hr)) {
  21232. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed.");
  21233. return ma_result_from_HRESULT(hr);
  21234. }
  21235. ma_IDirectSoundBuffer_SetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0);
  21236. }
  21237. return MA_SUCCESS;
  21238. }
  21239. static ma_result ma_context_uninit__dsound(ma_context* pContext)
  21240. {
  21241. MA_ASSERT(pContext != NULL);
  21242. MA_ASSERT(pContext->backend == ma_backend_dsound);
  21243. ma_dlclose(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL);
  21244. return MA_SUCCESS;
  21245. }
  21246. static ma_result ma_context_init__dsound(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  21247. {
  21248. MA_ASSERT(pContext != NULL);
  21249. (void)pConfig;
  21250. pContext->dsound.hDSoundDLL = ma_dlopen(ma_context_get_log(pContext), "dsound.dll");
  21251. if (pContext->dsound.hDSoundDLL == NULL) {
  21252. return MA_API_NOT_FOUND;
  21253. }
  21254. pContext->dsound.DirectSoundCreate = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundCreate");
  21255. pContext->dsound.DirectSoundEnumerateA = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA");
  21256. pContext->dsound.DirectSoundCaptureCreate = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate");
  21257. pContext->dsound.DirectSoundCaptureEnumerateA = ma_dlsym(ma_context_get_log(pContext), pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA");
  21258. /*
  21259. We need to support all functions or nothing. DirectSound with Windows 95 seems to not work too
  21260. well in my testing. For example, it's missing DirectSoundCaptureEnumerateA(). This is a convenient
  21261. place to just disable the DirectSound backend for Windows 95.
  21262. */
  21263. if (pContext->dsound.DirectSoundCreate == NULL ||
  21264. pContext->dsound.DirectSoundEnumerateA == NULL ||
  21265. pContext->dsound.DirectSoundCaptureCreate == NULL ||
  21266. pContext->dsound.DirectSoundCaptureEnumerateA == NULL) {
  21267. return MA_API_NOT_FOUND;
  21268. }
  21269. pCallbacks->onContextInit = ma_context_init__dsound;
  21270. pCallbacks->onContextUninit = ma_context_uninit__dsound;
  21271. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__dsound;
  21272. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__dsound;
  21273. pCallbacks->onDeviceInit = ma_device_init__dsound;
  21274. pCallbacks->onDeviceUninit = ma_device_uninit__dsound;
  21275. pCallbacks->onDeviceStart = NULL; /* Not used. Started in onDeviceDataLoop. */
  21276. pCallbacks->onDeviceStop = NULL; /* Not used. Stopped in onDeviceDataLoop. */
  21277. pCallbacks->onDeviceRead = NULL; /* Not used. Data is read directly in onDeviceDataLoop. */
  21278. pCallbacks->onDeviceWrite = NULL; /* Not used. Data is written directly in onDeviceDataLoop. */
  21279. pCallbacks->onDeviceDataLoop = ma_device_data_loop__dsound;
  21280. return MA_SUCCESS;
  21281. }
  21282. #endif
  21283. /******************************************************************************
  21284. WinMM Backend
  21285. ******************************************************************************/
  21286. #ifdef MA_HAS_WINMM
  21287. /*
  21288. Some build configurations will exclude the WinMM API. An example is when WIN32_LEAN_AND_MEAN
  21289. is defined. We need to define the types and functions we need manually.
  21290. */
  21291. #define MA_MMSYSERR_NOERROR 0
  21292. #define MA_MMSYSERR_ERROR 1
  21293. #define MA_MMSYSERR_BADDEVICEID 2
  21294. #define MA_MMSYSERR_INVALHANDLE 5
  21295. #define MA_MMSYSERR_NOMEM 7
  21296. #define MA_MMSYSERR_INVALFLAG 10
  21297. #define MA_MMSYSERR_INVALPARAM 11
  21298. #define MA_MMSYSERR_HANDLEBUSY 12
  21299. #define MA_CALLBACK_EVENT 0x00050000
  21300. #define MA_WAVE_ALLOWSYNC 0x0002
  21301. #define MA_WHDR_DONE 0x00000001
  21302. #define MA_WHDR_PREPARED 0x00000002
  21303. #define MA_WHDR_BEGINLOOP 0x00000004
  21304. #define MA_WHDR_ENDLOOP 0x00000008
  21305. #define MA_WHDR_INQUEUE 0x00000010
  21306. #define MA_MAXPNAMELEN 32
  21307. typedef void* MA_HWAVEIN;
  21308. typedef void* MA_HWAVEOUT;
  21309. typedef UINT MA_MMRESULT;
  21310. typedef UINT MA_MMVERSION;
  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. } MA_WAVEINCAPSA;
  21321. typedef struct
  21322. {
  21323. WORD wMid;
  21324. WORD wPid;
  21325. MA_MMVERSION vDriverVersion;
  21326. CHAR szPname[MA_MAXPNAMELEN];
  21327. DWORD dwFormats;
  21328. WORD wChannels;
  21329. WORD wReserved1;
  21330. DWORD dwSupport;
  21331. } MA_WAVEOUTCAPSA;
  21332. typedef struct tagWAVEHDR
  21333. {
  21334. char* lpData;
  21335. DWORD dwBufferLength;
  21336. DWORD dwBytesRecorded;
  21337. DWORD_PTR dwUser;
  21338. DWORD dwFlags;
  21339. DWORD dwLoops;
  21340. struct tagWAVEHDR* lpNext;
  21341. DWORD_PTR reserved;
  21342. } MA_WAVEHDR;
  21343. typedef struct
  21344. {
  21345. WORD wMid;
  21346. WORD wPid;
  21347. MA_MMVERSION vDriverVersion;
  21348. CHAR szPname[MA_MAXPNAMELEN];
  21349. DWORD dwFormats;
  21350. WORD wChannels;
  21351. WORD wReserved1;
  21352. DWORD dwSupport;
  21353. GUID ManufacturerGuid;
  21354. GUID ProductGuid;
  21355. GUID NameGuid;
  21356. } MA_WAVEOUTCAPS2A;
  21357. typedef struct
  21358. {
  21359. WORD wMid;
  21360. WORD wPid;
  21361. MA_MMVERSION vDriverVersion;
  21362. CHAR szPname[MA_MAXPNAMELEN];
  21363. DWORD dwFormats;
  21364. WORD wChannels;
  21365. WORD wReserved1;
  21366. GUID ManufacturerGuid;
  21367. GUID ProductGuid;
  21368. GUID NameGuid;
  21369. } MA_WAVEINCAPS2A;
  21370. typedef UINT (WINAPI * MA_PFN_waveOutGetNumDevs)(void);
  21371. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutGetDevCapsA)(ma_uintptr uDeviceID, MA_WAVEOUTCAPSA* pwoc, UINT cbwoc);
  21372. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutOpen)(MA_HWAVEOUT* phwo, UINT uDeviceID, const MA_WAVEFORMATEX* pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
  21373. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutClose)(MA_HWAVEOUT hwo);
  21374. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutPrepareHeader)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh);
  21375. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutUnprepareHeader)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh);
  21376. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutWrite)(MA_HWAVEOUT hwo, MA_WAVEHDR* pwh, UINT cbwh);
  21377. typedef MA_MMRESULT (WINAPI * MA_PFN_waveOutReset)(MA_HWAVEOUT hwo);
  21378. typedef UINT (WINAPI * MA_PFN_waveInGetNumDevs)(void);
  21379. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInGetDevCapsA)(ma_uintptr uDeviceID, MA_WAVEINCAPSA* pwic, UINT cbwic);
  21380. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInOpen)(MA_HWAVEIN* phwi, UINT uDeviceID, const MA_WAVEFORMATEX* pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
  21381. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInClose)(MA_HWAVEIN hwi);
  21382. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInPrepareHeader)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh);
  21383. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInUnprepareHeader)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh);
  21384. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInAddBuffer)(MA_HWAVEIN hwi, MA_WAVEHDR* pwh, UINT cbwh);
  21385. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInStart)(MA_HWAVEIN hwi);
  21386. typedef MA_MMRESULT (WINAPI * MA_PFN_waveInReset)(MA_HWAVEIN hwi);
  21387. static ma_result ma_result_from_MMRESULT(MA_MMRESULT resultMM)
  21388. {
  21389. switch (resultMM)
  21390. {
  21391. case MA_MMSYSERR_NOERROR: return MA_SUCCESS;
  21392. case MA_MMSYSERR_BADDEVICEID: return MA_INVALID_ARGS;
  21393. case MA_MMSYSERR_INVALHANDLE: return MA_INVALID_ARGS;
  21394. case MA_MMSYSERR_NOMEM: return MA_OUT_OF_MEMORY;
  21395. case MA_MMSYSERR_INVALFLAG: return MA_INVALID_ARGS;
  21396. case MA_MMSYSERR_INVALPARAM: return MA_INVALID_ARGS;
  21397. case MA_MMSYSERR_HANDLEBUSY: return MA_BUSY;
  21398. case MA_MMSYSERR_ERROR: return MA_ERROR;
  21399. default: return MA_ERROR;
  21400. }
  21401. }
  21402. static char* ma_find_last_character(char* str, char ch)
  21403. {
  21404. char* last;
  21405. if (str == NULL) {
  21406. return NULL;
  21407. }
  21408. last = NULL;
  21409. while (*str != '\0') {
  21410. if (*str == ch) {
  21411. last = str;
  21412. }
  21413. str += 1;
  21414. }
  21415. return last;
  21416. }
  21417. static ma_uint32 ma_get_period_size_in_bytes(ma_uint32 periodSizeInFrames, ma_format format, ma_uint32 channels)
  21418. {
  21419. return periodSizeInFrames * ma_get_bytes_per_frame(format, channels);
  21420. }
  21421. /*
  21422. Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so
  21423. we can do things generically and typesafely. Names are being kept the same for consistency.
  21424. */
  21425. typedef struct
  21426. {
  21427. CHAR szPname[MA_MAXPNAMELEN];
  21428. DWORD dwFormats;
  21429. WORD wChannels;
  21430. GUID NameGuid;
  21431. } MA_WAVECAPSA;
  21432. static ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate)
  21433. {
  21434. WORD bitsPerSample = 0;
  21435. DWORD sampleRate = 0;
  21436. if (pBitsPerSample) {
  21437. *pBitsPerSample = 0;
  21438. }
  21439. if (pSampleRate) {
  21440. *pSampleRate = 0;
  21441. }
  21442. if (channels == 1) {
  21443. bitsPerSample = 16;
  21444. if ((dwFormats & WAVE_FORMAT_48M16) != 0) {
  21445. sampleRate = 48000;
  21446. } else if ((dwFormats & WAVE_FORMAT_44M16) != 0) {
  21447. sampleRate = 44100;
  21448. } else if ((dwFormats & WAVE_FORMAT_2M16) != 0) {
  21449. sampleRate = 22050;
  21450. } else if ((dwFormats & WAVE_FORMAT_1M16) != 0) {
  21451. sampleRate = 11025;
  21452. } else if ((dwFormats & WAVE_FORMAT_96M16) != 0) {
  21453. sampleRate = 96000;
  21454. } else {
  21455. bitsPerSample = 8;
  21456. if ((dwFormats & WAVE_FORMAT_48M08) != 0) {
  21457. sampleRate = 48000;
  21458. } else if ((dwFormats & WAVE_FORMAT_44M08) != 0) {
  21459. sampleRate = 44100;
  21460. } else if ((dwFormats & WAVE_FORMAT_2M08) != 0) {
  21461. sampleRate = 22050;
  21462. } else if ((dwFormats & WAVE_FORMAT_1M08) != 0) {
  21463. sampleRate = 11025;
  21464. } else if ((dwFormats & WAVE_FORMAT_96M08) != 0) {
  21465. sampleRate = 96000;
  21466. } else {
  21467. return MA_FORMAT_NOT_SUPPORTED;
  21468. }
  21469. }
  21470. } else {
  21471. bitsPerSample = 16;
  21472. if ((dwFormats & WAVE_FORMAT_48S16) != 0) {
  21473. sampleRate = 48000;
  21474. } else if ((dwFormats & WAVE_FORMAT_44S16) != 0) {
  21475. sampleRate = 44100;
  21476. } else if ((dwFormats & WAVE_FORMAT_2S16) != 0) {
  21477. sampleRate = 22050;
  21478. } else if ((dwFormats & WAVE_FORMAT_1S16) != 0) {
  21479. sampleRate = 11025;
  21480. } else if ((dwFormats & WAVE_FORMAT_96S16) != 0) {
  21481. sampleRate = 96000;
  21482. } else {
  21483. bitsPerSample = 8;
  21484. if ((dwFormats & WAVE_FORMAT_48S08) != 0) {
  21485. sampleRate = 48000;
  21486. } else if ((dwFormats & WAVE_FORMAT_44S08) != 0) {
  21487. sampleRate = 44100;
  21488. } else if ((dwFormats & WAVE_FORMAT_2S08) != 0) {
  21489. sampleRate = 22050;
  21490. } else if ((dwFormats & WAVE_FORMAT_1S08) != 0) {
  21491. sampleRate = 11025;
  21492. } else if ((dwFormats & WAVE_FORMAT_96S08) != 0) {
  21493. sampleRate = 96000;
  21494. } else {
  21495. return MA_FORMAT_NOT_SUPPORTED;
  21496. }
  21497. }
  21498. }
  21499. if (pBitsPerSample) {
  21500. *pBitsPerSample = bitsPerSample;
  21501. }
  21502. if (pSampleRate) {
  21503. *pSampleRate = sampleRate;
  21504. }
  21505. return MA_SUCCESS;
  21506. }
  21507. static ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels, MA_WAVEFORMATEX* pWF)
  21508. {
  21509. ma_result result;
  21510. MA_ASSERT(pWF != NULL);
  21511. MA_ZERO_OBJECT(pWF);
  21512. pWF->cbSize = sizeof(*pWF);
  21513. pWF->wFormatTag = WAVE_FORMAT_PCM;
  21514. pWF->nChannels = (WORD)channels;
  21515. if (pWF->nChannels > 2) {
  21516. pWF->nChannels = 2;
  21517. }
  21518. result = ma_get_best_info_from_formats_flags__winmm(dwFormats, channels, &pWF->wBitsPerSample, &pWF->nSamplesPerSec);
  21519. if (result != MA_SUCCESS) {
  21520. return result;
  21521. }
  21522. pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8);
  21523. pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec;
  21524. return MA_SUCCESS;
  21525. }
  21526. static ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVECAPSA* pCaps, ma_device_info* pDeviceInfo)
  21527. {
  21528. WORD bitsPerSample;
  21529. DWORD sampleRate;
  21530. ma_result result;
  21531. MA_ASSERT(pContext != NULL);
  21532. MA_ASSERT(pCaps != NULL);
  21533. MA_ASSERT(pDeviceInfo != NULL);
  21534. /*
  21535. Name / Description
  21536. Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking
  21537. situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try
  21538. 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.
  21539. */
  21540. /* Set the default to begin with. */
  21541. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1);
  21542. /*
  21543. Now try the registry. There's a few things to consider here:
  21544. - The name GUID can be null, in which we case we just need to stick to the original 31 characters.
  21545. - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters.
  21546. - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The
  21547. problem, however is that WASAPI and DirectSound use "<component> (<name>)" format (such as "Speakers (High Definition Audio)"),
  21548. but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to
  21549. 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
  21550. name, and then concatenate the name from the registry.
  21551. */
  21552. if (!ma_is_guid_null(&pCaps->NameGuid)) {
  21553. WCHAR guidStrW[256];
  21554. if (((MA_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, ma_countof(guidStrW)) > 0) {
  21555. char guidStr[256];
  21556. char keyStr[1024];
  21557. HKEY hKey;
  21558. WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE);
  21559. ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\");
  21560. ma_strcat_s(keyStr, sizeof(keyStr), guidStr);
  21561. if (((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
  21562. BYTE nameFromReg[512];
  21563. DWORD nameFromRegSize = sizeof(nameFromReg);
  21564. LONG resultWin32 = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (BYTE*)nameFromReg, (DWORD*)&nameFromRegSize);
  21565. ((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey);
  21566. if (resultWin32 == ERROR_SUCCESS) {
  21567. /* We have the value from the registry, so now we need to construct the name string. */
  21568. char name[1024];
  21569. if (ma_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) {
  21570. char* nameBeg = ma_find_last_character(name, '(');
  21571. if (nameBeg != NULL) {
  21572. size_t leadingLen = (nameBeg - name);
  21573. ma_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1);
  21574. /* The closing ")", if it can fit. */
  21575. if (leadingLen + nameFromRegSize < sizeof(name)-1) {
  21576. ma_strcat_s(name, sizeof(name), ")");
  21577. }
  21578. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), name, (size_t)-1);
  21579. }
  21580. }
  21581. }
  21582. }
  21583. }
  21584. }
  21585. result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate);
  21586. if (result != MA_SUCCESS) {
  21587. return result;
  21588. }
  21589. if (bitsPerSample == 8) {
  21590. pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
  21591. } else if (bitsPerSample == 16) {
  21592. pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
  21593. } else if (bitsPerSample == 24) {
  21594. pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
  21595. } else if (bitsPerSample == 32) {
  21596. pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
  21597. } else {
  21598. return MA_FORMAT_NOT_SUPPORTED;
  21599. }
  21600. pDeviceInfo->nativeDataFormats[0].channels = pCaps->wChannels;
  21601. pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
  21602. pDeviceInfo->nativeDataFormats[0].flags = 0;
  21603. pDeviceInfo->nativeDataFormatCount = 1;
  21604. return MA_SUCCESS;
  21605. }
  21606. static ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_WAVEOUTCAPS2A* pCaps, ma_device_info* pDeviceInfo)
  21607. {
  21608. MA_WAVECAPSA caps;
  21609. MA_ASSERT(pContext != NULL);
  21610. MA_ASSERT(pCaps != NULL);
  21611. MA_ASSERT(pDeviceInfo != NULL);
  21612. MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
  21613. caps.dwFormats = pCaps->dwFormats;
  21614. caps.wChannels = pCaps->wChannels;
  21615. caps.NameGuid = pCaps->NameGuid;
  21616. return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
  21617. }
  21618. static ma_result ma_context_get_device_info_from_WAVEINCAPS2(ma_context* pContext, MA_WAVEINCAPS2A* pCaps, ma_device_info* pDeviceInfo)
  21619. {
  21620. MA_WAVECAPSA caps;
  21621. MA_ASSERT(pContext != NULL);
  21622. MA_ASSERT(pCaps != NULL);
  21623. MA_ASSERT(pDeviceInfo != NULL);
  21624. MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
  21625. caps.dwFormats = pCaps->dwFormats;
  21626. caps.wChannels = pCaps->wChannels;
  21627. caps.NameGuid = pCaps->NameGuid;
  21628. return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
  21629. }
  21630. static ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  21631. {
  21632. UINT playbackDeviceCount;
  21633. UINT captureDeviceCount;
  21634. UINT iPlaybackDevice;
  21635. UINT iCaptureDevice;
  21636. MA_ASSERT(pContext != NULL);
  21637. MA_ASSERT(callback != NULL);
  21638. /* Playback. */
  21639. playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)();
  21640. for (iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) {
  21641. MA_MMRESULT result;
  21642. MA_WAVEOUTCAPS2A caps;
  21643. MA_ZERO_OBJECT(&caps);
  21644. result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (MA_WAVEOUTCAPSA*)&caps, sizeof(caps));
  21645. if (result == MA_MMSYSERR_NOERROR) {
  21646. ma_device_info deviceInfo;
  21647. MA_ZERO_OBJECT(&deviceInfo);
  21648. deviceInfo.id.winmm = iPlaybackDevice;
  21649. /* The first enumerated device is the default device. */
  21650. if (iPlaybackDevice == 0) {
  21651. deviceInfo.isDefault = MA_TRUE;
  21652. }
  21653. if (ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
  21654. ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  21655. if (cbResult == MA_FALSE) {
  21656. return MA_SUCCESS; /* Enumeration was stopped. */
  21657. }
  21658. }
  21659. }
  21660. }
  21661. /* Capture. */
  21662. captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)();
  21663. for (iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) {
  21664. MA_MMRESULT result;
  21665. MA_WAVEINCAPS2A caps;
  21666. MA_ZERO_OBJECT(&caps);
  21667. result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (MA_WAVEINCAPSA*)&caps, sizeof(caps));
  21668. if (result == MA_MMSYSERR_NOERROR) {
  21669. ma_device_info deviceInfo;
  21670. MA_ZERO_OBJECT(&deviceInfo);
  21671. deviceInfo.id.winmm = iCaptureDevice;
  21672. /* The first enumerated device is the default device. */
  21673. if (iCaptureDevice == 0) {
  21674. deviceInfo.isDefault = MA_TRUE;
  21675. }
  21676. if (ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
  21677. ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  21678. if (cbResult == MA_FALSE) {
  21679. return MA_SUCCESS; /* Enumeration was stopped. */
  21680. }
  21681. }
  21682. }
  21683. }
  21684. return MA_SUCCESS;
  21685. }
  21686. 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)
  21687. {
  21688. UINT winMMDeviceID;
  21689. MA_ASSERT(pContext != NULL);
  21690. winMMDeviceID = 0;
  21691. if (pDeviceID != NULL) {
  21692. winMMDeviceID = (UINT)pDeviceID->winmm;
  21693. }
  21694. pDeviceInfo->id.winmm = winMMDeviceID;
  21695. /* The first ID is the default device. */
  21696. if (winMMDeviceID == 0) {
  21697. pDeviceInfo->isDefault = MA_TRUE;
  21698. }
  21699. if (deviceType == ma_device_type_playback) {
  21700. MA_MMRESULT result;
  21701. MA_WAVEOUTCAPS2A caps;
  21702. MA_ZERO_OBJECT(&caps);
  21703. result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (MA_WAVEOUTCAPSA*)&caps, sizeof(caps));
  21704. if (result == MA_MMSYSERR_NOERROR) {
  21705. return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo);
  21706. }
  21707. } else {
  21708. MA_MMRESULT result;
  21709. MA_WAVEINCAPS2A caps;
  21710. MA_ZERO_OBJECT(&caps);
  21711. result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (MA_WAVEINCAPSA*)&caps, sizeof(caps));
  21712. if (result == MA_MMSYSERR_NOERROR) {
  21713. return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo);
  21714. }
  21715. }
  21716. return MA_NO_DEVICE;
  21717. }
  21718. static ma_result ma_device_uninit__winmm(ma_device* pDevice)
  21719. {
  21720. MA_ASSERT(pDevice != NULL);
  21721. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21722. ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21723. CloseHandle((HANDLE)pDevice->winmm.hEventCapture);
  21724. }
  21725. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21726. ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21727. ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21728. CloseHandle((HANDLE)pDevice->winmm.hEventPlayback);
  21729. }
  21730. ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
  21731. MA_ZERO_OBJECT(&pDevice->winmm); /* Safety. */
  21732. return MA_SUCCESS;
  21733. }
  21734. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__winmm(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  21735. {
  21736. /* WinMM has a minimum period size of 40ms. */
  21737. ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(40, nativeSampleRate);
  21738. ma_uint32 periodSizeInFrames;
  21739. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile);
  21740. if (periodSizeInFrames < minPeriodSizeInFrames) {
  21741. periodSizeInFrames = minPeriodSizeInFrames;
  21742. }
  21743. return periodSizeInFrames;
  21744. }
  21745. static ma_result ma_device_init__winmm(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  21746. {
  21747. const char* errorMsg = "";
  21748. ma_result errorCode = MA_ERROR;
  21749. ma_result result = MA_SUCCESS;
  21750. ma_uint32 heapSize;
  21751. UINT winMMDeviceIDPlayback = 0;
  21752. UINT winMMDeviceIDCapture = 0;
  21753. MA_ASSERT(pDevice != NULL);
  21754. MA_ZERO_OBJECT(&pDevice->winmm);
  21755. if (pConfig->deviceType == ma_device_type_loopback) {
  21756. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  21757. }
  21758. /* No exlusive mode with WinMM. */
  21759. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  21760. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  21761. return MA_SHARE_MODE_NOT_SUPPORTED;
  21762. }
  21763. if (pDescriptorPlayback->pDeviceID != NULL) {
  21764. winMMDeviceIDPlayback = (UINT)pDescriptorPlayback->pDeviceID->winmm;
  21765. }
  21766. if (pDescriptorCapture->pDeviceID != NULL) {
  21767. winMMDeviceIDCapture = (UINT)pDescriptorCapture->pDeviceID->winmm;
  21768. }
  21769. /* The capture device needs to be initialized first. */
  21770. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  21771. MA_WAVEINCAPSA caps;
  21772. MA_WAVEFORMATEX wf;
  21773. MA_MMRESULT resultMM;
  21774. /* We use an event to know when a new fragment needs to be enqueued. */
  21775. pDevice->winmm.hEventCapture = (ma_handle)CreateEventA(NULL, TRUE, TRUE, NULL);
  21776. if (pDevice->winmm.hEventCapture == NULL) {
  21777. errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError());
  21778. goto on_error;
  21779. }
  21780. /* The format should be based on the device's actual format. */
  21781. if (((MA_PFN_waveInGetDevCapsA)pDevice->pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MA_MMSYSERR_NOERROR) {
  21782. errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
  21783. goto on_error;
  21784. }
  21785. result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
  21786. if (result != MA_SUCCESS) {
  21787. errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
  21788. goto on_error;
  21789. }
  21790. 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);
  21791. if (resultMM != MA_MMSYSERR_NOERROR) {
  21792. errorMsg = "[WinMM] Failed to open capture device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  21793. goto on_error;
  21794. }
  21795. pDescriptorCapture->format = ma_format_from_WAVEFORMATEX(&wf);
  21796. pDescriptorCapture->channels = wf.nChannels;
  21797. pDescriptorCapture->sampleRate = wf.nSamplesPerSec;
  21798. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  21799. pDescriptorCapture->periodCount = pDescriptorCapture->periodCount;
  21800. pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  21801. }
  21802. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  21803. MA_WAVEOUTCAPSA caps;
  21804. MA_WAVEFORMATEX wf;
  21805. MA_MMRESULT resultMM;
  21806. /* We use an event to know when a new fragment needs to be enqueued. */
  21807. pDevice->winmm.hEventPlayback = (ma_handle)CreateEventA(NULL, TRUE, TRUE, NULL);
  21808. if (pDevice->winmm.hEventPlayback == NULL) {
  21809. errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError());
  21810. goto on_error;
  21811. }
  21812. /* The format should be based on the device's actual format. */
  21813. if (((MA_PFN_waveOutGetDevCapsA)pDevice->pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MA_MMSYSERR_NOERROR) {
  21814. errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
  21815. goto on_error;
  21816. }
  21817. result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
  21818. if (result != MA_SUCCESS) {
  21819. errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
  21820. goto on_error;
  21821. }
  21822. 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);
  21823. if (resultMM != MA_MMSYSERR_NOERROR) {
  21824. errorMsg = "[WinMM] Failed to open playback device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  21825. goto on_error;
  21826. }
  21827. pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX(&wf);
  21828. pDescriptorPlayback->channels = wf.nChannels;
  21829. pDescriptorPlayback->sampleRate = wf.nSamplesPerSec;
  21830. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  21831. pDescriptorPlayback->periodCount = pDescriptorPlayback->periodCount;
  21832. pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  21833. }
  21834. /*
  21835. The heap allocated data is allocated like so:
  21836. [Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer]
  21837. */
  21838. heapSize = 0;
  21839. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  21840. heapSize += sizeof(MA_WAVEHDR)*pDescriptorCapture->periodCount + (pDescriptorCapture->periodSizeInFrames * pDescriptorCapture->periodCount * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
  21841. }
  21842. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  21843. heapSize += sizeof(MA_WAVEHDR)*pDescriptorPlayback->periodCount + (pDescriptorPlayback->periodSizeInFrames * pDescriptorPlayback->periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels));
  21844. }
  21845. pDevice->winmm._pHeapData = (ma_uint8*)ma_calloc(heapSize, &pDevice->pContext->allocationCallbacks);
  21846. if (pDevice->winmm._pHeapData == NULL) {
  21847. errorMsg = "[WinMM] Failed to allocate memory for the intermediary buffer.", errorCode = MA_OUT_OF_MEMORY;
  21848. goto on_error;
  21849. }
  21850. MA_ZERO_MEMORY(pDevice->winmm._pHeapData, heapSize);
  21851. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  21852. ma_uint32 iPeriod;
  21853. if (pConfig->deviceType == ma_device_type_capture) {
  21854. pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
  21855. pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount));
  21856. } else {
  21857. pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
  21858. pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount));
  21859. }
  21860. /* Prepare headers. */
  21861. for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
  21862. ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->format, pDescriptorCapture->channels);
  21863. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (char*)(pDevice->winmm.pIntermediaryBufferCapture + (periodSizeInBytes*iPeriod));
  21864. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwBufferLength = periodSizeInBytes;
  21865. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwFlags = 0L;
  21866. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwLoops = 0L;
  21867. ((MA_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR));
  21868. /*
  21869. 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
  21870. it's unlocked and available for writing. A value of 1 means it's locked.
  21871. */
  21872. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwUser = 0;
  21873. }
  21874. }
  21875. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  21876. ma_uint32 iPeriod;
  21877. if (pConfig->deviceType == ma_device_type_playback) {
  21878. pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData;
  21879. pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*pDescriptorPlayback->periodCount);
  21880. } else {
  21881. pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(MA_WAVEHDR)*(pDescriptorCapture->periodCount));
  21882. 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));
  21883. }
  21884. /* Prepare headers. */
  21885. for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
  21886. ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->format, pDescriptorPlayback->channels);
  21887. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (char*)(pDevice->winmm.pIntermediaryBufferPlayback + (periodSizeInBytes*iPeriod));
  21888. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwBufferLength = periodSizeInBytes;
  21889. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwFlags = 0L;
  21890. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwLoops = 0L;
  21891. ((MA_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(MA_WAVEHDR));
  21892. /*
  21893. 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
  21894. it's unlocked and available for writing. A value of 1 means it's locked.
  21895. */
  21896. ((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwUser = 0;
  21897. }
  21898. }
  21899. return MA_SUCCESS;
  21900. on_error:
  21901. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21902. if (pDevice->winmm.pWAVEHDRCapture != NULL) {
  21903. ma_uint32 iPeriod;
  21904. for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
  21905. ((MA_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR));
  21906. }
  21907. }
  21908. ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21909. }
  21910. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21911. if (pDevice->winmm.pWAVEHDRCapture != NULL) {
  21912. ma_uint32 iPeriod;
  21913. for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
  21914. ((MA_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(MA_WAVEHDR));
  21915. }
  21916. }
  21917. ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21918. }
  21919. ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
  21920. if (errorMsg != NULL && errorMsg[0] != '\0') {
  21921. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "%s", errorMsg);
  21922. }
  21923. return errorCode;
  21924. }
  21925. static ma_result ma_device_start__winmm(ma_device* pDevice)
  21926. {
  21927. MA_ASSERT(pDevice != NULL);
  21928. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21929. MA_MMRESULT resultMM;
  21930. MA_WAVEHDR* pWAVEHDR;
  21931. ma_uint32 iPeriod;
  21932. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
  21933. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  21934. ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
  21935. /* 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. */
  21936. for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
  21937. resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(MA_WAVEHDR));
  21938. if (resultMM != MA_MMSYSERR_NOERROR) {
  21939. 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.");
  21940. return ma_result_from_MMRESULT(resultMM);
  21941. }
  21942. /* Make sure all of the buffers start out locked. We don't want to access them until the backend tells us we can. */
  21943. pWAVEHDR[iPeriod].dwUser = 1; /* 1 = locked. */
  21944. }
  21945. /* Capture devices need to be explicitly started, unlike playback devices. */
  21946. resultMM = ((MA_PFN_waveInStart)pDevice->pContext->winmm.waveInStart)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21947. if (resultMM != MA_MMSYSERR_NOERROR) {
  21948. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device.");
  21949. return ma_result_from_MMRESULT(resultMM);
  21950. }
  21951. }
  21952. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21953. /* Don't need to do anything for playback. It'll be started automatically in ma_device_start__winmm(). */
  21954. }
  21955. return MA_SUCCESS;
  21956. }
  21957. static ma_result ma_device_stop__winmm(ma_device* pDevice)
  21958. {
  21959. MA_MMRESULT resultMM;
  21960. MA_ASSERT(pDevice != NULL);
  21961. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21962. if (pDevice->winmm.hDeviceCapture == NULL) {
  21963. return MA_INVALID_ARGS;
  21964. }
  21965. resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture);
  21966. if (resultMM != MA_MMSYSERR_NOERROR) {
  21967. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset capture device.");
  21968. }
  21969. }
  21970. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21971. ma_uint32 iPeriod;
  21972. MA_WAVEHDR* pWAVEHDR;
  21973. if (pDevice->winmm.hDevicePlayback == NULL) {
  21974. return MA_INVALID_ARGS;
  21975. }
  21976. /* 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. */
  21977. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
  21978. for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; iPeriod += 1) {
  21979. if (pWAVEHDR[iPeriod].dwUser == 1) { /* 1 = locked. */
  21980. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
  21981. break; /* An error occurred so just abandon ship and stop the device without draining. */
  21982. }
  21983. pWAVEHDR[iPeriod].dwUser = 0;
  21984. }
  21985. }
  21986. resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21987. if (resultMM != MA_MMSYSERR_NOERROR) {
  21988. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset playback device.");
  21989. }
  21990. }
  21991. return MA_SUCCESS;
  21992. }
  21993. static ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  21994. {
  21995. ma_result result = MA_SUCCESS;
  21996. MA_MMRESULT resultMM;
  21997. ma_uint32 totalFramesWritten;
  21998. MA_WAVEHDR* pWAVEHDR;
  21999. MA_ASSERT(pDevice != NULL);
  22000. MA_ASSERT(pPCMFrames != NULL);
  22001. if (pFramesWritten != NULL) {
  22002. *pFramesWritten = 0;
  22003. }
  22004. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
  22005. /* Keep processing as much data as possible. */
  22006. totalFramesWritten = 0;
  22007. while (totalFramesWritten < frameCount) {
  22008. /* If the current header has some space available we need to write part of it. */
  22009. if (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser == 0) { /* 0 = unlocked. */
  22010. /*
  22011. 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
  22012. write it out and move on to the next iteration.
  22013. */
  22014. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  22015. ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedPlayback;
  22016. ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesWritten));
  22017. const void* pSrc = ma_offset_ptr(pPCMFrames, totalFramesWritten*bpf);
  22018. void* pDst = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].lpData, pDevice->winmm.headerFramesConsumedPlayback*bpf);
  22019. MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
  22020. pDevice->winmm.headerFramesConsumedPlayback += framesToCopy;
  22021. totalFramesWritten += framesToCopy;
  22022. /* If we've consumed the buffer entirely we need to write it out to the device. */
  22023. if (pDevice->winmm.headerFramesConsumedPlayback == (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf)) {
  22024. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 1; /* 1 = locked. */
  22025. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags &= ~MA_WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
  22026. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  22027. ResetEvent((HANDLE)pDevice->winmm.hEventPlayback);
  22028. /* The device will be started here. */
  22029. resultMM = ((MA_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((MA_HWAVEOUT)pDevice->winmm.hDevicePlayback, &pWAVEHDR[pDevice->winmm.iNextHeaderPlayback], sizeof(MA_WAVEHDR));
  22030. if (resultMM != MA_MMSYSERR_NOERROR) {
  22031. result = ma_result_from_MMRESULT(resultMM);
  22032. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveOutWrite() failed.");
  22033. break;
  22034. }
  22035. /* Make sure we move to the next header. */
  22036. pDevice->winmm.iNextHeaderPlayback = (pDevice->winmm.iNextHeaderPlayback + 1) % pDevice->playback.internalPeriods;
  22037. pDevice->winmm.headerFramesConsumedPlayback = 0;
  22038. }
  22039. /* If at this point we have consumed the entire input buffer we can return. */
  22040. MA_ASSERT(totalFramesWritten <= frameCount);
  22041. if (totalFramesWritten == frameCount) {
  22042. break;
  22043. }
  22044. /* Getting here means there's more to process. */
  22045. continue;
  22046. }
  22047. /* Getting here means there isn't enough room in the buffer and we need to wait for one to become available. */
  22048. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
  22049. result = MA_ERROR;
  22050. break;
  22051. }
  22052. /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
  22053. if ((pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags & MA_WHDR_DONE) != 0) {
  22054. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 0; /* 0 = unlocked (make it available for writing). */
  22055. pDevice->winmm.headerFramesConsumedPlayback = 0;
  22056. }
  22057. /* If the device has been stopped we need to break. */
  22058. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  22059. break;
  22060. }
  22061. }
  22062. if (pFramesWritten != NULL) {
  22063. *pFramesWritten = totalFramesWritten;
  22064. }
  22065. return result;
  22066. }
  22067. static ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  22068. {
  22069. ma_result result = MA_SUCCESS;
  22070. MA_MMRESULT resultMM;
  22071. ma_uint32 totalFramesRead;
  22072. MA_WAVEHDR* pWAVEHDR;
  22073. MA_ASSERT(pDevice != NULL);
  22074. MA_ASSERT(pPCMFrames != NULL);
  22075. if (pFramesRead != NULL) {
  22076. *pFramesRead = 0;
  22077. }
  22078. pWAVEHDR = (MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
  22079. /* Keep processing as much data as possible. */
  22080. totalFramesRead = 0;
  22081. while (totalFramesRead < frameCount) {
  22082. /* If the current header has some space available we need to write part of it. */
  22083. if (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser == 0) { /* 0 = unlocked. */
  22084. /* The buffer is available for reading. If we fully consume it we need to add it back to the buffer. */
  22085. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  22086. ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedCapture;
  22087. ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesRead));
  22088. const void* pSrc = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderCapture].lpData, pDevice->winmm.headerFramesConsumedCapture*bpf);
  22089. void* pDst = ma_offset_ptr(pPCMFrames, totalFramesRead*bpf);
  22090. MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
  22091. pDevice->winmm.headerFramesConsumedCapture += framesToCopy;
  22092. totalFramesRead += framesToCopy;
  22093. /* If we've consumed the buffer entirely we need to add it back to the device. */
  22094. if (pDevice->winmm.headerFramesConsumedCapture == (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf)) {
  22095. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 1; /* 1 = locked. */
  22096. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags &= ~MA_WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
  22097. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  22098. ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
  22099. /* The device will be started here. */
  22100. resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((MA_HWAVEIN)pDevice->winmm.hDeviceCapture, &((MA_WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[pDevice->winmm.iNextHeaderCapture], sizeof(MA_WAVEHDR));
  22101. if (resultMM != MA_MMSYSERR_NOERROR) {
  22102. result = ma_result_from_MMRESULT(resultMM);
  22103. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveInAddBuffer() failed.");
  22104. break;
  22105. }
  22106. /* Make sure we move to the next header. */
  22107. pDevice->winmm.iNextHeaderCapture = (pDevice->winmm.iNextHeaderCapture + 1) % pDevice->capture.internalPeriods;
  22108. pDevice->winmm.headerFramesConsumedCapture = 0;
  22109. }
  22110. /* If at this point we have filled the entire input buffer we can return. */
  22111. MA_ASSERT(totalFramesRead <= frameCount);
  22112. if (totalFramesRead == frameCount) {
  22113. break;
  22114. }
  22115. /* Getting here means there's more to process. */
  22116. continue;
  22117. }
  22118. /* Getting here means there isn't enough any data left to send to the client which means we need to wait for more. */
  22119. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
  22120. result = MA_ERROR;
  22121. break;
  22122. }
  22123. /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
  22124. if ((pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags & MA_WHDR_DONE) != 0) {
  22125. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 0; /* 0 = unlocked (make it available for reading). */
  22126. pDevice->winmm.headerFramesConsumedCapture = 0;
  22127. }
  22128. /* If the device has been stopped we need to break. */
  22129. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  22130. break;
  22131. }
  22132. }
  22133. if (pFramesRead != NULL) {
  22134. *pFramesRead = totalFramesRead;
  22135. }
  22136. return result;
  22137. }
  22138. static ma_result ma_context_uninit__winmm(ma_context* pContext)
  22139. {
  22140. MA_ASSERT(pContext != NULL);
  22141. MA_ASSERT(pContext->backend == ma_backend_winmm);
  22142. ma_dlclose(ma_context_get_log(pContext), pContext->winmm.hWinMM);
  22143. return MA_SUCCESS;
  22144. }
  22145. static ma_result ma_context_init__winmm(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  22146. {
  22147. MA_ASSERT(pContext != NULL);
  22148. (void)pConfig;
  22149. pContext->winmm.hWinMM = ma_dlopen(ma_context_get_log(pContext), "winmm.dll");
  22150. if (pContext->winmm.hWinMM == NULL) {
  22151. return MA_NO_BACKEND;
  22152. }
  22153. pContext->winmm.waveOutGetNumDevs = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutGetNumDevs");
  22154. pContext->winmm.waveOutGetDevCapsA = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutGetDevCapsA");
  22155. pContext->winmm.waveOutOpen = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutOpen");
  22156. pContext->winmm.waveOutClose = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutClose");
  22157. pContext->winmm.waveOutPrepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutPrepareHeader");
  22158. pContext->winmm.waveOutUnprepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutUnprepareHeader");
  22159. pContext->winmm.waveOutWrite = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutWrite");
  22160. pContext->winmm.waveOutReset = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveOutReset");
  22161. pContext->winmm.waveInGetNumDevs = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInGetNumDevs");
  22162. pContext->winmm.waveInGetDevCapsA = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInGetDevCapsA");
  22163. pContext->winmm.waveInOpen = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInOpen");
  22164. pContext->winmm.waveInClose = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInClose");
  22165. pContext->winmm.waveInPrepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInPrepareHeader");
  22166. pContext->winmm.waveInUnprepareHeader = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInUnprepareHeader");
  22167. pContext->winmm.waveInAddBuffer = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInAddBuffer");
  22168. pContext->winmm.waveInStart = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInStart");
  22169. pContext->winmm.waveInReset = ma_dlsym(ma_context_get_log(pContext), pContext->winmm.hWinMM, "waveInReset");
  22170. pCallbacks->onContextInit = ma_context_init__winmm;
  22171. pCallbacks->onContextUninit = ma_context_uninit__winmm;
  22172. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__winmm;
  22173. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__winmm;
  22174. pCallbacks->onDeviceInit = ma_device_init__winmm;
  22175. pCallbacks->onDeviceUninit = ma_device_uninit__winmm;
  22176. pCallbacks->onDeviceStart = ma_device_start__winmm;
  22177. pCallbacks->onDeviceStop = ma_device_stop__winmm;
  22178. pCallbacks->onDeviceRead = ma_device_read__winmm;
  22179. pCallbacks->onDeviceWrite = ma_device_write__winmm;
  22180. pCallbacks->onDeviceDataLoop = NULL; /* This is a blocking read-write API, so this can be NULL since miniaudio will manage the audio thread for us. */
  22181. return MA_SUCCESS;
  22182. }
  22183. #endif
  22184. /******************************************************************************
  22185. ALSA Backend
  22186. ******************************************************************************/
  22187. #ifdef MA_HAS_ALSA
  22188. #include <poll.h> /* poll(), struct pollfd */
  22189. #include <sys/eventfd.h> /* eventfd() */
  22190. #ifdef MA_NO_RUNTIME_LINKING
  22191. /* asoundlib.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
  22192. #if !defined(__cplusplus)
  22193. #if defined(__STRICT_ANSI__)
  22194. #if !defined(inline)
  22195. #define inline __inline__ __attribute__((always_inline))
  22196. #define MA_INLINE_DEFINED
  22197. #endif
  22198. #endif
  22199. #endif
  22200. #include <alsa/asoundlib.h>
  22201. #if defined(MA_INLINE_DEFINED)
  22202. #undef inline
  22203. #undef MA_INLINE_DEFINED
  22204. #endif
  22205. typedef snd_pcm_uframes_t ma_snd_pcm_uframes_t;
  22206. typedef snd_pcm_sframes_t ma_snd_pcm_sframes_t;
  22207. typedef snd_pcm_stream_t ma_snd_pcm_stream_t;
  22208. typedef snd_pcm_format_t ma_snd_pcm_format_t;
  22209. typedef snd_pcm_access_t ma_snd_pcm_access_t;
  22210. typedef snd_pcm_t ma_snd_pcm_t;
  22211. typedef snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
  22212. typedef snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
  22213. typedef snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
  22214. typedef snd_pcm_info_t ma_snd_pcm_info_t;
  22215. typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t;
  22216. typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t;
  22217. typedef snd_pcm_state_t ma_snd_pcm_state_t;
  22218. /* snd_pcm_stream_t */
  22219. #define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK
  22220. #define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE
  22221. /* snd_pcm_format_t */
  22222. #define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN
  22223. #define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8
  22224. #define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE
  22225. #define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE
  22226. #define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE
  22227. #define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE
  22228. #define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE
  22229. #define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE
  22230. #define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE
  22231. #define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE
  22232. #define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE
  22233. #define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE
  22234. #define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW
  22235. #define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW
  22236. #define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE
  22237. #define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE
  22238. /* ma_snd_pcm_access_t */
  22239. #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED
  22240. #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED
  22241. #define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX
  22242. #define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED
  22243. #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED
  22244. /* Channel positions. */
  22245. #define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN
  22246. #define MA_SND_CHMAP_NA SND_CHMAP_NA
  22247. #define MA_SND_CHMAP_MONO SND_CHMAP_MONO
  22248. #define MA_SND_CHMAP_FL SND_CHMAP_FL
  22249. #define MA_SND_CHMAP_FR SND_CHMAP_FR
  22250. #define MA_SND_CHMAP_RL SND_CHMAP_RL
  22251. #define MA_SND_CHMAP_RR SND_CHMAP_RR
  22252. #define MA_SND_CHMAP_FC SND_CHMAP_FC
  22253. #define MA_SND_CHMAP_LFE SND_CHMAP_LFE
  22254. #define MA_SND_CHMAP_SL SND_CHMAP_SL
  22255. #define MA_SND_CHMAP_SR SND_CHMAP_SR
  22256. #define MA_SND_CHMAP_RC SND_CHMAP_RC
  22257. #define MA_SND_CHMAP_FLC SND_CHMAP_FLC
  22258. #define MA_SND_CHMAP_FRC SND_CHMAP_FRC
  22259. #define MA_SND_CHMAP_RLC SND_CHMAP_RLC
  22260. #define MA_SND_CHMAP_RRC SND_CHMAP_RRC
  22261. #define MA_SND_CHMAP_FLW SND_CHMAP_FLW
  22262. #define MA_SND_CHMAP_FRW SND_CHMAP_FRW
  22263. #define MA_SND_CHMAP_FLH SND_CHMAP_FLH
  22264. #define MA_SND_CHMAP_FCH SND_CHMAP_FCH
  22265. #define MA_SND_CHMAP_FRH SND_CHMAP_FRH
  22266. #define MA_SND_CHMAP_TC SND_CHMAP_TC
  22267. #define MA_SND_CHMAP_TFL SND_CHMAP_TFL
  22268. #define MA_SND_CHMAP_TFR SND_CHMAP_TFR
  22269. #define MA_SND_CHMAP_TFC SND_CHMAP_TFC
  22270. #define MA_SND_CHMAP_TRL SND_CHMAP_TRL
  22271. #define MA_SND_CHMAP_TRR SND_CHMAP_TRR
  22272. #define MA_SND_CHMAP_TRC SND_CHMAP_TRC
  22273. #define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC
  22274. #define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC
  22275. #define MA_SND_CHMAP_TSL SND_CHMAP_TSL
  22276. #define MA_SND_CHMAP_TSR SND_CHMAP_TSR
  22277. #define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE
  22278. #define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE
  22279. #define MA_SND_CHMAP_BC SND_CHMAP_BC
  22280. #define MA_SND_CHMAP_BLC SND_CHMAP_BLC
  22281. #define MA_SND_CHMAP_BRC SND_CHMAP_BRC
  22282. /* Open mode flags. */
  22283. #define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE
  22284. #define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS
  22285. #define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT
  22286. #else
  22287. #include <errno.h> /* For EPIPE, etc. */
  22288. typedef unsigned long ma_snd_pcm_uframes_t;
  22289. typedef long ma_snd_pcm_sframes_t;
  22290. typedef int ma_snd_pcm_stream_t;
  22291. typedef int ma_snd_pcm_format_t;
  22292. typedef int ma_snd_pcm_access_t;
  22293. typedef int ma_snd_pcm_state_t;
  22294. typedef struct ma_snd_pcm_t ma_snd_pcm_t;
  22295. typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
  22296. typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
  22297. typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
  22298. typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t;
  22299. typedef struct
  22300. {
  22301. void* addr;
  22302. unsigned int first;
  22303. unsigned int step;
  22304. } ma_snd_pcm_channel_area_t;
  22305. typedef struct
  22306. {
  22307. unsigned int channels;
  22308. unsigned int pos[1];
  22309. } ma_snd_pcm_chmap_t;
  22310. /* snd_pcm_state_t */
  22311. #define MA_SND_PCM_STATE_OPEN 0
  22312. #define MA_SND_PCM_STATE_SETUP 1
  22313. #define MA_SND_PCM_STATE_PREPARED 2
  22314. #define MA_SND_PCM_STATE_RUNNING 3
  22315. #define MA_SND_PCM_STATE_XRUN 4
  22316. #define MA_SND_PCM_STATE_DRAINING 5
  22317. #define MA_SND_PCM_STATE_PAUSED 6
  22318. #define MA_SND_PCM_STATE_SUSPENDED 7
  22319. #define MA_SND_PCM_STATE_DISCONNECTED 8
  22320. /* snd_pcm_stream_t */
  22321. #define MA_SND_PCM_STREAM_PLAYBACK 0
  22322. #define MA_SND_PCM_STREAM_CAPTURE 1
  22323. /* snd_pcm_format_t */
  22324. #define MA_SND_PCM_FORMAT_UNKNOWN -1
  22325. #define MA_SND_PCM_FORMAT_U8 1
  22326. #define MA_SND_PCM_FORMAT_S16_LE 2
  22327. #define MA_SND_PCM_FORMAT_S16_BE 3
  22328. #define MA_SND_PCM_FORMAT_S24_LE 6
  22329. #define MA_SND_PCM_FORMAT_S24_BE 7
  22330. #define MA_SND_PCM_FORMAT_S32_LE 10
  22331. #define MA_SND_PCM_FORMAT_S32_BE 11
  22332. #define MA_SND_PCM_FORMAT_FLOAT_LE 14
  22333. #define MA_SND_PCM_FORMAT_FLOAT_BE 15
  22334. #define MA_SND_PCM_FORMAT_FLOAT64_LE 16
  22335. #define MA_SND_PCM_FORMAT_FLOAT64_BE 17
  22336. #define MA_SND_PCM_FORMAT_MU_LAW 20
  22337. #define MA_SND_PCM_FORMAT_A_LAW 21
  22338. #define MA_SND_PCM_FORMAT_S24_3LE 32
  22339. #define MA_SND_PCM_FORMAT_S24_3BE 33
  22340. /* snd_pcm_access_t */
  22341. #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED 0
  22342. #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1
  22343. #define MA_SND_PCM_ACCESS_MMAP_COMPLEX 2
  22344. #define MA_SND_PCM_ACCESS_RW_INTERLEAVED 3
  22345. #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED 4
  22346. /* Channel positions. */
  22347. #define MA_SND_CHMAP_UNKNOWN 0
  22348. #define MA_SND_CHMAP_NA 1
  22349. #define MA_SND_CHMAP_MONO 2
  22350. #define MA_SND_CHMAP_FL 3
  22351. #define MA_SND_CHMAP_FR 4
  22352. #define MA_SND_CHMAP_RL 5
  22353. #define MA_SND_CHMAP_RR 6
  22354. #define MA_SND_CHMAP_FC 7
  22355. #define MA_SND_CHMAP_LFE 8
  22356. #define MA_SND_CHMAP_SL 9
  22357. #define MA_SND_CHMAP_SR 10
  22358. #define MA_SND_CHMAP_RC 11
  22359. #define MA_SND_CHMAP_FLC 12
  22360. #define MA_SND_CHMAP_FRC 13
  22361. #define MA_SND_CHMAP_RLC 14
  22362. #define MA_SND_CHMAP_RRC 15
  22363. #define MA_SND_CHMAP_FLW 16
  22364. #define MA_SND_CHMAP_FRW 17
  22365. #define MA_SND_CHMAP_FLH 18
  22366. #define MA_SND_CHMAP_FCH 19
  22367. #define MA_SND_CHMAP_FRH 20
  22368. #define MA_SND_CHMAP_TC 21
  22369. #define MA_SND_CHMAP_TFL 22
  22370. #define MA_SND_CHMAP_TFR 23
  22371. #define MA_SND_CHMAP_TFC 24
  22372. #define MA_SND_CHMAP_TRL 25
  22373. #define MA_SND_CHMAP_TRR 26
  22374. #define MA_SND_CHMAP_TRC 27
  22375. #define MA_SND_CHMAP_TFLC 28
  22376. #define MA_SND_CHMAP_TFRC 29
  22377. #define MA_SND_CHMAP_TSL 30
  22378. #define MA_SND_CHMAP_TSR 31
  22379. #define MA_SND_CHMAP_LLFE 32
  22380. #define MA_SND_CHMAP_RLFE 33
  22381. #define MA_SND_CHMAP_BC 34
  22382. #define MA_SND_CHMAP_BLC 35
  22383. #define MA_SND_CHMAP_BRC 36
  22384. /* Open mode flags. */
  22385. #define MA_SND_PCM_NO_AUTO_RESAMPLE 0x00010000
  22386. #define MA_SND_PCM_NO_AUTO_CHANNELS 0x00020000
  22387. #define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000
  22388. #endif
  22389. typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode);
  22390. typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm);
  22391. typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void);
  22392. typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
  22393. 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);
  22394. 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);
  22395. 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);
  22396. 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);
  22397. 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);
  22398. 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);
  22399. 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);
  22400. 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);
  22401. 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);
  22402. 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);
  22403. 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);
  22404. 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);
  22405. typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format);
  22406. typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22407. typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22408. typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  22409. typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  22410. typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  22411. typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  22412. 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);
  22413. typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
  22414. typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access);
  22415. 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);
  22416. 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);
  22417. 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);
  22418. typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
  22419. typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void);
  22420. typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
  22421. typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (const ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val);
  22422. 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);
  22423. 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);
  22424. 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);
  22425. typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
  22426. typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void);
  22427. typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val);
  22428. typedef ma_snd_pcm_chmap_t * (* ma_snd_pcm_get_chmap_proc) (ma_snd_pcm_t *pcm);
  22429. typedef ma_snd_pcm_state_t (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm);
  22430. typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm);
  22431. typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm);
  22432. typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm);
  22433. typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm);
  22434. typedef int (* ma_snd_pcm_reset_proc) (ma_snd_pcm_t *pcm);
  22435. typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints);
  22436. typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id);
  22437. typedef int (* ma_snd_card_get_index_proc) (const char *name);
  22438. typedef int (* ma_snd_device_name_free_hint_proc) (void **hints);
  22439. 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);
  22440. 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);
  22441. typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent);
  22442. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_readi_proc) (ma_snd_pcm_t *pcm, void *buffer, ma_snd_pcm_uframes_t size);
  22443. 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);
  22444. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_proc) (ma_snd_pcm_t *pcm);
  22445. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_update_proc) (ma_snd_pcm_t *pcm);
  22446. typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout);
  22447. typedef int (* ma_snd_pcm_nonblock_proc) (ma_snd_pcm_t *pcm, int nonblock);
  22448. typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info);
  22449. typedef size_t (* ma_snd_pcm_info_sizeof_proc) (void);
  22450. typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info);
  22451. typedef int (* ma_snd_pcm_poll_descriptors_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int space);
  22452. typedef int (* ma_snd_pcm_poll_descriptors_count_proc) (ma_snd_pcm_t *pcm);
  22453. typedef int (* ma_snd_pcm_poll_descriptors_revents_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int nfds, unsigned short *revents);
  22454. typedef int (* ma_snd_config_update_free_global_proc) (void);
  22455. /* This array specifies each of the common devices that can be used for both playback and capture. */
  22456. static const char* g_maCommonDeviceNamesALSA[] = {
  22457. "default",
  22458. "null",
  22459. "pulse",
  22460. "jack"
  22461. };
  22462. /* This array allows us to blacklist specific playback devices. */
  22463. static const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = {
  22464. ""
  22465. };
  22466. /* This array allows us to blacklist specific capture devices. */
  22467. static const char* g_maBlacklistedCaptureDeviceNamesALSA[] = {
  22468. ""
  22469. };
  22470. static ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format)
  22471. {
  22472. ma_snd_pcm_format_t ALSAFormats[] = {
  22473. MA_SND_PCM_FORMAT_UNKNOWN, /* ma_format_unknown */
  22474. MA_SND_PCM_FORMAT_U8, /* ma_format_u8 */
  22475. MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */
  22476. MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */
  22477. MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */
  22478. MA_SND_PCM_FORMAT_FLOAT_LE /* ma_format_f32 */
  22479. };
  22480. if (ma_is_big_endian()) {
  22481. ALSAFormats[0] = MA_SND_PCM_FORMAT_UNKNOWN;
  22482. ALSAFormats[1] = MA_SND_PCM_FORMAT_U8;
  22483. ALSAFormats[2] = MA_SND_PCM_FORMAT_S16_BE;
  22484. ALSAFormats[3] = MA_SND_PCM_FORMAT_S24_3BE;
  22485. ALSAFormats[4] = MA_SND_PCM_FORMAT_S32_BE;
  22486. ALSAFormats[5] = MA_SND_PCM_FORMAT_FLOAT_BE;
  22487. }
  22488. return ALSAFormats[format];
  22489. }
  22490. static ma_format ma_format_from_alsa(ma_snd_pcm_format_t formatALSA)
  22491. {
  22492. if (ma_is_little_endian()) {
  22493. switch (formatALSA) {
  22494. case MA_SND_PCM_FORMAT_S16_LE: return ma_format_s16;
  22495. case MA_SND_PCM_FORMAT_S24_3LE: return ma_format_s24;
  22496. case MA_SND_PCM_FORMAT_S32_LE: return ma_format_s32;
  22497. case MA_SND_PCM_FORMAT_FLOAT_LE: return ma_format_f32;
  22498. default: break;
  22499. }
  22500. } else {
  22501. switch (formatALSA) {
  22502. case MA_SND_PCM_FORMAT_S16_BE: return ma_format_s16;
  22503. case MA_SND_PCM_FORMAT_S24_3BE: return ma_format_s24;
  22504. case MA_SND_PCM_FORMAT_S32_BE: return ma_format_s32;
  22505. case MA_SND_PCM_FORMAT_FLOAT_BE: return ma_format_f32;
  22506. default: break;
  22507. }
  22508. }
  22509. /* Endian agnostic. */
  22510. switch (formatALSA) {
  22511. case MA_SND_PCM_FORMAT_U8: return ma_format_u8;
  22512. default: return ma_format_unknown;
  22513. }
  22514. }
  22515. static ma_channel ma_convert_alsa_channel_position_to_ma_channel(unsigned int alsaChannelPos)
  22516. {
  22517. switch (alsaChannelPos)
  22518. {
  22519. case MA_SND_CHMAP_MONO: return MA_CHANNEL_MONO;
  22520. case MA_SND_CHMAP_FL: return MA_CHANNEL_FRONT_LEFT;
  22521. case MA_SND_CHMAP_FR: return MA_CHANNEL_FRONT_RIGHT;
  22522. case MA_SND_CHMAP_RL: return MA_CHANNEL_BACK_LEFT;
  22523. case MA_SND_CHMAP_RR: return MA_CHANNEL_BACK_RIGHT;
  22524. case MA_SND_CHMAP_FC: return MA_CHANNEL_FRONT_CENTER;
  22525. case MA_SND_CHMAP_LFE: return MA_CHANNEL_LFE;
  22526. case MA_SND_CHMAP_SL: return MA_CHANNEL_SIDE_LEFT;
  22527. case MA_SND_CHMAP_SR: return MA_CHANNEL_SIDE_RIGHT;
  22528. case MA_SND_CHMAP_RC: return MA_CHANNEL_BACK_CENTER;
  22529. case MA_SND_CHMAP_FLC: return MA_CHANNEL_FRONT_LEFT_CENTER;
  22530. case MA_SND_CHMAP_FRC: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  22531. case MA_SND_CHMAP_RLC: return 0;
  22532. case MA_SND_CHMAP_RRC: return 0;
  22533. case MA_SND_CHMAP_FLW: return 0;
  22534. case MA_SND_CHMAP_FRW: return 0;
  22535. case MA_SND_CHMAP_FLH: return 0;
  22536. case MA_SND_CHMAP_FCH: return 0;
  22537. case MA_SND_CHMAP_FRH: return 0;
  22538. case MA_SND_CHMAP_TC: return MA_CHANNEL_TOP_CENTER;
  22539. case MA_SND_CHMAP_TFL: return MA_CHANNEL_TOP_FRONT_LEFT;
  22540. case MA_SND_CHMAP_TFR: return MA_CHANNEL_TOP_FRONT_RIGHT;
  22541. case MA_SND_CHMAP_TFC: return MA_CHANNEL_TOP_FRONT_CENTER;
  22542. case MA_SND_CHMAP_TRL: return MA_CHANNEL_TOP_BACK_LEFT;
  22543. case MA_SND_CHMAP_TRR: return MA_CHANNEL_TOP_BACK_RIGHT;
  22544. case MA_SND_CHMAP_TRC: return MA_CHANNEL_TOP_BACK_CENTER;
  22545. default: break;
  22546. }
  22547. return 0;
  22548. }
  22549. static ma_bool32 ma_is_common_device_name__alsa(const char* name)
  22550. {
  22551. size_t iName;
  22552. for (iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) {
  22553. if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) {
  22554. return MA_TRUE;
  22555. }
  22556. }
  22557. return MA_FALSE;
  22558. }
  22559. static ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name)
  22560. {
  22561. size_t iName;
  22562. for (iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) {
  22563. if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) {
  22564. return MA_TRUE;
  22565. }
  22566. }
  22567. return MA_FALSE;
  22568. }
  22569. static ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name)
  22570. {
  22571. size_t iName;
  22572. for (iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) {
  22573. if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) {
  22574. return MA_TRUE;
  22575. }
  22576. }
  22577. return MA_FALSE;
  22578. }
  22579. static ma_bool32 ma_is_device_blacklisted__alsa(ma_device_type deviceType, const char* name)
  22580. {
  22581. if (deviceType == ma_device_type_playback) {
  22582. return ma_is_playback_device_blacklisted__alsa(name);
  22583. } else {
  22584. return ma_is_capture_device_blacklisted__alsa(name);
  22585. }
  22586. }
  22587. static const char* ma_find_char(const char* str, char c, int* index)
  22588. {
  22589. int i = 0;
  22590. for (;;) {
  22591. if (str[i] == '\0') {
  22592. if (index) *index = -1;
  22593. return NULL;
  22594. }
  22595. if (str[i] == c) {
  22596. if (index) *index = i;
  22597. return str + i;
  22598. }
  22599. i += 1;
  22600. }
  22601. /* Should never get here, but treat it as though the character was not found to make me feel better inside. */
  22602. if (index) *index = -1;
  22603. return NULL;
  22604. }
  22605. static ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid)
  22606. {
  22607. /* This function is just checking whether or not hwid is in "hw:%d,%d" format. */
  22608. int commaPos;
  22609. const char* dev;
  22610. int i;
  22611. if (hwid == NULL) {
  22612. return MA_FALSE;
  22613. }
  22614. if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') {
  22615. return MA_FALSE;
  22616. }
  22617. hwid += 3;
  22618. dev = ma_find_char(hwid, ',', &commaPos);
  22619. if (dev == NULL) {
  22620. return MA_FALSE;
  22621. } else {
  22622. dev += 1; /* Skip past the ",". */
  22623. }
  22624. /* Check if the part between the ":" and the "," contains only numbers. If not, return false. */
  22625. for (i = 0; i < commaPos; ++i) {
  22626. if (hwid[i] < '0' || hwid[i] > '9') {
  22627. return MA_FALSE;
  22628. }
  22629. }
  22630. /* Check if everything after the "," is numeric. If not, return false. */
  22631. i = 0;
  22632. while (dev[i] != '\0') {
  22633. if (dev[i] < '0' || dev[i] > '9') {
  22634. return MA_FALSE;
  22635. }
  22636. i += 1;
  22637. }
  22638. return MA_TRUE;
  22639. }
  22640. 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. */
  22641. {
  22642. /* src should look something like this: "hw:CARD=I82801AAICH,DEV=0" */
  22643. int colonPos;
  22644. int commaPos;
  22645. char card[256];
  22646. const char* dev;
  22647. int cardIndex;
  22648. if (dst == NULL) {
  22649. return -1;
  22650. }
  22651. if (dstSize < 7) {
  22652. return -1; /* Absolute minimum size of the output buffer is 7 bytes. */
  22653. }
  22654. *dst = '\0'; /* Safety. */
  22655. if (src == NULL) {
  22656. return -1;
  22657. }
  22658. /* If the input name is already in "hw:%d,%d" format, just return that verbatim. */
  22659. if (ma_is_device_name_in_hw_format__alsa(src)) {
  22660. return ma_strcpy_s(dst, dstSize, src);
  22661. }
  22662. src = ma_find_char(src, ':', &colonPos);
  22663. if (src == NULL) {
  22664. return -1; /* Couldn't find a colon */
  22665. }
  22666. dev = ma_find_char(src, ',', &commaPos);
  22667. if (dev == NULL) {
  22668. dev = "0";
  22669. ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); /* +6 = ":CARD=" */
  22670. } else {
  22671. dev = dev + 5; /* +5 = ",DEV=" */
  22672. ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); /* +6 = ":CARD=" */
  22673. }
  22674. cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card);
  22675. if (cardIndex < 0) {
  22676. return -2; /* Failed to retrieve the card index. */
  22677. }
  22678. /* Construction. */
  22679. dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':';
  22680. if (ma_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) {
  22681. return -3;
  22682. }
  22683. if (ma_strcat_s(dst, dstSize, ",") != 0) {
  22684. return -3;
  22685. }
  22686. if (ma_strcat_s(dst, dstSize, dev) != 0) {
  22687. return -3;
  22688. }
  22689. return 0;
  22690. }
  22691. static ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 count, const char* pHWID)
  22692. {
  22693. ma_uint32 i;
  22694. MA_ASSERT(pHWID != NULL);
  22695. for (i = 0; i < count; ++i) {
  22696. if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) {
  22697. return MA_TRUE;
  22698. }
  22699. }
  22700. return MA_FALSE;
  22701. }
  22702. 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)
  22703. {
  22704. ma_snd_pcm_t* pPCM;
  22705. ma_snd_pcm_stream_t stream;
  22706. MA_ASSERT(pContext != NULL);
  22707. MA_ASSERT(ppPCM != NULL);
  22708. *ppPCM = NULL;
  22709. pPCM = NULL;
  22710. stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE;
  22711. if (pDeviceID == NULL) {
  22712. ma_bool32 isDeviceOpen;
  22713. size_t i;
  22714. /*
  22715. We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes
  22716. me feel better to try as hard as we can get to get _something_ working.
  22717. */
  22718. const char* defaultDeviceNames[] = {
  22719. "default",
  22720. NULL,
  22721. NULL,
  22722. NULL,
  22723. NULL,
  22724. NULL,
  22725. NULL
  22726. };
  22727. if (shareMode == ma_share_mode_exclusive) {
  22728. defaultDeviceNames[1] = "hw";
  22729. defaultDeviceNames[2] = "hw:0";
  22730. defaultDeviceNames[3] = "hw:0,0";
  22731. } else {
  22732. if (deviceType == ma_device_type_playback) {
  22733. defaultDeviceNames[1] = "dmix";
  22734. defaultDeviceNames[2] = "dmix:0";
  22735. defaultDeviceNames[3] = "dmix:0,0";
  22736. } else {
  22737. defaultDeviceNames[1] = "dsnoop";
  22738. defaultDeviceNames[2] = "dsnoop:0";
  22739. defaultDeviceNames[3] = "dsnoop:0,0";
  22740. }
  22741. defaultDeviceNames[4] = "hw";
  22742. defaultDeviceNames[5] = "hw:0";
  22743. defaultDeviceNames[6] = "hw:0,0";
  22744. }
  22745. isDeviceOpen = MA_FALSE;
  22746. for (i = 0; i < ma_countof(defaultDeviceNames); ++i) {
  22747. if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') {
  22748. if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) {
  22749. isDeviceOpen = MA_TRUE;
  22750. break;
  22751. }
  22752. }
  22753. }
  22754. if (!isDeviceOpen) {
  22755. 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.");
  22756. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  22757. }
  22758. } else {
  22759. /*
  22760. We're trying to open a specific device. There's a few things to consider here:
  22761. 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
  22762. an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it
  22763. 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").
  22764. */
  22765. /* May end up needing to make small adjustments to the ID, so make a copy. */
  22766. ma_device_id deviceID = *pDeviceID;
  22767. int resultALSA = -ENODEV;
  22768. if (deviceID.alsa[0] != ':') {
  22769. /* The ID is not in ":0,0" format. Use the ID exactly as-is. */
  22770. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode);
  22771. } else {
  22772. char hwid[256];
  22773. /* The ID is in ":0,0" format. Try different plugins depending on the shared mode. */
  22774. if (deviceID.alsa[1] == '\0') {
  22775. deviceID.alsa[0] = '\0'; /* An ID of ":" should be converted to "". */
  22776. }
  22777. if (shareMode == ma_share_mode_shared) {
  22778. if (deviceType == ma_device_type_playback) {
  22779. ma_strcpy_s(hwid, sizeof(hwid), "dmix");
  22780. } else {
  22781. ma_strcpy_s(hwid, sizeof(hwid), "dsnoop");
  22782. }
  22783. if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
  22784. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
  22785. }
  22786. }
  22787. /* 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. */
  22788. if (resultALSA != 0) {
  22789. ma_strcpy_s(hwid, sizeof(hwid), "hw");
  22790. if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
  22791. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
  22792. }
  22793. }
  22794. }
  22795. if (resultALSA < 0) {
  22796. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed.");
  22797. return ma_result_from_errno(-resultALSA);
  22798. }
  22799. }
  22800. *ppPCM = pPCM;
  22801. return MA_SUCCESS;
  22802. }
  22803. static ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  22804. {
  22805. int resultALSA;
  22806. ma_bool32 cbResult = MA_TRUE;
  22807. char** ppDeviceHints;
  22808. ma_device_id* pUniqueIDs = NULL;
  22809. ma_uint32 uniqueIDCount = 0;
  22810. char** ppNextDeviceHint;
  22811. MA_ASSERT(pContext != NULL);
  22812. MA_ASSERT(callback != NULL);
  22813. ma_mutex_lock(&pContext->alsa.internalDeviceEnumLock);
  22814. resultALSA = ((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints);
  22815. if (resultALSA < 0) {
  22816. ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
  22817. return ma_result_from_errno(-resultALSA);
  22818. }
  22819. ppNextDeviceHint = ppDeviceHints;
  22820. while (*ppNextDeviceHint != NULL) {
  22821. char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME");
  22822. char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC");
  22823. char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID");
  22824. ma_device_type deviceType = ma_device_type_playback;
  22825. ma_bool32 stopEnumeration = MA_FALSE;
  22826. char hwid[sizeof(pUniqueIDs->alsa)];
  22827. ma_device_info deviceInfo;
  22828. if ((IOID == NULL || ma_strcmp(IOID, "Output") == 0)) {
  22829. deviceType = ma_device_type_playback;
  22830. }
  22831. if ((IOID != NULL && ma_strcmp(IOID, "Input" ) == 0)) {
  22832. deviceType = ma_device_type_capture;
  22833. }
  22834. if (NAME != NULL) {
  22835. if (pContext->alsa.useVerboseDeviceEnumeration) {
  22836. /* Verbose mode. Use the name exactly as-is. */
  22837. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
  22838. } else {
  22839. /* Simplified mode. Use ":%d,%d" format. */
  22840. if (ma_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) {
  22841. /*
  22842. At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the
  22843. plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device
  22844. initialization time and is used as an indicator to try and use the most appropriate plugin depending on the
  22845. device type and sharing mode.
  22846. */
  22847. char* dst = hwid;
  22848. char* src = hwid+2;
  22849. while ((*dst++ = *src++));
  22850. } else {
  22851. /* Conversion to "hw:%d,%d" failed. Just use the name as-is. */
  22852. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
  22853. }
  22854. if (ma_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) {
  22855. goto next_device; /* The device has already been enumerated. Move on to the next one. */
  22856. } else {
  22857. /* The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. */
  22858. size_t newCapacity = sizeof(*pUniqueIDs) * (uniqueIDCount + 1);
  22859. ma_device_id* pNewUniqueIDs = (ma_device_id*)ma_realloc(pUniqueIDs, newCapacity, &pContext->allocationCallbacks);
  22860. if (pNewUniqueIDs == NULL) {
  22861. goto next_device; /* Failed to allocate memory. */
  22862. }
  22863. pUniqueIDs = pNewUniqueIDs;
  22864. MA_COPY_MEMORY(pUniqueIDs[uniqueIDCount].alsa, hwid, sizeof(hwid));
  22865. uniqueIDCount += 1;
  22866. }
  22867. }
  22868. } else {
  22869. MA_ZERO_MEMORY(hwid, sizeof(hwid));
  22870. }
  22871. MA_ZERO_OBJECT(&deviceInfo);
  22872. ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1);
  22873. /*
  22874. 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
  22875. just use the name of "default" as the indicator.
  22876. */
  22877. if (ma_strcmp(deviceInfo.id.alsa, "default") == 0) {
  22878. deviceInfo.isDefault = MA_TRUE;
  22879. }
  22880. /*
  22881. DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose
  22882. device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish
  22883. between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the
  22884. description.
  22885. The value in DESC seems to be split into two lines, with the first line being the name of the device and the
  22886. second line being a description of the device. I don't like having the description be across two lines because
  22887. it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line
  22888. being put into parentheses. In simplified mode I'm just stripping the second line entirely.
  22889. */
  22890. if (DESC != NULL) {
  22891. int lfPos;
  22892. const char* line2 = ma_find_char(DESC, '\n', &lfPos);
  22893. if (line2 != NULL) {
  22894. line2 += 1; /* Skip past the new-line character. */
  22895. if (pContext->alsa.useVerboseDeviceEnumeration) {
  22896. /* Verbose mode. Put the second line in brackets. */
  22897. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
  22898. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " (");
  22899. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2);
  22900. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")");
  22901. } else {
  22902. /* Simplified mode. Strip the second line entirely. */
  22903. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
  22904. }
  22905. } else {
  22906. /* There's no second line. Just copy the whole description. */
  22907. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1);
  22908. }
  22909. }
  22910. if (!ma_is_device_blacklisted__alsa(deviceType, NAME)) {
  22911. cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
  22912. }
  22913. /*
  22914. Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback
  22915. again for the other device type in this case. We do this for known devices and where the IOID hint is NULL, which
  22916. means both Input and Output.
  22917. */
  22918. if (cbResult) {
  22919. if (ma_is_common_device_name__alsa(NAME) || IOID == NULL) {
  22920. if (deviceType == ma_device_type_playback) {
  22921. if (!ma_is_capture_device_blacklisted__alsa(NAME)) {
  22922. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  22923. }
  22924. } else {
  22925. if (!ma_is_playback_device_blacklisted__alsa(NAME)) {
  22926. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  22927. }
  22928. }
  22929. }
  22930. }
  22931. if (cbResult == MA_FALSE) {
  22932. stopEnumeration = MA_TRUE;
  22933. }
  22934. next_device:
  22935. free(NAME);
  22936. free(DESC);
  22937. free(IOID);
  22938. ppNextDeviceHint += 1;
  22939. /* We need to stop enumeration if the callback returned false. */
  22940. if (stopEnumeration) {
  22941. break;
  22942. }
  22943. }
  22944. ma_free(pUniqueIDs, &pContext->allocationCallbacks);
  22945. ((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints);
  22946. ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
  22947. return MA_SUCCESS;
  22948. }
  22949. typedef struct
  22950. {
  22951. ma_device_type deviceType;
  22952. const ma_device_id* pDeviceID;
  22953. ma_share_mode shareMode;
  22954. ma_device_info* pDeviceInfo;
  22955. ma_bool32 foundDevice;
  22956. } ma_context_get_device_info_enum_callback_data__alsa;
  22957. 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)
  22958. {
  22959. ma_context_get_device_info_enum_callback_data__alsa* pData = (ma_context_get_device_info_enum_callback_data__alsa*)pUserData;
  22960. MA_ASSERT(pData != NULL);
  22961. (void)pContext;
  22962. if (pData->pDeviceID == NULL && ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
  22963. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
  22964. pData->foundDevice = MA_TRUE;
  22965. } else {
  22966. if (pData->deviceType == deviceType && (pData->pDeviceID != NULL && ma_strcmp(pData->pDeviceID->alsa, pDeviceInfo->id.alsa) == 0)) {
  22967. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
  22968. pData->foundDevice = MA_TRUE;
  22969. }
  22970. }
  22971. /* Keep enumerating until we have found the device. */
  22972. return !pData->foundDevice;
  22973. }
  22974. 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)
  22975. {
  22976. MA_ASSERT(pPCM != NULL);
  22977. MA_ASSERT(pHWParams != NULL);
  22978. MA_ASSERT(pDeviceInfo != NULL);
  22979. 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) {
  22980. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  22981. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  22982. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  22983. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  22984. pDeviceInfo->nativeDataFormatCount += 1;
  22985. }
  22986. }
  22987. 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)
  22988. {
  22989. ma_uint32 iSampleRate;
  22990. unsigned int minSampleRate;
  22991. unsigned int maxSampleRate;
  22992. int sampleRateDir; /* Not used. Just passed into snd_pcm_hw_params_get_rate_min/max(). */
  22993. /* There could be a range. */
  22994. ((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &minSampleRate, &sampleRateDir);
  22995. ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &maxSampleRate, &sampleRateDir);
  22996. /* Make sure our sample rates are clamped to sane values. Stupid devices like "pulse" will reports rates like "1" which is ridiculus. */
  22997. minSampleRate = ma_clamp(minSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max);
  22998. maxSampleRate = ma_clamp(maxSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max);
  22999. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) {
  23000. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate];
  23001. if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) {
  23002. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, standardSampleRate, flags, pDeviceInfo);
  23003. }
  23004. }
  23005. /* Now make sure our min and max rates are included just in case they aren't in the range of our standard rates. */
  23006. if (!ma_is_standard_sample_rate(minSampleRate)) {
  23007. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, minSampleRate, flags, pDeviceInfo);
  23008. }
  23009. if (!ma_is_standard_sample_rate(maxSampleRate) && maxSampleRate != minSampleRate) {
  23010. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, maxSampleRate, flags, pDeviceInfo);
  23011. }
  23012. }
  23013. 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)
  23014. {
  23015. ma_context_get_device_info_enum_callback_data__alsa data;
  23016. ma_result result;
  23017. int resultALSA;
  23018. ma_snd_pcm_t* pPCM;
  23019. ma_snd_pcm_hw_params_t* pHWParams;
  23020. ma_uint32 iFormat;
  23021. ma_uint32 iChannel;
  23022. MA_ASSERT(pContext != NULL);
  23023. /* We just enumerate to find basic information about the device. */
  23024. data.deviceType = deviceType;
  23025. data.pDeviceID = pDeviceID;
  23026. data.pDeviceInfo = pDeviceInfo;
  23027. data.foundDevice = MA_FALSE;
  23028. result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data);
  23029. if (result != MA_SUCCESS) {
  23030. return result;
  23031. }
  23032. if (!data.foundDevice) {
  23033. return MA_NO_DEVICE;
  23034. }
  23035. if (ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
  23036. pDeviceInfo->isDefault = MA_TRUE;
  23037. }
  23038. /* For detailed info we need to open the device. */
  23039. result = ma_context_open_pcm__alsa(pContext, ma_share_mode_shared, deviceType, pDeviceID, 0, &pPCM);
  23040. if (result != MA_SUCCESS) {
  23041. return result;
  23042. }
  23043. /* We need to initialize a HW parameters object in order to know what formats are supported. */
  23044. 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);
  23045. if (pHWParams == NULL) {
  23046. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  23047. return MA_OUT_OF_MEMORY;
  23048. }
  23049. resultALSA = ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23050. if (resultALSA < 0) {
  23051. ma_free(pHWParams, &pContext->allocationCallbacks);
  23052. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  23053. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.");
  23054. return ma_result_from_errno(-resultALSA);
  23055. }
  23056. /*
  23057. Some ALSA devices can support many permutations of formats, channels and rates. We only support
  23058. a fixed number of permutations which means we need to employ some strategies to ensure the best
  23059. combinations are returned. An example is the "pulse" device which can do it's own data conversion
  23060. in software and as a result can support any combination of format, channels and rate.
  23061. We want to ensure the the first data formats are the best. We have a list of favored sample
  23062. formats and sample rates, so these will be the basis of our iteration.
  23063. */
  23064. /* Formats. We just iterate over our standard formats and test them, making sure we reset the configuration space each iteration. */
  23065. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) {
  23066. ma_format format = g_maFormatPriorities[iFormat];
  23067. /*
  23068. For each format we need to make sure we reset the configuration space so we don't return
  23069. channel counts and rates that aren't compatible with a format.
  23070. */
  23071. ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23072. /* Test the format first. If this fails it means the format is not supported and we can skip it. */
  23073. 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) {
  23074. /* The format is supported. */
  23075. unsigned int minChannels;
  23076. unsigned int maxChannels;
  23077. /*
  23078. The configuration space needs to be restricted to this format so we can get an accurate
  23079. picture of which sample rates and channel counts are support with this format.
  23080. */
  23081. ((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));
  23082. /* Now we need to check for supported channels. */
  23083. ((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &minChannels);
  23084. ((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &maxChannels);
  23085. if (minChannels > MA_MAX_CHANNELS) {
  23086. continue; /* Too many channels. */
  23087. }
  23088. if (maxChannels < MA_MIN_CHANNELS) {
  23089. continue; /* Not enough channels. */
  23090. }
  23091. /*
  23092. Make sure the channel count is clamped. This is mainly intended for the max channels
  23093. because some devices can report an unbound maximum.
  23094. */
  23095. minChannels = ma_clamp(minChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  23096. maxChannels = ma_clamp(maxChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  23097. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  23098. /* 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. */
  23099. 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. */
  23100. } else {
  23101. /* The device only supports a specific set of channels. We need to iterate over all of them. */
  23102. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  23103. /* Test the channel before applying it to the configuration space. */
  23104. unsigned int channels = iChannel;
  23105. /* Make sure our channel range is reset before testing again or else we'll always fail the test. */
  23106. ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23107. ((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));
  23108. if (((ma_snd_pcm_hw_params_test_channels_proc)pContext->alsa.snd_pcm_hw_params_test_channels)(pPCM, pHWParams, channels) == 0) {
  23109. /* The channel count is supported. */
  23110. /* The configuration space now needs to be restricted to the channel count before extracting the sample rate. */
  23111. ((ma_snd_pcm_hw_params_set_channels_proc)pContext->alsa.snd_pcm_hw_params_set_channels)(pPCM, pHWParams, channels);
  23112. /* Only after the configuration space has been restricted to the specific channel count should we iterate over our sample rates. */
  23113. ma_context_iterate_rates_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, 0, pDeviceInfo);
  23114. } else {
  23115. /* The channel count is not supported. Skip. */
  23116. }
  23117. }
  23118. }
  23119. } else {
  23120. /* The format is not supported. Skip. */
  23121. }
  23122. }
  23123. ma_free(pHWParams, &pContext->allocationCallbacks);
  23124. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  23125. return MA_SUCCESS;
  23126. }
  23127. static ma_result ma_device_uninit__alsa(ma_device* pDevice)
  23128. {
  23129. MA_ASSERT(pDevice != NULL);
  23130. if ((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) {
  23131. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23132. close(pDevice->alsa.wakeupfdCapture);
  23133. ma_free(pDevice->alsa.pPollDescriptorsCapture, &pDevice->pContext->allocationCallbacks);
  23134. }
  23135. if ((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) {
  23136. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  23137. close(pDevice->alsa.wakeupfdPlayback);
  23138. ma_free(pDevice->alsa.pPollDescriptorsPlayback, &pDevice->pContext->allocationCallbacks);
  23139. }
  23140. return MA_SUCCESS;
  23141. }
  23142. 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)
  23143. {
  23144. ma_result result;
  23145. int resultALSA;
  23146. ma_snd_pcm_t* pPCM;
  23147. ma_bool32 isUsingMMap;
  23148. ma_snd_pcm_format_t formatALSA;
  23149. ma_format internalFormat;
  23150. ma_uint32 internalChannels;
  23151. ma_uint32 internalSampleRate;
  23152. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  23153. ma_uint32 internalPeriodSizeInFrames;
  23154. ma_uint32 internalPeriods;
  23155. int openMode;
  23156. ma_snd_pcm_hw_params_t* pHWParams;
  23157. ma_snd_pcm_sw_params_t* pSWParams;
  23158. ma_snd_pcm_uframes_t bufferBoundary;
  23159. int pollDescriptorCount;
  23160. struct pollfd* pPollDescriptors;
  23161. int wakeupfd;
  23162. MA_ASSERT(pConfig != NULL);
  23163. MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should only be called for playback _or_ capture, never duplex. */
  23164. MA_ASSERT(pDevice != NULL);
  23165. formatALSA = ma_convert_ma_format_to_alsa_format(pDescriptor->format);
  23166. openMode = 0;
  23167. if (pConfig->alsa.noAutoResample) {
  23168. openMode |= MA_SND_PCM_NO_AUTO_RESAMPLE;
  23169. }
  23170. if (pConfig->alsa.noAutoChannels) {
  23171. openMode |= MA_SND_PCM_NO_AUTO_CHANNELS;
  23172. }
  23173. if (pConfig->alsa.noAutoFormat) {
  23174. openMode |= MA_SND_PCM_NO_AUTO_FORMAT;
  23175. }
  23176. result = ma_context_open_pcm__alsa(pDevice->pContext, pDescriptor->shareMode, deviceType, pDescriptor->pDeviceID, openMode, &pPCM);
  23177. if (result != MA_SUCCESS) {
  23178. return result;
  23179. }
  23180. /* Hardware parameters. */
  23181. 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);
  23182. if (pHWParams == NULL) {
  23183. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23184. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for hardware parameters.");
  23185. return MA_OUT_OF_MEMORY;
  23186. }
  23187. resultALSA = ((ma_snd_pcm_hw_params_any_proc)pDevice->pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  23188. if (resultALSA < 0) {
  23189. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23190. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23191. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.");
  23192. return ma_result_from_errno(-resultALSA);
  23193. }
  23194. /* MMAP Mode. Try using interleaved MMAP access. If this fails, fall back to standard readi/writei. */
  23195. isUsingMMap = MA_FALSE;
  23196. #if 0 /* NOTE: MMAP mode temporarily disabled. */
  23197. 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. */
  23198. if (!pConfig->alsa.noMMap) {
  23199. 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) {
  23200. pDevice->alsa.isUsingMMap = MA_TRUE;
  23201. }
  23202. }
  23203. }
  23204. #endif
  23205. if (!isUsingMMap) {
  23206. 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);
  23207. if (resultALSA < 0) {
  23208. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23209. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23210. 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.");
  23211. return ma_result_from_errno(-resultALSA);
  23212. }
  23213. }
  23214. /*
  23215. Most important properties first. The documentation for OSS (yes, I know this is ALSA!) recommends format, channels, then sample rate. I can't
  23216. find any documentation for ALSA specifically, so I'm going to copy the recommendation for OSS.
  23217. */
  23218. /* Format. */
  23219. {
  23220. /*
  23221. 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
  23222. 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.
  23223. */
  23224. 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) {
  23225. /* We're either requesting the native format or the specified format is not supported. */
  23226. size_t iFormat;
  23227. formatALSA = MA_SND_PCM_FORMAT_UNKNOWN;
  23228. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) {
  23229. 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) {
  23230. formatALSA = ma_convert_ma_format_to_alsa_format(g_maFormatPriorities[iFormat]);
  23231. break;
  23232. }
  23233. }
  23234. if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) {
  23235. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23236. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23237. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats.");
  23238. return MA_FORMAT_NOT_SUPPORTED;
  23239. }
  23240. }
  23241. resultALSA = ((ma_snd_pcm_hw_params_set_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA);
  23242. if (resultALSA < 0) {
  23243. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23244. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23245. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.");
  23246. return ma_result_from_errno(-resultALSA);
  23247. }
  23248. internalFormat = ma_format_from_alsa(formatALSA);
  23249. if (internalFormat == ma_format_unknown) {
  23250. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23251. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23252. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio.");
  23253. return MA_FORMAT_NOT_SUPPORTED;
  23254. }
  23255. }
  23256. /* Channels. */
  23257. {
  23258. unsigned int channels = pDescriptor->channels;
  23259. if (channels == 0) {
  23260. channels = MA_DEFAULT_CHANNELS;
  23261. }
  23262. resultALSA = ((ma_snd_pcm_hw_params_set_channels_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels);
  23263. if (resultALSA < 0) {
  23264. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23265. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23266. 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.");
  23267. return ma_result_from_errno(-resultALSA);
  23268. }
  23269. internalChannels = (ma_uint32)channels;
  23270. }
  23271. /* Sample Rate */
  23272. {
  23273. unsigned int sampleRate;
  23274. /*
  23275. 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
  23276. problems with some device configurations when used in conjunction with MMAP access mode. To fix this problem we need to disable
  23277. resampling.
  23278. To reproduce this problem, open the "plug:dmix" device, and set the sample rate to 44100. Internally, it looks like dmix uses a
  23279. sample rate of 48000. The hardware parameters will get set correctly with no errors, but it looks like the 44100 -> 48000 resampling
  23280. 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
  23281. faster rate.
  23282. miniaudio has built-in support for sample rate conversion (albeit low quality at the moment), so disabling resampling should be fine
  23283. 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
  23284. good quality until I get a chance to improve the quality of miniaudio's software sample rate conversion.
  23285. 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
  23286. this error with. In the future, we may want to restrict the disabling of resampling to only known bad plugins.
  23287. */
  23288. ((ma_snd_pcm_hw_params_set_rate_resample_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_resample)(pPCM, pHWParams, 0);
  23289. sampleRate = pDescriptor->sampleRate;
  23290. if (sampleRate == 0) {
  23291. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  23292. }
  23293. resultALSA = ((ma_snd_pcm_hw_params_set_rate_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0);
  23294. if (resultALSA < 0) {
  23295. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23296. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23297. 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.");
  23298. return ma_result_from_errno(-resultALSA);
  23299. }
  23300. internalSampleRate = (ma_uint32)sampleRate;
  23301. }
  23302. /* Periods. */
  23303. {
  23304. ma_uint32 periods = pDescriptor->periodCount;
  23305. resultALSA = ((ma_snd_pcm_hw_params_set_periods_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL);
  23306. if (resultALSA < 0) {
  23307. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23308. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23309. 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.");
  23310. return ma_result_from_errno(-resultALSA);
  23311. }
  23312. internalPeriods = periods;
  23313. }
  23314. /* Buffer Size */
  23315. {
  23316. ma_snd_pcm_uframes_t actualBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile) * internalPeriods;
  23317. 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);
  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 buffer size for device. snd_pcm_hw_params_set_buffer_size() failed.");
  23322. return ma_result_from_errno(-resultALSA);
  23323. }
  23324. internalPeriodSizeInFrames = actualBufferSizeInFrames / internalPeriods;
  23325. }
  23326. /* Apply hardware parameters. */
  23327. resultALSA = ((ma_snd_pcm_hw_params_proc)pDevice->pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams);
  23328. if (resultALSA < 0) {
  23329. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23330. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23331. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.");
  23332. return ma_result_from_errno(-resultALSA);
  23333. }
  23334. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  23335. pHWParams = NULL;
  23336. /* Software parameters. */
  23337. 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);
  23338. if (pSWParams == NULL) {
  23339. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23340. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for software parameters.");
  23341. return MA_OUT_OF_MEMORY;
  23342. }
  23343. resultALSA = ((ma_snd_pcm_sw_params_current_proc)pDevice->pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams);
  23344. if (resultALSA < 0) {
  23345. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23346. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23347. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.");
  23348. return ma_result_from_errno(-resultALSA);
  23349. }
  23350. 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));
  23351. if (resultALSA < 0) {
  23352. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23353. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23354. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.");
  23355. return ma_result_from_errno(-resultALSA);
  23356. }
  23357. resultALSA = ((ma_snd_pcm_sw_params_get_boundary_proc)pDevice->pContext->alsa.snd_pcm_sw_params_get_boundary)(pSWParams, &bufferBoundary);
  23358. if (resultALSA < 0) {
  23359. bufferBoundary = internalPeriodSizeInFrames * internalPeriods;
  23360. }
  23361. if (deviceType == ma_device_type_playback && !isUsingMMap) { /* Only playback devices in writei/readi mode need a start threshold. */
  23362. /*
  23363. Subtle detail here with the start threshold. When in playback-only mode (no full-duplex) we can set the start threshold to
  23364. the size of a period. But for full-duplex we need to set it such that it is at least two periods.
  23365. */
  23366. resultALSA = ((ma_snd_pcm_sw_params_set_start_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalPeriodSizeInFrames*2);
  23367. if (resultALSA < 0) {
  23368. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23369. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23370. 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.");
  23371. return ma_result_from_errno(-resultALSA);
  23372. }
  23373. resultALSA = ((ma_snd_pcm_sw_params_set_stop_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary);
  23374. if (resultALSA < 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */
  23375. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23376. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23377. 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.");
  23378. return ma_result_from_errno(-resultALSA);
  23379. }
  23380. }
  23381. resultALSA = ((ma_snd_pcm_sw_params_proc)pDevice->pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams);
  23382. if (resultALSA < 0) {
  23383. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23384. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23385. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.");
  23386. return ma_result_from_errno(-resultALSA);
  23387. }
  23388. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  23389. pSWParams = NULL;
  23390. /* 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. */
  23391. {
  23392. ma_snd_pcm_chmap_t* pChmap = NULL;
  23393. if (pDevice->pContext->alsa.snd_pcm_get_chmap != NULL) {
  23394. pChmap = ((ma_snd_pcm_get_chmap_proc)pDevice->pContext->alsa.snd_pcm_get_chmap)(pPCM);
  23395. }
  23396. if (pChmap != NULL) {
  23397. ma_uint32 iChannel;
  23398. /* 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(). */
  23399. if (pChmap->channels >= internalChannels) {
  23400. /* Drop excess channels. */
  23401. for (iChannel = 0; iChannel < internalChannels; ++iChannel) {
  23402. internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
  23403. }
  23404. } else {
  23405. ma_uint32 i;
  23406. /*
  23407. Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate
  23408. channels. If validation fails, fall back to defaults.
  23409. */
  23410. ma_bool32 isValid = MA_TRUE;
  23411. /* Fill with defaults. */
  23412. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  23413. /* Overwrite first pChmap->channels channels. */
  23414. for (iChannel = 0; iChannel < pChmap->channels; ++iChannel) {
  23415. internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
  23416. }
  23417. /* Validate. */
  23418. for (i = 0; i < internalChannels && isValid; ++i) {
  23419. ma_uint32 j;
  23420. for (j = i+1; j < internalChannels; ++j) {
  23421. if (internalChannelMap[i] == internalChannelMap[j]) {
  23422. isValid = MA_FALSE;
  23423. break;
  23424. }
  23425. }
  23426. }
  23427. /* If our channel map is invalid, fall back to defaults. */
  23428. if (!isValid) {
  23429. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  23430. }
  23431. }
  23432. free(pChmap);
  23433. pChmap = NULL;
  23434. } else {
  23435. /* Could not retrieve the channel map. Fall back to a hard-coded assumption. */
  23436. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  23437. }
  23438. }
  23439. /*
  23440. We need to retrieve the poll descriptors so we can use poll() to wait for data to become
  23441. available for reading or writing. There's no well defined maximum for this so we're just going
  23442. to allocate this on the heap.
  23443. */
  23444. pollDescriptorCount = ((ma_snd_pcm_poll_descriptors_count_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors_count)(pPCM);
  23445. if (pollDescriptorCount <= 0) {
  23446. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23447. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors count.");
  23448. return MA_ERROR;
  23449. }
  23450. pPollDescriptors = (struct pollfd*)ma_malloc(sizeof(*pPollDescriptors) * (pollDescriptorCount + 1), &pDevice->pContext->allocationCallbacks); /* +1 because we want room for the wakeup descriptor. */
  23451. if (pPollDescriptors == NULL) {
  23452. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23453. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for poll descriptors.");
  23454. return MA_OUT_OF_MEMORY;
  23455. }
  23456. /*
  23457. We need an eventfd to wakeup from poll() and avoid a deadlock in situations where the driver
  23458. never returns from writei() and readi(). This has been observed with the "pulse" device.
  23459. */
  23460. wakeupfd = eventfd(0, 0);
  23461. if (wakeupfd < 0) {
  23462. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  23463. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23464. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to create eventfd for poll wakeup.");
  23465. return ma_result_from_errno(errno);
  23466. }
  23467. /* We'll place the wakeup fd at the start of the buffer. */
  23468. pPollDescriptors[0].fd = wakeupfd;
  23469. pPollDescriptors[0].events = POLLIN; /* We only care about waiting to read from the wakeup file descriptor. */
  23470. pPollDescriptors[0].revents = 0;
  23471. /* We can now extract the PCM poll descriptors which we place after the wakeup descriptor. */
  23472. 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. */
  23473. if (pollDescriptorCount <= 0) {
  23474. close(wakeupfd);
  23475. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  23476. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23477. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors.");
  23478. return MA_ERROR;
  23479. }
  23480. if (deviceType == ma_device_type_capture) {
  23481. pDevice->alsa.pollDescriptorCountCapture = pollDescriptorCount;
  23482. pDevice->alsa.pPollDescriptorsCapture = pPollDescriptors;
  23483. pDevice->alsa.wakeupfdCapture = wakeupfd;
  23484. } else {
  23485. pDevice->alsa.pollDescriptorCountPlayback = pollDescriptorCount;
  23486. pDevice->alsa.pPollDescriptorsPlayback = pPollDescriptors;
  23487. pDevice->alsa.wakeupfdPlayback = wakeupfd;
  23488. }
  23489. /* We're done. Prepare the device. */
  23490. resultALSA = ((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)(pPCM);
  23491. if (resultALSA < 0) {
  23492. close(wakeupfd);
  23493. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  23494. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  23495. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.");
  23496. return ma_result_from_errno(-resultALSA);
  23497. }
  23498. if (deviceType == ma_device_type_capture) {
  23499. pDevice->alsa.pPCMCapture = (ma_ptr)pPCM;
  23500. pDevice->alsa.isUsingMMapCapture = isUsingMMap;
  23501. } else {
  23502. pDevice->alsa.pPCMPlayback = (ma_ptr)pPCM;
  23503. pDevice->alsa.isUsingMMapPlayback = isUsingMMap;
  23504. }
  23505. pDescriptor->format = internalFormat;
  23506. pDescriptor->channels = internalChannels;
  23507. pDescriptor->sampleRate = internalSampleRate;
  23508. ma_channel_map_copy(pDescriptor->channelMap, internalChannelMap, ma_min(internalChannels, MA_MAX_CHANNELS));
  23509. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  23510. pDescriptor->periodCount = internalPeriods;
  23511. return MA_SUCCESS;
  23512. }
  23513. static ma_result ma_device_init__alsa(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  23514. {
  23515. MA_ASSERT(pDevice != NULL);
  23516. MA_ZERO_OBJECT(&pDevice->alsa);
  23517. if (pConfig->deviceType == ma_device_type_loopback) {
  23518. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  23519. }
  23520. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  23521. ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  23522. if (result != MA_SUCCESS) {
  23523. return result;
  23524. }
  23525. }
  23526. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  23527. ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  23528. if (result != MA_SUCCESS) {
  23529. return result;
  23530. }
  23531. }
  23532. return MA_SUCCESS;
  23533. }
  23534. static ma_result ma_device_start__alsa(ma_device* pDevice)
  23535. {
  23536. int resultALSA;
  23537. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  23538. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23539. if (resultALSA < 0) {
  23540. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.");
  23541. return ma_result_from_errno(-resultALSA);
  23542. }
  23543. }
  23544. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  23545. /* Don't need to do anything for playback because it'll be started automatically when enough data has been written. */
  23546. }
  23547. return MA_SUCCESS;
  23548. }
  23549. static ma_result ma_device_stop__alsa(ma_device* pDevice)
  23550. {
  23551. /*
  23552. The stop callback will get called on the worker thread after read/write__alsa() has returned. At this point there is
  23553. a small chance that our wakeupfd has not been cleared. We'll clear that out now if applicable.
  23554. */
  23555. int resultPoll;
  23556. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  23557. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device...\n");
  23558. ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23559. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device successful.\n");
  23560. /* We need to prepare the device again, otherwise we won't be able to restart the device. */
  23561. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device...\n");
  23562. if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) {
  23563. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device failed.\n");
  23564. } else {
  23565. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device successful.\n");
  23566. }
  23567. /* Clear the wakeupfd. */
  23568. resultPoll = poll((struct pollfd*)pDevice->alsa.pPollDescriptorsCapture, 1, 0);
  23569. if (resultPoll > 0) {
  23570. ma_uint64 t;
  23571. read(((struct pollfd*)pDevice->alsa.pPollDescriptorsCapture)[0].fd, &t, sizeof(t));
  23572. }
  23573. }
  23574. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  23575. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device...\n");
  23576. ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  23577. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device successful.\n");
  23578. /* We need to prepare the device again, otherwise we won't be able to restart the device. */
  23579. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device...\n");
  23580. if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) < 0) {
  23581. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device failed.\n");
  23582. } else {
  23583. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device successful.\n");
  23584. }
  23585. /* Clear the wakeupfd. */
  23586. resultPoll = poll((struct pollfd*)pDevice->alsa.pPollDescriptorsPlayback, 1, 0);
  23587. if (resultPoll > 0) {
  23588. ma_uint64 t;
  23589. read(((struct pollfd*)pDevice->alsa.pPollDescriptorsPlayback)[0].fd, &t, sizeof(t));
  23590. }
  23591. }
  23592. return MA_SUCCESS;
  23593. }
  23594. static ma_result ma_device_wait__alsa(ma_device* pDevice, ma_snd_pcm_t* pPCM, struct pollfd* pPollDescriptors, int pollDescriptorCount, short requiredEvent)
  23595. {
  23596. for (;;) {
  23597. unsigned short revents;
  23598. int resultALSA;
  23599. int resultPoll = poll(pPollDescriptors, pollDescriptorCount, -1);
  23600. if (resultPoll < 0) {
  23601. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] poll() failed.\n");
  23602. return ma_result_from_errno(errno);
  23603. }
  23604. /*
  23605. Before checking the ALSA poll descriptor flag we need to check if the wakeup descriptor
  23606. has had it's POLLIN flag set. If so, we need to actually read the data and then exit
  23607. function. The wakeup descriptor will be the first item in the descriptors buffer.
  23608. */
  23609. if ((pPollDescriptors[0].revents & POLLIN) != 0) {
  23610. ma_uint64 t;
  23611. int resultRead = read(pPollDescriptors[0].fd, &t, sizeof(t)); /* <-- Important that we read here so that the next write() does not block. */
  23612. if (resultRead < 0) {
  23613. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] read() failed.\n");
  23614. return ma_result_from_errno(errno);
  23615. }
  23616. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] POLLIN set for wakeupfd\n");
  23617. return MA_DEVICE_NOT_STARTED;
  23618. }
  23619. /*
  23620. Getting here means that some data should be able to be read. We need to use ALSA to
  23621. translate the revents flags for us.
  23622. */
  23623. 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. */
  23624. if (resultALSA < 0) {
  23625. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_poll_descriptors_revents() failed.\n");
  23626. return ma_result_from_errno(-resultALSA);
  23627. }
  23628. if ((revents & POLLERR) != 0) {
  23629. ma_snd_pcm_state_t state = ((ma_snd_pcm_state_proc)pDevice->pContext->alsa.snd_pcm_state)(pPCM);
  23630. if (state == MA_SND_PCM_STATE_XRUN) {
  23631. /* The PCM is in a xrun state. This will be recovered from at a higher level. We can disregard this. */
  23632. } else {
  23633. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[ALSA] POLLERR detected. status = %d\n", ((ma_snd_pcm_state_proc)pDevice->pContext->alsa.snd_pcm_state)(pPCM));
  23634. }
  23635. }
  23636. if ((revents & requiredEvent) == requiredEvent) {
  23637. break; /* We're done. Data available for reading or writing. */
  23638. }
  23639. }
  23640. return MA_SUCCESS;
  23641. }
  23642. static ma_result ma_device_wait_read__alsa(ma_device* pDevice)
  23643. {
  23644. 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. */
  23645. }
  23646. static ma_result ma_device_wait_write__alsa(ma_device* pDevice)
  23647. {
  23648. 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. */
  23649. }
  23650. static ma_result ma_device_read__alsa(ma_device* pDevice, void* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead)
  23651. {
  23652. ma_snd_pcm_sframes_t resultALSA = 0;
  23653. MA_ASSERT(pDevice != NULL);
  23654. MA_ASSERT(pFramesOut != NULL);
  23655. if (pFramesRead != NULL) {
  23656. *pFramesRead = 0;
  23657. }
  23658. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  23659. ma_result result;
  23660. /* 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. */
  23661. result = ma_device_wait_read__alsa(pDevice);
  23662. if (result != MA_SUCCESS) {
  23663. return result;
  23664. }
  23665. /* Getting here means we should have data available. */
  23666. resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pFramesOut, frameCount);
  23667. if (resultALSA >= 0) {
  23668. break; /* Success. */
  23669. } else {
  23670. if (resultALSA == -EAGAIN) {
  23671. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (read)\n");*/
  23672. continue; /* Try again. */
  23673. } else if (resultALSA == -EPIPE) {
  23674. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (read)\n");
  23675. /* Overrun. Recover and try again. If this fails we need to return an error. */
  23676. resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE);
  23677. if (resultALSA < 0) {
  23678. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.");
  23679. return ma_result_from_errno((int)-resultALSA);
  23680. }
  23681. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  23682. if (resultALSA < 0) {
  23683. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.");
  23684. return ma_result_from_errno((int)-resultALSA);
  23685. }
  23686. continue; /* Try reading again. */
  23687. }
  23688. }
  23689. }
  23690. if (pFramesRead != NULL) {
  23691. *pFramesRead = resultALSA;
  23692. }
  23693. return MA_SUCCESS;
  23694. }
  23695. static ma_result ma_device_write__alsa(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  23696. {
  23697. ma_snd_pcm_sframes_t resultALSA = 0;
  23698. MA_ASSERT(pDevice != NULL);
  23699. MA_ASSERT(pFrames != NULL);
  23700. if (pFramesWritten != NULL) {
  23701. *pFramesWritten = 0;
  23702. }
  23703. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  23704. ma_result result;
  23705. /* 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. */
  23706. result = ma_device_wait_write__alsa(pDevice);
  23707. if (result != MA_SUCCESS) {
  23708. return result;
  23709. }
  23710. resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pFrames, frameCount);
  23711. if (resultALSA >= 0) {
  23712. break; /* Success. */
  23713. } else {
  23714. if (resultALSA == -EAGAIN) {
  23715. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (write)\n");*/
  23716. continue; /* Try again. */
  23717. } else if (resultALSA == -EPIPE) {
  23718. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (write)\n");
  23719. /* Underrun. Recover and try again. If this fails we need to return an error. */
  23720. 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). */
  23721. if (resultALSA < 0) {
  23722. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.");
  23723. return ma_result_from_errno((int)-resultALSA);
  23724. }
  23725. /*
  23726. In my testing I have had a situation where writei() does not automatically restart the device even though I've set it
  23727. up as such in the software parameters. What will happen is writei() will block indefinitely even though the number of
  23728. frames is well beyond the auto-start threshold. To work around this I've needed to add an explicit start here. Not sure
  23729. if this is me just being stupid and not recovering the device properly, but this definitely feels like something isn't
  23730. quite right here.
  23731. */
  23732. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  23733. if (resultALSA < 0) {
  23734. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.");
  23735. return ma_result_from_errno((int)-resultALSA);
  23736. }
  23737. continue; /* Try writing again. */
  23738. }
  23739. }
  23740. }
  23741. if (pFramesWritten != NULL) {
  23742. *pFramesWritten = resultALSA;
  23743. }
  23744. return MA_SUCCESS;
  23745. }
  23746. static ma_result ma_device_data_loop_wakeup__alsa(ma_device* pDevice)
  23747. {
  23748. ma_uint64 t = 1;
  23749. int resultWrite = 0;
  23750. MA_ASSERT(pDevice != NULL);
  23751. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up...\n");
  23752. /* Write to an eventfd to trigger a wakeup from poll() and abort any reading or writing. */
  23753. if (pDevice->alsa.pPollDescriptorsCapture != NULL) {
  23754. resultWrite = write(pDevice->alsa.wakeupfdCapture, &t, sizeof(t));
  23755. }
  23756. if (pDevice->alsa.pPollDescriptorsPlayback != NULL) {
  23757. resultWrite = write(pDevice->alsa.wakeupfdPlayback, &t, sizeof(t));
  23758. }
  23759. if (resultWrite < 0) {
  23760. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] write() failed.\n");
  23761. return ma_result_from_errno(errno);
  23762. }
  23763. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up completed successfully.\n");
  23764. return MA_SUCCESS;
  23765. }
  23766. static ma_result ma_context_uninit__alsa(ma_context* pContext)
  23767. {
  23768. MA_ASSERT(pContext != NULL);
  23769. MA_ASSERT(pContext->backend == ma_backend_alsa);
  23770. /* Clean up memory for memory leak checkers. */
  23771. ((ma_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)();
  23772. #ifndef MA_NO_RUNTIME_LINKING
  23773. ma_dlclose(ma_context_get_log(pContext), pContext->alsa.asoundSO);
  23774. #endif
  23775. ma_mutex_uninit(&pContext->alsa.internalDeviceEnumLock);
  23776. return MA_SUCCESS;
  23777. }
  23778. static ma_result ma_context_init__alsa(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  23779. {
  23780. ma_result result;
  23781. #ifndef MA_NO_RUNTIME_LINKING
  23782. const char* libasoundNames[] = {
  23783. "libasound.so.2",
  23784. "libasound.so"
  23785. };
  23786. size_t i;
  23787. for (i = 0; i < ma_countof(libasoundNames); ++i) {
  23788. pContext->alsa.asoundSO = ma_dlopen(ma_context_get_log(pContext), libasoundNames[i]);
  23789. if (pContext->alsa.asoundSO != NULL) {
  23790. break;
  23791. }
  23792. }
  23793. if (pContext->alsa.asoundSO == NULL) {
  23794. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[ALSA] Failed to open shared object.\n");
  23795. return MA_NO_BACKEND;
  23796. }
  23797. pContext->alsa.snd_pcm_open = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_open");
  23798. pContext->alsa.snd_pcm_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_close");
  23799. pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof");
  23800. pContext->alsa.snd_pcm_hw_params_any = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_any");
  23801. pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format");
  23802. pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first");
  23803. pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask");
  23804. pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels");
  23805. pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near");
  23806. pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_minmax");
  23807. pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample");
  23808. pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate");
  23809. pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near");
  23810. pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near");
  23811. pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near");
  23812. pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access");
  23813. pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format");
  23814. pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels");
  23815. pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min");
  23816. pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max");
  23817. pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate");
  23818. pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min");
  23819. pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max");
  23820. pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size");
  23821. pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods");
  23822. pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access");
  23823. pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_test_format");
  23824. pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_test_channels");
  23825. pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params_test_rate");
  23826. pContext->alsa.snd_pcm_hw_params = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_hw_params");
  23827. pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof");
  23828. pContext->alsa.snd_pcm_sw_params_current = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_current");
  23829. pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_get_boundary");
  23830. pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min");
  23831. pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold");
  23832. pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params_set_stop_threshold");
  23833. pContext->alsa.snd_pcm_sw_params = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_sw_params");
  23834. pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof");
  23835. pContext->alsa.snd_pcm_format_mask_test = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_format_mask_test");
  23836. pContext->alsa.snd_pcm_get_chmap = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_get_chmap");
  23837. pContext->alsa.snd_pcm_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_state");
  23838. pContext->alsa.snd_pcm_prepare = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_prepare");
  23839. pContext->alsa.snd_pcm_start = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_start");
  23840. pContext->alsa.snd_pcm_drop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_drop");
  23841. pContext->alsa.snd_pcm_drain = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_drain");
  23842. pContext->alsa.snd_pcm_reset = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_reset");
  23843. pContext->alsa.snd_device_name_hint = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_device_name_hint");
  23844. pContext->alsa.snd_device_name_get_hint = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_device_name_get_hint");
  23845. pContext->alsa.snd_card_get_index = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_card_get_index");
  23846. pContext->alsa.snd_device_name_free_hint = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_device_name_free_hint");
  23847. pContext->alsa.snd_pcm_mmap_begin = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_mmap_begin");
  23848. pContext->alsa.snd_pcm_mmap_commit = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_mmap_commit");
  23849. pContext->alsa.snd_pcm_recover = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_recover");
  23850. pContext->alsa.snd_pcm_readi = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_readi");
  23851. pContext->alsa.snd_pcm_writei = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_writei");
  23852. pContext->alsa.snd_pcm_avail = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_avail");
  23853. pContext->alsa.snd_pcm_avail_update = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_avail_update");
  23854. pContext->alsa.snd_pcm_wait = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_wait");
  23855. pContext->alsa.snd_pcm_nonblock = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_nonblock");
  23856. pContext->alsa.snd_pcm_info = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_info");
  23857. pContext->alsa.snd_pcm_info_sizeof = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_info_sizeof");
  23858. pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_info_get_name");
  23859. pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_poll_descriptors");
  23860. pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_count");
  23861. pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_revents");
  23862. pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->alsa.asoundSO, "snd_config_update_free_global");
  23863. #else
  23864. /* The system below is just for type safety. */
  23865. ma_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open;
  23866. ma_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close;
  23867. ma_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof;
  23868. ma_snd_pcm_hw_params_any_proc _snd_pcm_hw_params_any = snd_pcm_hw_params_any;
  23869. ma_snd_pcm_hw_params_set_format_proc _snd_pcm_hw_params_set_format = snd_pcm_hw_params_set_format;
  23870. ma_snd_pcm_hw_params_set_format_first_proc _snd_pcm_hw_params_set_format_first = snd_pcm_hw_params_set_format_first;
  23871. ma_snd_pcm_hw_params_get_format_mask_proc _snd_pcm_hw_params_get_format_mask = snd_pcm_hw_params_get_format_mask;
  23872. ma_snd_pcm_hw_params_set_channels_proc _snd_pcm_hw_params_set_channels = snd_pcm_hw_params_set_channels;
  23873. ma_snd_pcm_hw_params_set_channels_near_proc _snd_pcm_hw_params_set_channels_near = snd_pcm_hw_params_set_channels_near;
  23874. ma_snd_pcm_hw_params_set_rate_resample_proc _snd_pcm_hw_params_set_rate_resample = snd_pcm_hw_params_set_rate_resample;
  23875. ma_snd_pcm_hw_params_set_rate_near _snd_pcm_hw_params_set_rate = snd_pcm_hw_params_set_rate;
  23876. ma_snd_pcm_hw_params_set_rate_near_proc _snd_pcm_hw_params_set_rate_near = snd_pcm_hw_params_set_rate_near;
  23877. ma_snd_pcm_hw_params_set_rate_minmax_proc _snd_pcm_hw_params_set_rate_minmax = snd_pcm_hw_params_set_rate_minmax;
  23878. 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;
  23879. ma_snd_pcm_hw_params_set_periods_near_proc _snd_pcm_hw_params_set_periods_near = snd_pcm_hw_params_set_periods_near;
  23880. ma_snd_pcm_hw_params_set_access_proc _snd_pcm_hw_params_set_access = snd_pcm_hw_params_set_access;
  23881. ma_snd_pcm_hw_params_get_format_proc _snd_pcm_hw_params_get_format = snd_pcm_hw_params_get_format;
  23882. ma_snd_pcm_hw_params_get_channels_proc _snd_pcm_hw_params_get_channels = snd_pcm_hw_params_get_channels;
  23883. ma_snd_pcm_hw_params_get_channels_min_proc _snd_pcm_hw_params_get_channels_min = snd_pcm_hw_params_get_channels_min;
  23884. ma_snd_pcm_hw_params_get_channels_max_proc _snd_pcm_hw_params_get_channels_max = snd_pcm_hw_params_get_channels_max;
  23885. ma_snd_pcm_hw_params_get_rate_proc _snd_pcm_hw_params_get_rate = snd_pcm_hw_params_get_rate;
  23886. ma_snd_pcm_hw_params_get_rate_min_proc _snd_pcm_hw_params_get_rate_min = snd_pcm_hw_params_get_rate_min;
  23887. ma_snd_pcm_hw_params_get_rate_max_proc _snd_pcm_hw_params_get_rate_max = snd_pcm_hw_params_get_rate_max;
  23888. ma_snd_pcm_hw_params_get_buffer_size_proc _snd_pcm_hw_params_get_buffer_size = snd_pcm_hw_params_get_buffer_size;
  23889. ma_snd_pcm_hw_params_get_periods_proc _snd_pcm_hw_params_get_periods = snd_pcm_hw_params_get_periods;
  23890. ma_snd_pcm_hw_params_get_access_proc _snd_pcm_hw_params_get_access = snd_pcm_hw_params_get_access;
  23891. ma_snd_pcm_hw_params_test_format_proc _snd_pcm_hw_params_test_format = snd_pcm_hw_params_test_format;
  23892. ma_snd_pcm_hw_params_test_channels_proc _snd_pcm_hw_params_test_channels = snd_pcm_hw_params_test_channels;
  23893. ma_snd_pcm_hw_params_test_rate_proc _snd_pcm_hw_params_test_rate = snd_pcm_hw_params_test_rate;
  23894. ma_snd_pcm_hw_params_proc _snd_pcm_hw_params = snd_pcm_hw_params;
  23895. ma_snd_pcm_sw_params_sizeof_proc _snd_pcm_sw_params_sizeof = snd_pcm_sw_params_sizeof;
  23896. ma_snd_pcm_sw_params_current_proc _snd_pcm_sw_params_current = snd_pcm_sw_params_current;
  23897. ma_snd_pcm_sw_params_get_boundary_proc _snd_pcm_sw_params_get_boundary = snd_pcm_sw_params_get_boundary;
  23898. ma_snd_pcm_sw_params_set_avail_min_proc _snd_pcm_sw_params_set_avail_min = snd_pcm_sw_params_set_avail_min;
  23899. ma_snd_pcm_sw_params_set_start_threshold_proc _snd_pcm_sw_params_set_start_threshold = snd_pcm_sw_params_set_start_threshold;
  23900. ma_snd_pcm_sw_params_set_stop_threshold_proc _snd_pcm_sw_params_set_stop_threshold = snd_pcm_sw_params_set_stop_threshold;
  23901. ma_snd_pcm_sw_params_proc _snd_pcm_sw_params = snd_pcm_sw_params;
  23902. ma_snd_pcm_format_mask_sizeof_proc _snd_pcm_format_mask_sizeof = snd_pcm_format_mask_sizeof;
  23903. ma_snd_pcm_format_mask_test_proc _snd_pcm_format_mask_test = snd_pcm_format_mask_test;
  23904. ma_snd_pcm_get_chmap_proc _snd_pcm_get_chmap = snd_pcm_get_chmap;
  23905. ma_snd_pcm_state_proc _snd_pcm_state = snd_pcm_state;
  23906. ma_snd_pcm_prepare_proc _snd_pcm_prepare = snd_pcm_prepare;
  23907. ma_snd_pcm_start_proc _snd_pcm_start = snd_pcm_start;
  23908. ma_snd_pcm_drop_proc _snd_pcm_drop = snd_pcm_drop;
  23909. ma_snd_pcm_drain_proc _snd_pcm_drain = snd_pcm_drain;
  23910. ma_snd_pcm_reset_proc _snd_pcm_reset = snd_pcm_reset;
  23911. ma_snd_device_name_hint_proc _snd_device_name_hint = snd_device_name_hint;
  23912. ma_snd_device_name_get_hint_proc _snd_device_name_get_hint = snd_device_name_get_hint;
  23913. ma_snd_card_get_index_proc _snd_card_get_index = snd_card_get_index;
  23914. ma_snd_device_name_free_hint_proc _snd_device_name_free_hint = snd_device_name_free_hint;
  23915. ma_snd_pcm_mmap_begin_proc _snd_pcm_mmap_begin = snd_pcm_mmap_begin;
  23916. ma_snd_pcm_mmap_commit_proc _snd_pcm_mmap_commit = snd_pcm_mmap_commit;
  23917. ma_snd_pcm_recover_proc _snd_pcm_recover = snd_pcm_recover;
  23918. ma_snd_pcm_readi_proc _snd_pcm_readi = snd_pcm_readi;
  23919. ma_snd_pcm_writei_proc _snd_pcm_writei = snd_pcm_writei;
  23920. ma_snd_pcm_avail_proc _snd_pcm_avail = snd_pcm_avail;
  23921. ma_snd_pcm_avail_update_proc _snd_pcm_avail_update = snd_pcm_avail_update;
  23922. ma_snd_pcm_wait_proc _snd_pcm_wait = snd_pcm_wait;
  23923. ma_snd_pcm_nonblock_proc _snd_pcm_nonblock = snd_pcm_nonblock;
  23924. ma_snd_pcm_info_proc _snd_pcm_info = snd_pcm_info;
  23925. ma_snd_pcm_info_sizeof_proc _snd_pcm_info_sizeof = snd_pcm_info_sizeof;
  23926. ma_snd_pcm_info_get_name_proc _snd_pcm_info_get_name = snd_pcm_info_get_name;
  23927. ma_snd_pcm_poll_descriptors _snd_pcm_poll_descriptors = snd_pcm_poll_descriptors;
  23928. ma_snd_pcm_poll_descriptors_count _snd_pcm_poll_descriptors_count = snd_pcm_poll_descriptors_count;
  23929. ma_snd_pcm_poll_descriptors_revents _snd_pcm_poll_descriptors_revents = snd_pcm_poll_descriptors_revents;
  23930. ma_snd_config_update_free_global_proc _snd_config_update_free_global = snd_config_update_free_global;
  23931. pContext->alsa.snd_pcm_open = (ma_proc)_snd_pcm_open;
  23932. pContext->alsa.snd_pcm_close = (ma_proc)_snd_pcm_close;
  23933. pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)_snd_pcm_hw_params_sizeof;
  23934. pContext->alsa.snd_pcm_hw_params_any = (ma_proc)_snd_pcm_hw_params_any;
  23935. pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)_snd_pcm_hw_params_set_format;
  23936. pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)_snd_pcm_hw_params_set_format_first;
  23937. pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)_snd_pcm_hw_params_get_format_mask;
  23938. pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)_snd_pcm_hw_params_set_channels;
  23939. pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)_snd_pcm_hw_params_set_channels_near;
  23940. pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)_snd_pcm_hw_params_set_channels_minmax;
  23941. pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)_snd_pcm_hw_params_set_rate_resample;
  23942. pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)_snd_pcm_hw_params_set_rate;
  23943. pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)_snd_pcm_hw_params_set_rate_near;
  23944. pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)_snd_pcm_hw_params_set_buffer_size_near;
  23945. pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)_snd_pcm_hw_params_set_periods_near;
  23946. pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)_snd_pcm_hw_params_set_access;
  23947. pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)_snd_pcm_hw_params_get_format;
  23948. pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)_snd_pcm_hw_params_get_channels;
  23949. pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)_snd_pcm_hw_params_get_channels_min;
  23950. pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)_snd_pcm_hw_params_get_channels_max;
  23951. pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)_snd_pcm_hw_params_get_rate;
  23952. pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)_snd_pcm_hw_params_get_rate_min;
  23953. pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)_snd_pcm_hw_params_get_rate_max;
  23954. pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)_snd_pcm_hw_params_get_buffer_size;
  23955. pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)_snd_pcm_hw_params_get_periods;
  23956. pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)_snd_pcm_hw_params_get_access;
  23957. pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)_snd_pcm_hw_params_test_format;
  23958. pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)_snd_pcm_hw_params_test_channels;
  23959. pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)_snd_pcm_hw_params_test_rate;
  23960. pContext->alsa.snd_pcm_hw_params = (ma_proc)_snd_pcm_hw_params;
  23961. pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)_snd_pcm_sw_params_sizeof;
  23962. pContext->alsa.snd_pcm_sw_params_current = (ma_proc)_snd_pcm_sw_params_current;
  23963. pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)_snd_pcm_sw_params_get_boundary;
  23964. pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)_snd_pcm_sw_params_set_avail_min;
  23965. pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)_snd_pcm_sw_params_set_start_threshold;
  23966. pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)_snd_pcm_sw_params_set_stop_threshold;
  23967. pContext->alsa.snd_pcm_sw_params = (ma_proc)_snd_pcm_sw_params;
  23968. pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)_snd_pcm_format_mask_sizeof;
  23969. pContext->alsa.snd_pcm_format_mask_test = (ma_proc)_snd_pcm_format_mask_test;
  23970. pContext->alsa.snd_pcm_get_chmap = (ma_proc)_snd_pcm_get_chmap;
  23971. pContext->alsa.snd_pcm_state = (ma_proc)_snd_pcm_state;
  23972. pContext->alsa.snd_pcm_prepare = (ma_proc)_snd_pcm_prepare;
  23973. pContext->alsa.snd_pcm_start = (ma_proc)_snd_pcm_start;
  23974. pContext->alsa.snd_pcm_drop = (ma_proc)_snd_pcm_drop;
  23975. pContext->alsa.snd_pcm_drain = (ma_proc)_snd_pcm_drain;
  23976. pContext->alsa.snd_pcm_reset = (ma_proc)_snd_pcm_reset;
  23977. pContext->alsa.snd_device_name_hint = (ma_proc)_snd_device_name_hint;
  23978. pContext->alsa.snd_device_name_get_hint = (ma_proc)_snd_device_name_get_hint;
  23979. pContext->alsa.snd_card_get_index = (ma_proc)_snd_card_get_index;
  23980. pContext->alsa.snd_device_name_free_hint = (ma_proc)_snd_device_name_free_hint;
  23981. pContext->alsa.snd_pcm_mmap_begin = (ma_proc)_snd_pcm_mmap_begin;
  23982. pContext->alsa.snd_pcm_mmap_commit = (ma_proc)_snd_pcm_mmap_commit;
  23983. pContext->alsa.snd_pcm_recover = (ma_proc)_snd_pcm_recover;
  23984. pContext->alsa.snd_pcm_readi = (ma_proc)_snd_pcm_readi;
  23985. pContext->alsa.snd_pcm_writei = (ma_proc)_snd_pcm_writei;
  23986. pContext->alsa.snd_pcm_avail = (ma_proc)_snd_pcm_avail;
  23987. pContext->alsa.snd_pcm_avail_update = (ma_proc)_snd_pcm_avail_update;
  23988. pContext->alsa.snd_pcm_wait = (ma_proc)_snd_pcm_wait;
  23989. pContext->alsa.snd_pcm_nonblock = (ma_proc)_snd_pcm_nonblock;
  23990. pContext->alsa.snd_pcm_info = (ma_proc)_snd_pcm_info;
  23991. pContext->alsa.snd_pcm_info_sizeof = (ma_proc)_snd_pcm_info_sizeof;
  23992. pContext->alsa.snd_pcm_info_get_name = (ma_proc)_snd_pcm_info_get_name;
  23993. pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)_snd_pcm_poll_descriptors;
  23994. pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)_snd_pcm_poll_descriptors_count;
  23995. pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)_snd_pcm_poll_descriptors_revents;
  23996. pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global;
  23997. #endif
  23998. pContext->alsa.useVerboseDeviceEnumeration = pConfig->alsa.useVerboseDeviceEnumeration;
  23999. result = ma_mutex_init(&pContext->alsa.internalDeviceEnumLock);
  24000. if (result != MA_SUCCESS) {
  24001. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.");
  24002. return result;
  24003. }
  24004. pCallbacks->onContextInit = ma_context_init__alsa;
  24005. pCallbacks->onContextUninit = ma_context_uninit__alsa;
  24006. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__alsa;
  24007. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__alsa;
  24008. pCallbacks->onDeviceInit = ma_device_init__alsa;
  24009. pCallbacks->onDeviceUninit = ma_device_uninit__alsa;
  24010. pCallbacks->onDeviceStart = ma_device_start__alsa;
  24011. pCallbacks->onDeviceStop = ma_device_stop__alsa;
  24012. pCallbacks->onDeviceRead = ma_device_read__alsa;
  24013. pCallbacks->onDeviceWrite = ma_device_write__alsa;
  24014. pCallbacks->onDeviceDataLoop = NULL;
  24015. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__alsa;
  24016. return MA_SUCCESS;
  24017. }
  24018. #endif /* ALSA */
  24019. /******************************************************************************
  24020. PulseAudio Backend
  24021. ******************************************************************************/
  24022. #ifdef MA_HAS_PULSEAUDIO
  24023. /*
  24024. 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
  24025. in the PulseAudio backend. I apologize if this gets a bit ranty for your liking - you might want to skip this discussion.
  24026. PulseAudio has something they call the "Simple API", which unfortunately isn't suitable for miniaudio. I've not seen anywhere where it
  24027. allows you to enumerate over devices, nor does it seem to support the ability to stop and start streams. Looking at the documentation, it
  24028. appears as though the stream is constantly running and you prevent sound from being emitted or captured by simply not calling the read or
  24029. write functions. This is not a professional solution as it would be much better to *actually* stop the underlying stream. Perhaps the
  24030. 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
  24031. when you want to have multiple streams to a single context. For these reasons, miniaudio is not using the simple API.
  24032. 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
  24033. get fun, and I don't mean that in a good way...
  24034. The problems start with the very name of the API - "asynchronous". Yes, this is an asynchronous oriented API which means your commands
  24035. don't immediately take effect. You instead need to issue your commands, and then wait for them to complete. The waiting mechanism is
  24036. 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
  24037. all of PulseAudio's problems stem from.
  24038. When you first initialize PulseAudio you need an object referred to as "main loop". You can implement this yourself by defining your own
  24039. vtable, but it's much easier to just use one of the built-in main loop implementations. There's two generic implementations called
  24040. pa_mainloop and pa_threaded_mainloop, and another implementation specific to GLib called pa_glib_mainloop. We're using pa_threaded_mainloop
  24041. because it simplifies management of the worker thread. The idea of the main loop object is pretty self explanatory - you're supposed to use
  24042. it to implement a worker thread which runs in a loop. The main loop is where operations are actually executed.
  24043. 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
  24044. to the vtable with `pa_threaded_mainloop_get_api()` (the main loop vtable is called `pa_mainloop_api`). Again, you can bypass the threaded
  24045. main loop object entirely and just implement `pa_mainloop_api` directly, but there's no need for it unless you're doing something extremely
  24046. specialized such as if you want to integrate it into your application's existing main loop infrastructure.
  24047. (EDIT 2021-01-26: miniaudio is no longer using `pa_threaded_mainloop` due to this issue: https://github.com/mackron/miniaudio/issues/262.
  24048. It is now using `pa_mainloop` which turns out to be a simpler solution anyway. The rest of this rant still applies, however.)
  24049. Once you have your main loop vtable (the `pa_mainloop_api` object) you can create the PulseAudio context. This is very similar to
  24050. 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
  24051. 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
  24052. is done with `pa_context_new()`, it's not actually connected to anything. When you connect, you call `pa_context_connect()`. However, if
  24053. you remember, PulseAudio is an asynchronous API. That means you cannot just assume the context is connected after `pa_context_context()`
  24054. 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
  24055. 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.
  24056. 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.
  24057. This waiting loop is therefore unavoidable. In order for the waiting to ever complete, however, the main loop needs to be running. Before
  24058. attempting to connect the context, the main loop needs to be started with `pa_threaded_mainloop_start()`.
  24059. 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
  24060. internet connection. However, the *VAST* majority of cases don't involve this at all - they just connect to a local "server" running on the
  24061. host machine. The fact that this would be the default rather than making `pa_context_connect()` synchronous tends to boggle the mind.
  24062. Once the context has been created and connected you can start creating a stream. A PulseAudio stream is analogous to miniaudio's device.
  24063. The initialization of a stream is fairly standard - you configure some attributes (analogous to miniaudio's device config) and then call
  24064. `pa_stream_new()` to actually create it. Here is where we start to get into "operations". When configuring the stream, you can get
  24065. information about the source (such as sample format, sample rate, etc.), however it's not synchronous. Instead, a `pa_operation` object
  24066. is returned from `pa_context_get_source_info_by_name()` (capture) or `pa_context_get_sink_info_by_name()` (playback). Then, you need to
  24067. 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
  24068. context. Then, as an added bonus, you need to decrement the reference counter of the `pa_operation` object to ensure memory is cleaned up.
  24069. All of that just to retrieve basic information about a device!
  24070. Once the basic information about the device has been retrieved, miniaudio can now create the stream with `ma_stream_new()`. Like the
  24071. 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
  24072. choices in PulseAudio.
  24073. 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
  24074. because PulseAudio takes it literally, specifically the "can be". You would think these callbacks would be appropriate as the place for
  24075. 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
  24076. set a flag that tells PulseAudio to not start the stream automatically. This is required because miniaudio does not auto-start devices
  24077. straight after initialization - you need to call `ma_device_start()` manually. The problem is that even when this flag is specified,
  24078. PulseAudio will immediately fire it's write or read callback. This is *technically* correct (based on the wording in the documentation)
  24079. 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
  24080. 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
  24081. 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
  24082. that point (it may still need to load files or whatnot). Instead, this callback should only be fired when the application requests the
  24083. stream be started which is how it works with literally *every* other callback-based audio API. Since miniaudio forbids firing of the data
  24084. callback until the device has been started (as it should be with *all* callback based APIs), logic needs to be added to ensure miniaudio
  24085. doesn't just blindly fire the application-defined data callback from within the PulseAudio callback before the stream has actually been
  24086. 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
  24087. callback is not fired.
  24088. This, unfortunately, is not the end of the problems with the PulseAudio write callback. Any normal callback based audio API will
  24089. continuously fire the callback at regular intervals based on the size of the internal buffer. This will only ever be fired when the device
  24090. 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
  24091. PulseAudio. In PulseAudio, the data callback will *only* be called if you wrote something to it previously. That means, if you don't call
  24092. `pa_stream_write()`, the callback will not get fired. On the surface you wouldn't think this would matter because you should be always
  24093. 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
  24094. 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
  24095. *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
  24096. important? Because that's how we've defined stopping to work in miniaudio. In miniaudio, stopping the device requires it to be drained
  24097. before returning from ma_device_stop(). So we've stopped the device, which requires us to drain, but draining requires us to *not* write
  24098. 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!
  24099. This becomes a problem when stopping and then restarting the device. When the device is stopped, it's drained, which requires us to *not*
  24100. 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
  24101. resume the stream naively. This means that starting the stream requires us to write data to the stream from outside the callback. This
  24102. disconnect is something PulseAudio has got seriously wrong - there should only ever be a single source of data delivery, that being the
  24103. callback. (I have tried using `pa_stream_flush()` to trigger the write callback to fire, but this just doesn't work for some reason.)
  24104. 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,
  24105. 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
  24106. "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
  24107. 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
  24108. guessed it, asynchronous. This means you'll need our waiting loop as usual. Again, why this asynchronous design is the default is
  24109. absolutely beyond me. Would it really be that hard to just make it run synchronously?
  24110. Teardown is pretty simple (what?!). It's just a matter of calling the relevant `_unref()` function on each object in reverse order that
  24111. they were initialized in.
  24112. 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
  24113. embarrassingly unpractical. The main loop thing is an easy fix - have synchronous versions of all APIs. If an application wants these to
  24114. run asynchronously, they can execute them in a separate thread themselves. The desire to run these asynchronously is such a niche
  24115. requirement - it makes no sense to make it the default. The stream write callback needs to be change, or an alternative provided, that is
  24116. 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
  24117. parameter which the program just writes to directly rather than having to call `pa_stream_writable_size()` and `pa_stream_write()`. These
  24118. changes alone will change PulseAudio from one of the worst audio APIs to one of the best.
  24119. */
  24120. /*
  24121. It is assumed pulseaudio.h is available when linking at compile time. When linking at compile time, we use the declarations in the header
  24122. to check for type safety. We cannot do this when linking at run time because the header might not be available.
  24123. */
  24124. #ifdef MA_NO_RUNTIME_LINKING
  24125. /* pulseaudio.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
  24126. #if !defined(__cplusplus)
  24127. #if defined(__STRICT_ANSI__)
  24128. #if !defined(inline)
  24129. #define inline __inline__ __attribute__((always_inline))
  24130. #define MA_INLINE_DEFINED
  24131. #endif
  24132. #endif
  24133. #endif
  24134. #include <pulse/pulseaudio.h>
  24135. #if defined(MA_INLINE_DEFINED)
  24136. #undef inline
  24137. #undef MA_INLINE_DEFINED
  24138. #endif
  24139. #define MA_PA_OK PA_OK
  24140. #define MA_PA_ERR_ACCESS PA_ERR_ACCESS
  24141. #define MA_PA_ERR_INVALID PA_ERR_INVALID
  24142. #define MA_PA_ERR_NOENTITY PA_ERR_NOENTITY
  24143. #define MA_PA_ERR_NOTSUPPORTED PA_ERR_NOTSUPPORTED
  24144. #define MA_PA_CHANNELS_MAX PA_CHANNELS_MAX
  24145. #define MA_PA_RATE_MAX PA_RATE_MAX
  24146. typedef pa_context_flags_t ma_pa_context_flags_t;
  24147. #define MA_PA_CONTEXT_NOFLAGS PA_CONTEXT_NOFLAGS
  24148. #define MA_PA_CONTEXT_NOAUTOSPAWN PA_CONTEXT_NOAUTOSPAWN
  24149. #define MA_PA_CONTEXT_NOFAIL PA_CONTEXT_NOFAIL
  24150. typedef pa_stream_flags_t ma_pa_stream_flags_t;
  24151. #define MA_PA_STREAM_NOFLAGS PA_STREAM_NOFLAGS
  24152. #define MA_PA_STREAM_START_CORKED PA_STREAM_START_CORKED
  24153. #define MA_PA_STREAM_INTERPOLATE_TIMING PA_STREAM_INTERPOLATE_TIMING
  24154. #define MA_PA_STREAM_NOT_MONOTONIC PA_STREAM_NOT_MONOTONIC
  24155. #define MA_PA_STREAM_AUTO_TIMING_UPDATE PA_STREAM_AUTO_TIMING_UPDATE
  24156. #define MA_PA_STREAM_NO_REMAP_CHANNELS PA_STREAM_NO_REMAP_CHANNELS
  24157. #define MA_PA_STREAM_NO_REMIX_CHANNELS PA_STREAM_NO_REMIX_CHANNELS
  24158. #define MA_PA_STREAM_FIX_FORMAT PA_STREAM_FIX_FORMAT
  24159. #define MA_PA_STREAM_FIX_RATE PA_STREAM_FIX_RATE
  24160. #define MA_PA_STREAM_FIX_CHANNELS PA_STREAM_FIX_CHANNELS
  24161. #define MA_PA_STREAM_DONT_MOVE PA_STREAM_DONT_MOVE
  24162. #define MA_PA_STREAM_VARIABLE_RATE PA_STREAM_VARIABLE_RATE
  24163. #define MA_PA_STREAM_PEAK_DETECT PA_STREAM_PEAK_DETECT
  24164. #define MA_PA_STREAM_START_MUTED PA_STREAM_START_MUTED
  24165. #define MA_PA_STREAM_ADJUST_LATENCY PA_STREAM_ADJUST_LATENCY
  24166. #define MA_PA_STREAM_EARLY_REQUESTS PA_STREAM_EARLY_REQUESTS
  24167. #define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND
  24168. #define MA_PA_STREAM_START_UNMUTED PA_STREAM_START_UNMUTED
  24169. #define MA_PA_STREAM_FAIL_ON_SUSPEND PA_STREAM_FAIL_ON_SUSPEND
  24170. #define MA_PA_STREAM_RELATIVE_VOLUME PA_STREAM_RELATIVE_VOLUME
  24171. #define MA_PA_STREAM_PASSTHROUGH PA_STREAM_PASSTHROUGH
  24172. typedef pa_sink_flags_t ma_pa_sink_flags_t;
  24173. #define MA_PA_SINK_NOFLAGS PA_SINK_NOFLAGS
  24174. #define MA_PA_SINK_HW_VOLUME_CTRL PA_SINK_HW_VOLUME_CTRL
  24175. #define MA_PA_SINK_LATENCY PA_SINK_LATENCY
  24176. #define MA_PA_SINK_HARDWARE PA_SINK_HARDWARE
  24177. #define MA_PA_SINK_NETWORK PA_SINK_NETWORK
  24178. #define MA_PA_SINK_HW_MUTE_CTRL PA_SINK_HW_MUTE_CTRL
  24179. #define MA_PA_SINK_DECIBEL_VOLUME PA_SINK_DECIBEL_VOLUME
  24180. #define MA_PA_SINK_FLAT_VOLUME PA_SINK_FLAT_VOLUME
  24181. #define MA_PA_SINK_DYNAMIC_LATENCY PA_SINK_DYNAMIC_LATENCY
  24182. #define MA_PA_SINK_SET_FORMATS PA_SINK_SET_FORMATS
  24183. typedef pa_source_flags_t ma_pa_source_flags_t;
  24184. #define MA_PA_SOURCE_NOFLAGS PA_SOURCE_NOFLAGS
  24185. #define MA_PA_SOURCE_HW_VOLUME_CTRL PA_SOURCE_HW_VOLUME_CTRL
  24186. #define MA_PA_SOURCE_LATENCY PA_SOURCE_LATENCY
  24187. #define MA_PA_SOURCE_HARDWARE PA_SOURCE_HARDWARE
  24188. #define MA_PA_SOURCE_NETWORK PA_SOURCE_NETWORK
  24189. #define MA_PA_SOURCE_HW_MUTE_CTRL PA_SOURCE_HW_MUTE_CTRL
  24190. #define MA_PA_SOURCE_DECIBEL_VOLUME PA_SOURCE_DECIBEL_VOLUME
  24191. #define MA_PA_SOURCE_DYNAMIC_LATENCY PA_SOURCE_DYNAMIC_LATENCY
  24192. #define MA_PA_SOURCE_FLAT_VOLUME PA_SOURCE_FLAT_VOLUME
  24193. typedef pa_context_state_t ma_pa_context_state_t;
  24194. #define MA_PA_CONTEXT_UNCONNECTED PA_CONTEXT_UNCONNECTED
  24195. #define MA_PA_CONTEXT_CONNECTING PA_CONTEXT_CONNECTING
  24196. #define MA_PA_CONTEXT_AUTHORIZING PA_CONTEXT_AUTHORIZING
  24197. #define MA_PA_CONTEXT_SETTING_NAME PA_CONTEXT_SETTING_NAME
  24198. #define MA_PA_CONTEXT_READY PA_CONTEXT_READY
  24199. #define MA_PA_CONTEXT_FAILED PA_CONTEXT_FAILED
  24200. #define MA_PA_CONTEXT_TERMINATED PA_CONTEXT_TERMINATED
  24201. typedef pa_stream_state_t ma_pa_stream_state_t;
  24202. #define MA_PA_STREAM_UNCONNECTED PA_STREAM_UNCONNECTED
  24203. #define MA_PA_STREAM_CREATING PA_STREAM_CREATING
  24204. #define MA_PA_STREAM_READY PA_STREAM_READY
  24205. #define MA_PA_STREAM_FAILED PA_STREAM_FAILED
  24206. #define MA_PA_STREAM_TERMINATED PA_STREAM_TERMINATED
  24207. typedef pa_operation_state_t ma_pa_operation_state_t;
  24208. #define MA_PA_OPERATION_RUNNING PA_OPERATION_RUNNING
  24209. #define MA_PA_OPERATION_DONE PA_OPERATION_DONE
  24210. #define MA_PA_OPERATION_CANCELLED PA_OPERATION_CANCELLED
  24211. typedef pa_sink_state_t ma_pa_sink_state_t;
  24212. #define MA_PA_SINK_INVALID_STATE PA_SINK_INVALID_STATE
  24213. #define MA_PA_SINK_RUNNING PA_SINK_RUNNING
  24214. #define MA_PA_SINK_IDLE PA_SINK_IDLE
  24215. #define MA_PA_SINK_SUSPENDED PA_SINK_SUSPENDED
  24216. typedef pa_source_state_t ma_pa_source_state_t;
  24217. #define MA_PA_SOURCE_INVALID_STATE PA_SOURCE_INVALID_STATE
  24218. #define MA_PA_SOURCE_RUNNING PA_SOURCE_RUNNING
  24219. #define MA_PA_SOURCE_IDLE PA_SOURCE_IDLE
  24220. #define MA_PA_SOURCE_SUSPENDED PA_SOURCE_SUSPENDED
  24221. typedef pa_seek_mode_t ma_pa_seek_mode_t;
  24222. #define MA_PA_SEEK_RELATIVE PA_SEEK_RELATIVE
  24223. #define MA_PA_SEEK_ABSOLUTE PA_SEEK_ABSOLUTE
  24224. #define MA_PA_SEEK_RELATIVE_ON_READ PA_SEEK_RELATIVE_ON_READ
  24225. #define MA_PA_SEEK_RELATIVE_END PA_SEEK_RELATIVE_END
  24226. typedef pa_channel_position_t ma_pa_channel_position_t;
  24227. #define MA_PA_CHANNEL_POSITION_INVALID PA_CHANNEL_POSITION_INVALID
  24228. #define MA_PA_CHANNEL_POSITION_MONO PA_CHANNEL_POSITION_MONO
  24229. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT PA_CHANNEL_POSITION_FRONT_LEFT
  24230. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT PA_CHANNEL_POSITION_FRONT_RIGHT
  24231. #define MA_PA_CHANNEL_POSITION_FRONT_CENTER PA_CHANNEL_POSITION_FRONT_CENTER
  24232. #define MA_PA_CHANNEL_POSITION_REAR_CENTER PA_CHANNEL_POSITION_REAR_CENTER
  24233. #define MA_PA_CHANNEL_POSITION_REAR_LEFT PA_CHANNEL_POSITION_REAR_LEFT
  24234. #define MA_PA_CHANNEL_POSITION_REAR_RIGHT PA_CHANNEL_POSITION_REAR_RIGHT
  24235. #define MA_PA_CHANNEL_POSITION_LFE PA_CHANNEL_POSITION_LFE
  24236. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER
  24237. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER
  24238. #define MA_PA_CHANNEL_POSITION_SIDE_LEFT PA_CHANNEL_POSITION_SIDE_LEFT
  24239. #define MA_PA_CHANNEL_POSITION_SIDE_RIGHT PA_CHANNEL_POSITION_SIDE_RIGHT
  24240. #define MA_PA_CHANNEL_POSITION_AUX0 PA_CHANNEL_POSITION_AUX0
  24241. #define MA_PA_CHANNEL_POSITION_AUX1 PA_CHANNEL_POSITION_AUX1
  24242. #define MA_PA_CHANNEL_POSITION_AUX2 PA_CHANNEL_POSITION_AUX2
  24243. #define MA_PA_CHANNEL_POSITION_AUX3 PA_CHANNEL_POSITION_AUX3
  24244. #define MA_PA_CHANNEL_POSITION_AUX4 PA_CHANNEL_POSITION_AUX4
  24245. #define MA_PA_CHANNEL_POSITION_AUX5 PA_CHANNEL_POSITION_AUX5
  24246. #define MA_PA_CHANNEL_POSITION_AUX6 PA_CHANNEL_POSITION_AUX6
  24247. #define MA_PA_CHANNEL_POSITION_AUX7 PA_CHANNEL_POSITION_AUX7
  24248. #define MA_PA_CHANNEL_POSITION_AUX8 PA_CHANNEL_POSITION_AUX8
  24249. #define MA_PA_CHANNEL_POSITION_AUX9 PA_CHANNEL_POSITION_AUX9
  24250. #define MA_PA_CHANNEL_POSITION_AUX10 PA_CHANNEL_POSITION_AUX10
  24251. #define MA_PA_CHANNEL_POSITION_AUX11 PA_CHANNEL_POSITION_AUX11
  24252. #define MA_PA_CHANNEL_POSITION_AUX12 PA_CHANNEL_POSITION_AUX12
  24253. #define MA_PA_CHANNEL_POSITION_AUX13 PA_CHANNEL_POSITION_AUX13
  24254. #define MA_PA_CHANNEL_POSITION_AUX14 PA_CHANNEL_POSITION_AUX14
  24255. #define MA_PA_CHANNEL_POSITION_AUX15 PA_CHANNEL_POSITION_AUX15
  24256. #define MA_PA_CHANNEL_POSITION_AUX16 PA_CHANNEL_POSITION_AUX16
  24257. #define MA_PA_CHANNEL_POSITION_AUX17 PA_CHANNEL_POSITION_AUX17
  24258. #define MA_PA_CHANNEL_POSITION_AUX18 PA_CHANNEL_POSITION_AUX18
  24259. #define MA_PA_CHANNEL_POSITION_AUX19 PA_CHANNEL_POSITION_AUX19
  24260. #define MA_PA_CHANNEL_POSITION_AUX20 PA_CHANNEL_POSITION_AUX20
  24261. #define MA_PA_CHANNEL_POSITION_AUX21 PA_CHANNEL_POSITION_AUX21
  24262. #define MA_PA_CHANNEL_POSITION_AUX22 PA_CHANNEL_POSITION_AUX22
  24263. #define MA_PA_CHANNEL_POSITION_AUX23 PA_CHANNEL_POSITION_AUX23
  24264. #define MA_PA_CHANNEL_POSITION_AUX24 PA_CHANNEL_POSITION_AUX24
  24265. #define MA_PA_CHANNEL_POSITION_AUX25 PA_CHANNEL_POSITION_AUX25
  24266. #define MA_PA_CHANNEL_POSITION_AUX26 PA_CHANNEL_POSITION_AUX26
  24267. #define MA_PA_CHANNEL_POSITION_AUX27 PA_CHANNEL_POSITION_AUX27
  24268. #define MA_PA_CHANNEL_POSITION_AUX28 PA_CHANNEL_POSITION_AUX28
  24269. #define MA_PA_CHANNEL_POSITION_AUX29 PA_CHANNEL_POSITION_AUX29
  24270. #define MA_PA_CHANNEL_POSITION_AUX30 PA_CHANNEL_POSITION_AUX30
  24271. #define MA_PA_CHANNEL_POSITION_AUX31 PA_CHANNEL_POSITION_AUX31
  24272. #define MA_PA_CHANNEL_POSITION_TOP_CENTER PA_CHANNEL_POSITION_TOP_CENTER
  24273. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT PA_CHANNEL_POSITION_TOP_FRONT_LEFT
  24274. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT PA_CHANNEL_POSITION_TOP_FRONT_RIGHT
  24275. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER PA_CHANNEL_POSITION_TOP_FRONT_CENTER
  24276. #define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT PA_CHANNEL_POSITION_TOP_REAR_LEFT
  24277. #define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT PA_CHANNEL_POSITION_TOP_REAR_RIGHT
  24278. #define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER PA_CHANNEL_POSITION_TOP_REAR_CENTER
  24279. #define MA_PA_CHANNEL_POSITION_LEFT PA_CHANNEL_POSITION_LEFT
  24280. #define MA_PA_CHANNEL_POSITION_RIGHT PA_CHANNEL_POSITION_RIGHT
  24281. #define MA_PA_CHANNEL_POSITION_CENTER PA_CHANNEL_POSITION_CENTER
  24282. #define MA_PA_CHANNEL_POSITION_SUBWOOFER PA_CHANNEL_POSITION_SUBWOOFER
  24283. typedef pa_channel_map_def_t ma_pa_channel_map_def_t;
  24284. #define MA_PA_CHANNEL_MAP_AIFF PA_CHANNEL_MAP_AIFF
  24285. #define MA_PA_CHANNEL_MAP_ALSA PA_CHANNEL_MAP_ALSA
  24286. #define MA_PA_CHANNEL_MAP_AUX PA_CHANNEL_MAP_AUX
  24287. #define MA_PA_CHANNEL_MAP_WAVEEX PA_CHANNEL_MAP_WAVEEX
  24288. #define MA_PA_CHANNEL_MAP_OSS PA_CHANNEL_MAP_OSS
  24289. #define MA_PA_CHANNEL_MAP_DEFAULT PA_CHANNEL_MAP_DEFAULT
  24290. typedef pa_sample_format_t ma_pa_sample_format_t;
  24291. #define MA_PA_SAMPLE_INVALID PA_SAMPLE_INVALID
  24292. #define MA_PA_SAMPLE_U8 PA_SAMPLE_U8
  24293. #define MA_PA_SAMPLE_ALAW PA_SAMPLE_ALAW
  24294. #define MA_PA_SAMPLE_ULAW PA_SAMPLE_ULAW
  24295. #define MA_PA_SAMPLE_S16LE PA_SAMPLE_S16LE
  24296. #define MA_PA_SAMPLE_S16BE PA_SAMPLE_S16BE
  24297. #define MA_PA_SAMPLE_FLOAT32LE PA_SAMPLE_FLOAT32LE
  24298. #define MA_PA_SAMPLE_FLOAT32BE PA_SAMPLE_FLOAT32BE
  24299. #define MA_PA_SAMPLE_S32LE PA_SAMPLE_S32LE
  24300. #define MA_PA_SAMPLE_S32BE PA_SAMPLE_S32BE
  24301. #define MA_PA_SAMPLE_S24LE PA_SAMPLE_S24LE
  24302. #define MA_PA_SAMPLE_S24BE PA_SAMPLE_S24BE
  24303. #define MA_PA_SAMPLE_S24_32LE PA_SAMPLE_S24_32LE
  24304. #define MA_PA_SAMPLE_S24_32BE PA_SAMPLE_S24_32BE
  24305. typedef pa_mainloop ma_pa_mainloop;
  24306. typedef pa_threaded_mainloop ma_pa_threaded_mainloop;
  24307. typedef pa_mainloop_api ma_pa_mainloop_api;
  24308. typedef pa_context ma_pa_context;
  24309. typedef pa_operation ma_pa_operation;
  24310. typedef pa_stream ma_pa_stream;
  24311. typedef pa_spawn_api ma_pa_spawn_api;
  24312. typedef pa_buffer_attr ma_pa_buffer_attr;
  24313. typedef pa_channel_map ma_pa_channel_map;
  24314. typedef pa_cvolume ma_pa_cvolume;
  24315. typedef pa_sample_spec ma_pa_sample_spec;
  24316. typedef pa_sink_info ma_pa_sink_info;
  24317. typedef pa_source_info ma_pa_source_info;
  24318. typedef pa_context_notify_cb_t ma_pa_context_notify_cb_t;
  24319. typedef pa_sink_info_cb_t ma_pa_sink_info_cb_t;
  24320. typedef pa_source_info_cb_t ma_pa_source_info_cb_t;
  24321. typedef pa_stream_success_cb_t ma_pa_stream_success_cb_t;
  24322. typedef pa_stream_request_cb_t ma_pa_stream_request_cb_t;
  24323. typedef pa_stream_notify_cb_t ma_pa_stream_notify_cb_t;
  24324. typedef pa_free_cb_t ma_pa_free_cb_t;
  24325. #else
  24326. #define MA_PA_OK 0
  24327. #define MA_PA_ERR_ACCESS 1
  24328. #define MA_PA_ERR_INVALID 2
  24329. #define MA_PA_ERR_NOENTITY 5
  24330. #define MA_PA_ERR_NOTSUPPORTED 19
  24331. #define MA_PA_CHANNELS_MAX 32
  24332. #define MA_PA_RATE_MAX 384000
  24333. typedef int ma_pa_context_flags_t;
  24334. #define MA_PA_CONTEXT_NOFLAGS 0x00000000
  24335. #define MA_PA_CONTEXT_NOAUTOSPAWN 0x00000001
  24336. #define MA_PA_CONTEXT_NOFAIL 0x00000002
  24337. typedef int ma_pa_stream_flags_t;
  24338. #define MA_PA_STREAM_NOFLAGS 0x00000000
  24339. #define MA_PA_STREAM_START_CORKED 0x00000001
  24340. #define MA_PA_STREAM_INTERPOLATE_TIMING 0x00000002
  24341. #define MA_PA_STREAM_NOT_MONOTONIC 0x00000004
  24342. #define MA_PA_STREAM_AUTO_TIMING_UPDATE 0x00000008
  24343. #define MA_PA_STREAM_NO_REMAP_CHANNELS 0x00000010
  24344. #define MA_PA_STREAM_NO_REMIX_CHANNELS 0x00000020
  24345. #define MA_PA_STREAM_FIX_FORMAT 0x00000040
  24346. #define MA_PA_STREAM_FIX_RATE 0x00000080
  24347. #define MA_PA_STREAM_FIX_CHANNELS 0x00000100
  24348. #define MA_PA_STREAM_DONT_MOVE 0x00000200
  24349. #define MA_PA_STREAM_VARIABLE_RATE 0x00000400
  24350. #define MA_PA_STREAM_PEAK_DETECT 0x00000800
  24351. #define MA_PA_STREAM_START_MUTED 0x00001000
  24352. #define MA_PA_STREAM_ADJUST_LATENCY 0x00002000
  24353. #define MA_PA_STREAM_EARLY_REQUESTS 0x00004000
  24354. #define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND 0x00008000
  24355. #define MA_PA_STREAM_START_UNMUTED 0x00010000
  24356. #define MA_PA_STREAM_FAIL_ON_SUSPEND 0x00020000
  24357. #define MA_PA_STREAM_RELATIVE_VOLUME 0x00040000
  24358. #define MA_PA_STREAM_PASSTHROUGH 0x00080000
  24359. typedef int ma_pa_sink_flags_t;
  24360. #define MA_PA_SINK_NOFLAGS 0x00000000
  24361. #define MA_PA_SINK_HW_VOLUME_CTRL 0x00000001
  24362. #define MA_PA_SINK_LATENCY 0x00000002
  24363. #define MA_PA_SINK_HARDWARE 0x00000004
  24364. #define MA_PA_SINK_NETWORK 0x00000008
  24365. #define MA_PA_SINK_HW_MUTE_CTRL 0x00000010
  24366. #define MA_PA_SINK_DECIBEL_VOLUME 0x00000020
  24367. #define MA_PA_SINK_FLAT_VOLUME 0x00000040
  24368. #define MA_PA_SINK_DYNAMIC_LATENCY 0x00000080
  24369. #define MA_PA_SINK_SET_FORMATS 0x00000100
  24370. typedef int ma_pa_source_flags_t;
  24371. #define MA_PA_SOURCE_NOFLAGS 0x00000000
  24372. #define MA_PA_SOURCE_HW_VOLUME_CTRL 0x00000001
  24373. #define MA_PA_SOURCE_LATENCY 0x00000002
  24374. #define MA_PA_SOURCE_HARDWARE 0x00000004
  24375. #define MA_PA_SOURCE_NETWORK 0x00000008
  24376. #define MA_PA_SOURCE_HW_MUTE_CTRL 0x00000010
  24377. #define MA_PA_SOURCE_DECIBEL_VOLUME 0x00000020
  24378. #define MA_PA_SOURCE_DYNAMIC_LATENCY 0x00000040
  24379. #define MA_PA_SOURCE_FLAT_VOLUME 0x00000080
  24380. typedef int ma_pa_context_state_t;
  24381. #define MA_PA_CONTEXT_UNCONNECTED 0
  24382. #define MA_PA_CONTEXT_CONNECTING 1
  24383. #define MA_PA_CONTEXT_AUTHORIZING 2
  24384. #define MA_PA_CONTEXT_SETTING_NAME 3
  24385. #define MA_PA_CONTEXT_READY 4
  24386. #define MA_PA_CONTEXT_FAILED 5
  24387. #define MA_PA_CONTEXT_TERMINATED 6
  24388. typedef int ma_pa_stream_state_t;
  24389. #define MA_PA_STREAM_UNCONNECTED 0
  24390. #define MA_PA_STREAM_CREATING 1
  24391. #define MA_PA_STREAM_READY 2
  24392. #define MA_PA_STREAM_FAILED 3
  24393. #define MA_PA_STREAM_TERMINATED 4
  24394. typedef int ma_pa_operation_state_t;
  24395. #define MA_PA_OPERATION_RUNNING 0
  24396. #define MA_PA_OPERATION_DONE 1
  24397. #define MA_PA_OPERATION_CANCELLED 2
  24398. typedef int ma_pa_sink_state_t;
  24399. #define MA_PA_SINK_INVALID_STATE -1
  24400. #define MA_PA_SINK_RUNNING 0
  24401. #define MA_PA_SINK_IDLE 1
  24402. #define MA_PA_SINK_SUSPENDED 2
  24403. typedef int ma_pa_source_state_t;
  24404. #define MA_PA_SOURCE_INVALID_STATE -1
  24405. #define MA_PA_SOURCE_RUNNING 0
  24406. #define MA_PA_SOURCE_IDLE 1
  24407. #define MA_PA_SOURCE_SUSPENDED 2
  24408. typedef int ma_pa_seek_mode_t;
  24409. #define MA_PA_SEEK_RELATIVE 0
  24410. #define MA_PA_SEEK_ABSOLUTE 1
  24411. #define MA_PA_SEEK_RELATIVE_ON_READ 2
  24412. #define MA_PA_SEEK_RELATIVE_END 3
  24413. typedef int ma_pa_channel_position_t;
  24414. #define MA_PA_CHANNEL_POSITION_INVALID -1
  24415. #define MA_PA_CHANNEL_POSITION_MONO 0
  24416. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT 1
  24417. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT 2
  24418. #define MA_PA_CHANNEL_POSITION_FRONT_CENTER 3
  24419. #define MA_PA_CHANNEL_POSITION_REAR_CENTER 4
  24420. #define MA_PA_CHANNEL_POSITION_REAR_LEFT 5
  24421. #define MA_PA_CHANNEL_POSITION_REAR_RIGHT 6
  24422. #define MA_PA_CHANNEL_POSITION_LFE 7
  24423. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER 8
  24424. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER 9
  24425. #define MA_PA_CHANNEL_POSITION_SIDE_LEFT 10
  24426. #define MA_PA_CHANNEL_POSITION_SIDE_RIGHT 11
  24427. #define MA_PA_CHANNEL_POSITION_AUX0 12
  24428. #define MA_PA_CHANNEL_POSITION_AUX1 13
  24429. #define MA_PA_CHANNEL_POSITION_AUX2 14
  24430. #define MA_PA_CHANNEL_POSITION_AUX3 15
  24431. #define MA_PA_CHANNEL_POSITION_AUX4 16
  24432. #define MA_PA_CHANNEL_POSITION_AUX5 17
  24433. #define MA_PA_CHANNEL_POSITION_AUX6 18
  24434. #define MA_PA_CHANNEL_POSITION_AUX7 19
  24435. #define MA_PA_CHANNEL_POSITION_AUX8 20
  24436. #define MA_PA_CHANNEL_POSITION_AUX9 21
  24437. #define MA_PA_CHANNEL_POSITION_AUX10 22
  24438. #define MA_PA_CHANNEL_POSITION_AUX11 23
  24439. #define MA_PA_CHANNEL_POSITION_AUX12 24
  24440. #define MA_PA_CHANNEL_POSITION_AUX13 25
  24441. #define MA_PA_CHANNEL_POSITION_AUX14 26
  24442. #define MA_PA_CHANNEL_POSITION_AUX15 27
  24443. #define MA_PA_CHANNEL_POSITION_AUX16 28
  24444. #define MA_PA_CHANNEL_POSITION_AUX17 29
  24445. #define MA_PA_CHANNEL_POSITION_AUX18 30
  24446. #define MA_PA_CHANNEL_POSITION_AUX19 31
  24447. #define MA_PA_CHANNEL_POSITION_AUX20 32
  24448. #define MA_PA_CHANNEL_POSITION_AUX21 33
  24449. #define MA_PA_CHANNEL_POSITION_AUX22 34
  24450. #define MA_PA_CHANNEL_POSITION_AUX23 35
  24451. #define MA_PA_CHANNEL_POSITION_AUX24 36
  24452. #define MA_PA_CHANNEL_POSITION_AUX25 37
  24453. #define MA_PA_CHANNEL_POSITION_AUX26 38
  24454. #define MA_PA_CHANNEL_POSITION_AUX27 39
  24455. #define MA_PA_CHANNEL_POSITION_AUX28 40
  24456. #define MA_PA_CHANNEL_POSITION_AUX29 41
  24457. #define MA_PA_CHANNEL_POSITION_AUX30 42
  24458. #define MA_PA_CHANNEL_POSITION_AUX31 43
  24459. #define MA_PA_CHANNEL_POSITION_TOP_CENTER 44
  24460. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT 45
  24461. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT 46
  24462. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER 47
  24463. #define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT 48
  24464. #define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT 49
  24465. #define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER 50
  24466. #define MA_PA_CHANNEL_POSITION_LEFT MA_PA_CHANNEL_POSITION_FRONT_LEFT
  24467. #define MA_PA_CHANNEL_POSITION_RIGHT MA_PA_CHANNEL_POSITION_FRONT_RIGHT
  24468. #define MA_PA_CHANNEL_POSITION_CENTER MA_PA_CHANNEL_POSITION_FRONT_CENTER
  24469. #define MA_PA_CHANNEL_POSITION_SUBWOOFER MA_PA_CHANNEL_POSITION_LFE
  24470. typedef int ma_pa_channel_map_def_t;
  24471. #define MA_PA_CHANNEL_MAP_AIFF 0
  24472. #define MA_PA_CHANNEL_MAP_ALSA 1
  24473. #define MA_PA_CHANNEL_MAP_AUX 2
  24474. #define MA_PA_CHANNEL_MAP_WAVEEX 3
  24475. #define MA_PA_CHANNEL_MAP_OSS 4
  24476. #define MA_PA_CHANNEL_MAP_DEFAULT MA_PA_CHANNEL_MAP_AIFF
  24477. typedef int ma_pa_sample_format_t;
  24478. #define MA_PA_SAMPLE_INVALID -1
  24479. #define MA_PA_SAMPLE_U8 0
  24480. #define MA_PA_SAMPLE_ALAW 1
  24481. #define MA_PA_SAMPLE_ULAW 2
  24482. #define MA_PA_SAMPLE_S16LE 3
  24483. #define MA_PA_SAMPLE_S16BE 4
  24484. #define MA_PA_SAMPLE_FLOAT32LE 5
  24485. #define MA_PA_SAMPLE_FLOAT32BE 6
  24486. #define MA_PA_SAMPLE_S32LE 7
  24487. #define MA_PA_SAMPLE_S32BE 8
  24488. #define MA_PA_SAMPLE_S24LE 9
  24489. #define MA_PA_SAMPLE_S24BE 10
  24490. #define MA_PA_SAMPLE_S24_32LE 11
  24491. #define MA_PA_SAMPLE_S24_32BE 12
  24492. typedef struct ma_pa_mainloop ma_pa_mainloop;
  24493. typedef struct ma_pa_threaded_mainloop ma_pa_threaded_mainloop;
  24494. typedef struct ma_pa_mainloop_api ma_pa_mainloop_api;
  24495. typedef struct ma_pa_context ma_pa_context;
  24496. typedef struct ma_pa_operation ma_pa_operation;
  24497. typedef struct ma_pa_stream ma_pa_stream;
  24498. typedef struct ma_pa_spawn_api ma_pa_spawn_api;
  24499. typedef struct
  24500. {
  24501. ma_uint32 maxlength;
  24502. ma_uint32 tlength;
  24503. ma_uint32 prebuf;
  24504. ma_uint32 minreq;
  24505. ma_uint32 fragsize;
  24506. } ma_pa_buffer_attr;
  24507. typedef struct
  24508. {
  24509. ma_uint8 channels;
  24510. ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX];
  24511. } ma_pa_channel_map;
  24512. typedef struct
  24513. {
  24514. ma_uint8 channels;
  24515. ma_uint32 values[MA_PA_CHANNELS_MAX];
  24516. } ma_pa_cvolume;
  24517. typedef struct
  24518. {
  24519. ma_pa_sample_format_t format;
  24520. ma_uint32 rate;
  24521. ma_uint8 channels;
  24522. } ma_pa_sample_spec;
  24523. typedef struct
  24524. {
  24525. const char* name;
  24526. ma_uint32 index;
  24527. const char* description;
  24528. ma_pa_sample_spec sample_spec;
  24529. ma_pa_channel_map channel_map;
  24530. ma_uint32 owner_module;
  24531. ma_pa_cvolume volume;
  24532. int mute;
  24533. ma_uint32 monitor_source;
  24534. const char* monitor_source_name;
  24535. ma_uint64 latency;
  24536. const char* driver;
  24537. ma_pa_sink_flags_t flags;
  24538. void* proplist;
  24539. ma_uint64 configured_latency;
  24540. ma_uint32 base_volume;
  24541. ma_pa_sink_state_t state;
  24542. ma_uint32 n_volume_steps;
  24543. ma_uint32 card;
  24544. ma_uint32 n_ports;
  24545. void** ports;
  24546. void* active_port;
  24547. ma_uint8 n_formats;
  24548. void** formats;
  24549. } ma_pa_sink_info;
  24550. typedef struct
  24551. {
  24552. const char *name;
  24553. ma_uint32 index;
  24554. const char *description;
  24555. ma_pa_sample_spec sample_spec;
  24556. ma_pa_channel_map channel_map;
  24557. ma_uint32 owner_module;
  24558. ma_pa_cvolume volume;
  24559. int mute;
  24560. ma_uint32 monitor_of_sink;
  24561. const char *monitor_of_sink_name;
  24562. ma_uint64 latency;
  24563. const char *driver;
  24564. ma_pa_source_flags_t flags;
  24565. void* proplist;
  24566. ma_uint64 configured_latency;
  24567. ma_uint32 base_volume;
  24568. ma_pa_source_state_t state;
  24569. ma_uint32 n_volume_steps;
  24570. ma_uint32 card;
  24571. ma_uint32 n_ports;
  24572. void** ports;
  24573. void* active_port;
  24574. ma_uint8 n_formats;
  24575. void** formats;
  24576. } ma_pa_source_info;
  24577. typedef void (* ma_pa_context_notify_cb_t)(ma_pa_context* c, void* userdata);
  24578. typedef void (* ma_pa_sink_info_cb_t) (ma_pa_context* c, const ma_pa_sink_info* i, int eol, void* userdata);
  24579. typedef void (* ma_pa_source_info_cb_t) (ma_pa_context* c, const ma_pa_source_info* i, int eol, void* userdata);
  24580. typedef void (* ma_pa_stream_success_cb_t)(ma_pa_stream* s, int success, void* userdata);
  24581. typedef void (* ma_pa_stream_request_cb_t)(ma_pa_stream* s, size_t nbytes, void* userdata);
  24582. typedef void (* ma_pa_stream_notify_cb_t) (ma_pa_stream* s, void* userdata);
  24583. typedef void (* ma_pa_free_cb_t) (void* p);
  24584. #endif
  24585. typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (void);
  24586. typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m);
  24587. typedef void (* ma_pa_mainloop_quit_proc) (ma_pa_mainloop* m, int retval);
  24588. typedef ma_pa_mainloop_api* (* ma_pa_mainloop_get_api_proc) (ma_pa_mainloop* m);
  24589. typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval);
  24590. typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m);
  24591. typedef ma_pa_threaded_mainloop* (* ma_pa_threaded_mainloop_new_proc) (void);
  24592. typedef void (* ma_pa_threaded_mainloop_free_proc) (ma_pa_threaded_mainloop* m);
  24593. typedef int (* ma_pa_threaded_mainloop_start_proc) (ma_pa_threaded_mainloop* m);
  24594. typedef void (* ma_pa_threaded_mainloop_stop_proc) (ma_pa_threaded_mainloop* m);
  24595. typedef void (* ma_pa_threaded_mainloop_lock_proc) (ma_pa_threaded_mainloop* m);
  24596. typedef void (* ma_pa_threaded_mainloop_unlock_proc) (ma_pa_threaded_mainloop* m);
  24597. typedef void (* ma_pa_threaded_mainloop_wait_proc) (ma_pa_threaded_mainloop* m);
  24598. typedef void (* ma_pa_threaded_mainloop_signal_proc) (ma_pa_threaded_mainloop* m, int wait_for_accept);
  24599. typedef void (* ma_pa_threaded_mainloop_accept_proc) (ma_pa_threaded_mainloop* m);
  24600. typedef int (* ma_pa_threaded_mainloop_get_retval_proc) (ma_pa_threaded_mainloop* m);
  24601. typedef ma_pa_mainloop_api* (* ma_pa_threaded_mainloop_get_api_proc) (ma_pa_threaded_mainloop* m);
  24602. typedef int (* ma_pa_threaded_mainloop_in_thread_proc) (ma_pa_threaded_mainloop* m);
  24603. typedef void (* ma_pa_threaded_mainloop_set_name_proc) (ma_pa_threaded_mainloop* m, const char* name);
  24604. typedef ma_pa_context* (* ma_pa_context_new_proc) (ma_pa_mainloop_api* mainloop, const char* name);
  24605. typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c);
  24606. 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);
  24607. typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c);
  24608. typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata);
  24609. typedef ma_pa_context_state_t (* ma_pa_context_get_state_proc) (ma_pa_context* c);
  24610. 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);
  24611. 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);
  24612. 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);
  24613. 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);
  24614. typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o);
  24615. typedef ma_pa_operation_state_t (* ma_pa_operation_get_state_proc) (ma_pa_operation* o);
  24616. 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);
  24617. typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m);
  24618. typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss);
  24619. 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);
  24620. typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s);
  24621. 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);
  24622. 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);
  24623. typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s);
  24624. typedef ma_pa_stream_state_t (* ma_pa_stream_get_state_proc) (ma_pa_stream* s);
  24625. typedef const ma_pa_sample_spec* (* ma_pa_stream_get_sample_spec_proc) (ma_pa_stream* s);
  24626. typedef const ma_pa_channel_map* (* ma_pa_stream_get_channel_map_proc) (ma_pa_stream* s);
  24627. typedef const ma_pa_buffer_attr* (* ma_pa_stream_get_buffer_attr_proc) (ma_pa_stream* s);
  24628. 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);
  24629. typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s);
  24630. typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
  24631. typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
  24632. typedef void (* ma_pa_stream_set_suspended_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata);
  24633. typedef void (* ma_pa_stream_set_moved_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata);
  24634. typedef int (* ma_pa_stream_is_suspended_proc) (const ma_pa_stream* s);
  24635. typedef ma_pa_operation* (* ma_pa_stream_flush_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  24636. typedef ma_pa_operation* (* ma_pa_stream_drain_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  24637. typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s);
  24638. typedef ma_pa_operation* (* ma_pa_stream_cork_proc) (ma_pa_stream* s, int b, ma_pa_stream_success_cb_t cb, void* userdata);
  24639. typedef ma_pa_operation* (* ma_pa_stream_trigger_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  24640. typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes);
  24641. 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);
  24642. typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes);
  24643. typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s);
  24644. typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s);
  24645. typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s);
  24646. typedef struct
  24647. {
  24648. ma_uint32 count;
  24649. ma_uint32 capacity;
  24650. ma_device_info* pInfo;
  24651. } ma_pulse_device_enum_data;
  24652. static ma_result ma_result_from_pulse(int result)
  24653. {
  24654. if (result < 0) {
  24655. return MA_ERROR;
  24656. }
  24657. switch (result) {
  24658. case MA_PA_OK: return MA_SUCCESS;
  24659. case MA_PA_ERR_ACCESS: return MA_ACCESS_DENIED;
  24660. case MA_PA_ERR_INVALID: return MA_INVALID_ARGS;
  24661. case MA_PA_ERR_NOENTITY: return MA_NO_DEVICE;
  24662. default: return MA_ERROR;
  24663. }
  24664. }
  24665. #if 0
  24666. static ma_pa_sample_format_t ma_format_to_pulse(ma_format format)
  24667. {
  24668. if (ma_is_little_endian()) {
  24669. switch (format) {
  24670. case ma_format_s16: return MA_PA_SAMPLE_S16LE;
  24671. case ma_format_s24: return MA_PA_SAMPLE_S24LE;
  24672. case ma_format_s32: return MA_PA_SAMPLE_S32LE;
  24673. case ma_format_f32: return MA_PA_SAMPLE_FLOAT32LE;
  24674. default: break;
  24675. }
  24676. } else {
  24677. switch (format) {
  24678. case ma_format_s16: return MA_PA_SAMPLE_S16BE;
  24679. case ma_format_s24: return MA_PA_SAMPLE_S24BE;
  24680. case ma_format_s32: return MA_PA_SAMPLE_S32BE;
  24681. case ma_format_f32: return MA_PA_SAMPLE_FLOAT32BE;
  24682. default: break;
  24683. }
  24684. }
  24685. /* Endian agnostic. */
  24686. switch (format) {
  24687. case ma_format_u8: return MA_PA_SAMPLE_U8;
  24688. default: return MA_PA_SAMPLE_INVALID;
  24689. }
  24690. }
  24691. #endif
  24692. static ma_format ma_format_from_pulse(ma_pa_sample_format_t format)
  24693. {
  24694. if (ma_is_little_endian()) {
  24695. switch (format) {
  24696. case MA_PA_SAMPLE_S16LE: return ma_format_s16;
  24697. case MA_PA_SAMPLE_S24LE: return ma_format_s24;
  24698. case MA_PA_SAMPLE_S32LE: return ma_format_s32;
  24699. case MA_PA_SAMPLE_FLOAT32LE: return ma_format_f32;
  24700. default: break;
  24701. }
  24702. } else {
  24703. switch (format) {
  24704. case MA_PA_SAMPLE_S16BE: return ma_format_s16;
  24705. case MA_PA_SAMPLE_S24BE: return ma_format_s24;
  24706. case MA_PA_SAMPLE_S32BE: return ma_format_s32;
  24707. case MA_PA_SAMPLE_FLOAT32BE: return ma_format_f32;
  24708. default: break;
  24709. }
  24710. }
  24711. /* Endian agnostic. */
  24712. switch (format) {
  24713. case MA_PA_SAMPLE_U8: return ma_format_u8;
  24714. default: return ma_format_unknown;
  24715. }
  24716. }
  24717. static ma_channel ma_channel_position_from_pulse(ma_pa_channel_position_t position)
  24718. {
  24719. switch (position)
  24720. {
  24721. case MA_PA_CHANNEL_POSITION_INVALID: return MA_CHANNEL_NONE;
  24722. case MA_PA_CHANNEL_POSITION_MONO: return MA_CHANNEL_MONO;
  24723. case MA_PA_CHANNEL_POSITION_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  24724. case MA_PA_CHANNEL_POSITION_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  24725. case MA_PA_CHANNEL_POSITION_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  24726. case MA_PA_CHANNEL_POSITION_REAR_CENTER: return MA_CHANNEL_BACK_CENTER;
  24727. case MA_PA_CHANNEL_POSITION_REAR_LEFT: return MA_CHANNEL_BACK_LEFT;
  24728. case MA_PA_CHANNEL_POSITION_REAR_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  24729. case MA_PA_CHANNEL_POSITION_LFE: return MA_CHANNEL_LFE;
  24730. case MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  24731. case MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  24732. case MA_PA_CHANNEL_POSITION_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  24733. case MA_PA_CHANNEL_POSITION_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  24734. case MA_PA_CHANNEL_POSITION_AUX0: return MA_CHANNEL_AUX_0;
  24735. case MA_PA_CHANNEL_POSITION_AUX1: return MA_CHANNEL_AUX_1;
  24736. case MA_PA_CHANNEL_POSITION_AUX2: return MA_CHANNEL_AUX_2;
  24737. case MA_PA_CHANNEL_POSITION_AUX3: return MA_CHANNEL_AUX_3;
  24738. case MA_PA_CHANNEL_POSITION_AUX4: return MA_CHANNEL_AUX_4;
  24739. case MA_PA_CHANNEL_POSITION_AUX5: return MA_CHANNEL_AUX_5;
  24740. case MA_PA_CHANNEL_POSITION_AUX6: return MA_CHANNEL_AUX_6;
  24741. case MA_PA_CHANNEL_POSITION_AUX7: return MA_CHANNEL_AUX_7;
  24742. case MA_PA_CHANNEL_POSITION_AUX8: return MA_CHANNEL_AUX_8;
  24743. case MA_PA_CHANNEL_POSITION_AUX9: return MA_CHANNEL_AUX_9;
  24744. case MA_PA_CHANNEL_POSITION_AUX10: return MA_CHANNEL_AUX_10;
  24745. case MA_PA_CHANNEL_POSITION_AUX11: return MA_CHANNEL_AUX_11;
  24746. case MA_PA_CHANNEL_POSITION_AUX12: return MA_CHANNEL_AUX_12;
  24747. case MA_PA_CHANNEL_POSITION_AUX13: return MA_CHANNEL_AUX_13;
  24748. case MA_PA_CHANNEL_POSITION_AUX14: return MA_CHANNEL_AUX_14;
  24749. case MA_PA_CHANNEL_POSITION_AUX15: return MA_CHANNEL_AUX_15;
  24750. case MA_PA_CHANNEL_POSITION_AUX16: return MA_CHANNEL_AUX_16;
  24751. case MA_PA_CHANNEL_POSITION_AUX17: return MA_CHANNEL_AUX_17;
  24752. case MA_PA_CHANNEL_POSITION_AUX18: return MA_CHANNEL_AUX_18;
  24753. case MA_PA_CHANNEL_POSITION_AUX19: return MA_CHANNEL_AUX_19;
  24754. case MA_PA_CHANNEL_POSITION_AUX20: return MA_CHANNEL_AUX_20;
  24755. case MA_PA_CHANNEL_POSITION_AUX21: return MA_CHANNEL_AUX_21;
  24756. case MA_PA_CHANNEL_POSITION_AUX22: return MA_CHANNEL_AUX_22;
  24757. case MA_PA_CHANNEL_POSITION_AUX23: return MA_CHANNEL_AUX_23;
  24758. case MA_PA_CHANNEL_POSITION_AUX24: return MA_CHANNEL_AUX_24;
  24759. case MA_PA_CHANNEL_POSITION_AUX25: return MA_CHANNEL_AUX_25;
  24760. case MA_PA_CHANNEL_POSITION_AUX26: return MA_CHANNEL_AUX_26;
  24761. case MA_PA_CHANNEL_POSITION_AUX27: return MA_CHANNEL_AUX_27;
  24762. case MA_PA_CHANNEL_POSITION_AUX28: return MA_CHANNEL_AUX_28;
  24763. case MA_PA_CHANNEL_POSITION_AUX29: return MA_CHANNEL_AUX_29;
  24764. case MA_PA_CHANNEL_POSITION_AUX30: return MA_CHANNEL_AUX_30;
  24765. case MA_PA_CHANNEL_POSITION_AUX31: return MA_CHANNEL_AUX_31;
  24766. case MA_PA_CHANNEL_POSITION_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  24767. case MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  24768. case MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  24769. case MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  24770. case MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  24771. case MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  24772. case MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  24773. default: return MA_CHANNEL_NONE;
  24774. }
  24775. }
  24776. #if 0
  24777. static ma_pa_channel_position_t ma_channel_position_to_pulse(ma_channel position)
  24778. {
  24779. switch (position)
  24780. {
  24781. case MA_CHANNEL_NONE: return MA_PA_CHANNEL_POSITION_INVALID;
  24782. case MA_CHANNEL_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_FRONT_LEFT;
  24783. case MA_CHANNEL_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT;
  24784. case MA_CHANNEL_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_CENTER;
  24785. case MA_CHANNEL_LFE: return MA_PA_CHANNEL_POSITION_LFE;
  24786. case MA_CHANNEL_BACK_LEFT: return MA_PA_CHANNEL_POSITION_REAR_LEFT;
  24787. case MA_CHANNEL_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_REAR_RIGHT;
  24788. case MA_CHANNEL_FRONT_LEFT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
  24789. case MA_CHANNEL_FRONT_RIGHT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
  24790. case MA_CHANNEL_BACK_CENTER: return MA_PA_CHANNEL_POSITION_REAR_CENTER;
  24791. case MA_CHANNEL_SIDE_LEFT: return MA_PA_CHANNEL_POSITION_SIDE_LEFT;
  24792. case MA_CHANNEL_SIDE_RIGHT: return MA_PA_CHANNEL_POSITION_SIDE_RIGHT;
  24793. case MA_CHANNEL_TOP_CENTER: return MA_PA_CHANNEL_POSITION_TOP_CENTER;
  24794. case MA_CHANNEL_TOP_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT;
  24795. case MA_CHANNEL_TOP_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER;
  24796. case MA_CHANNEL_TOP_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT;
  24797. case MA_CHANNEL_TOP_BACK_LEFT: return MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT;
  24798. case MA_CHANNEL_TOP_BACK_CENTER: return MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER;
  24799. case MA_CHANNEL_TOP_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
  24800. case MA_CHANNEL_19: return MA_PA_CHANNEL_POSITION_AUX18;
  24801. case MA_CHANNEL_20: return MA_PA_CHANNEL_POSITION_AUX19;
  24802. case MA_CHANNEL_21: return MA_PA_CHANNEL_POSITION_AUX20;
  24803. case MA_CHANNEL_22: return MA_PA_CHANNEL_POSITION_AUX21;
  24804. case MA_CHANNEL_23: return MA_PA_CHANNEL_POSITION_AUX22;
  24805. case MA_CHANNEL_24: return MA_PA_CHANNEL_POSITION_AUX23;
  24806. case MA_CHANNEL_25: return MA_PA_CHANNEL_POSITION_AUX24;
  24807. case MA_CHANNEL_26: return MA_PA_CHANNEL_POSITION_AUX25;
  24808. case MA_CHANNEL_27: return MA_PA_CHANNEL_POSITION_AUX26;
  24809. case MA_CHANNEL_28: return MA_PA_CHANNEL_POSITION_AUX27;
  24810. case MA_CHANNEL_29: return MA_PA_CHANNEL_POSITION_AUX28;
  24811. case MA_CHANNEL_30: return MA_PA_CHANNEL_POSITION_AUX29;
  24812. case MA_CHANNEL_31: return MA_PA_CHANNEL_POSITION_AUX30;
  24813. case MA_CHANNEL_32: return MA_PA_CHANNEL_POSITION_AUX31;
  24814. default: return (ma_pa_channel_position_t)position;
  24815. }
  24816. }
  24817. #endif
  24818. static ma_result ma_wait_for_operation__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP)
  24819. {
  24820. int resultPA;
  24821. ma_pa_operation_state_t state;
  24822. MA_ASSERT(pContext != NULL);
  24823. MA_ASSERT(pOP != NULL);
  24824. for (;;) {
  24825. state = ((ma_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP);
  24826. if (state != MA_PA_OPERATION_RUNNING) {
  24827. break; /* Done. */
  24828. }
  24829. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  24830. if (resultPA < 0) {
  24831. return ma_result_from_pulse(resultPA);
  24832. }
  24833. }
  24834. return MA_SUCCESS;
  24835. }
  24836. static ma_result ma_wait_for_operation_and_unref__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP)
  24837. {
  24838. ma_result result;
  24839. if (pOP == NULL) {
  24840. return MA_INVALID_ARGS;
  24841. }
  24842. result = ma_wait_for_operation__pulse(pContext, pMainLoop, pOP);
  24843. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  24844. return result;
  24845. }
  24846. static ma_result ma_wait_for_pa_context_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pPulseContext)
  24847. {
  24848. int resultPA;
  24849. ma_pa_context_state_t state;
  24850. for (;;) {
  24851. state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)((ma_pa_context*)pPulseContext);
  24852. if (state == MA_PA_CONTEXT_READY) {
  24853. break; /* Done. */
  24854. }
  24855. if (state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) {
  24856. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.");
  24857. return MA_ERROR;
  24858. }
  24859. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  24860. if (resultPA < 0) {
  24861. return ma_result_from_pulse(resultPA);
  24862. }
  24863. }
  24864. /* Should never get here. */
  24865. return MA_SUCCESS;
  24866. }
  24867. static ma_result ma_wait_for_pa_stream_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pStream)
  24868. {
  24869. int resultPA;
  24870. ma_pa_stream_state_t state;
  24871. for (;;) {
  24872. state = ((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pStream);
  24873. if (state == MA_PA_STREAM_READY) {
  24874. break; /* Done. */
  24875. }
  24876. if (state == MA_PA_STREAM_FAILED || state == MA_PA_STREAM_TERMINATED) {
  24877. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio stream.");
  24878. return MA_ERROR;
  24879. }
  24880. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  24881. if (resultPA < 0) {
  24882. return ma_result_from_pulse(resultPA);
  24883. }
  24884. }
  24885. return MA_SUCCESS;
  24886. }
  24887. 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)
  24888. {
  24889. ma_result result;
  24890. ma_ptr pMainLoop;
  24891. ma_ptr pPulseContext;
  24892. MA_ASSERT(ppMainLoop != NULL);
  24893. MA_ASSERT(ppPulseContext != NULL);
  24894. /* 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. */
  24895. pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)();
  24896. if (pMainLoop == NULL) {
  24897. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create mainloop.");
  24898. return MA_FAILED_TO_INIT_BACKEND;
  24899. }
  24900. 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);
  24901. if (pPulseContext == NULL) {
  24902. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context.");
  24903. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24904. return MA_FAILED_TO_INIT_BACKEND;
  24905. }
  24906. /* Now we need to connect to the context. Everything is asynchronous so we need to wait for it to connect before returning. */
  24907. 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));
  24908. if (result != MA_SUCCESS) {
  24909. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.");
  24910. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24911. return result;
  24912. }
  24913. /* Since ma_context_init() runs synchronously we need to wait for the PulseAudio context to connect before we return. */
  24914. result = ma_wait_for_pa_context_to_connect__pulse(pContext, pMainLoop, pPulseContext);
  24915. if (result != MA_SUCCESS) {
  24916. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Waiting for connection failed.");
  24917. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24918. return result;
  24919. }
  24920. *ppMainLoop = pMainLoop;
  24921. *ppPulseContext = pPulseContext;
  24922. return MA_SUCCESS;
  24923. }
  24924. static void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24925. {
  24926. ma_pa_sink_info* pInfoOut;
  24927. if (endOfList > 0) {
  24928. return;
  24929. }
  24930. /*
  24931. There has been a report that indicates that pInfo can be null which results
  24932. in a null pointer dereference below. We'll check for this for safety.
  24933. */
  24934. if (pInfo == NULL) {
  24935. return;
  24936. }
  24937. pInfoOut = (ma_pa_sink_info*)pUserData;
  24938. MA_ASSERT(pInfoOut != NULL);
  24939. *pInfoOut = *pInfo;
  24940. (void)pPulseContext; /* Unused. */
  24941. }
  24942. static void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24943. {
  24944. ma_pa_source_info* pInfoOut;
  24945. if (endOfList > 0) {
  24946. return;
  24947. }
  24948. /*
  24949. There has been a report that indicates that pInfo can be null which results
  24950. in a null pointer dereference below. We'll check for this for safety.
  24951. */
  24952. if (pInfo == NULL) {
  24953. return;
  24954. }
  24955. pInfoOut = (ma_pa_source_info*)pUserData;
  24956. MA_ASSERT(pInfoOut != NULL);
  24957. *pInfoOut = *pInfo;
  24958. (void)pPulseContext; /* Unused. */
  24959. }
  24960. #if 0
  24961. static void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24962. {
  24963. ma_device* pDevice;
  24964. if (endOfList > 0) {
  24965. return;
  24966. }
  24967. pDevice = (ma_device*)pUserData;
  24968. MA_ASSERT(pDevice != NULL);
  24969. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), pInfo->description, (size_t)-1);
  24970. (void)pPulseContext; /* Unused. */
  24971. }
  24972. static void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24973. {
  24974. ma_device* pDevice;
  24975. if (endOfList > 0) {
  24976. return;
  24977. }
  24978. pDevice = (ma_device*)pUserData;
  24979. MA_ASSERT(pDevice != NULL);
  24980. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), pInfo->description, (size_t)-1);
  24981. (void)pPulseContext; /* Unused. */
  24982. }
  24983. #endif
  24984. static ma_result ma_context_get_sink_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_sink_info* pSinkInfo)
  24985. {
  24986. ma_pa_operation* pOP;
  24987. 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);
  24988. if (pOP == NULL) {
  24989. return MA_ERROR;
  24990. }
  24991. return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24992. }
  24993. static ma_result ma_context_get_source_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_source_info* pSourceInfo)
  24994. {
  24995. ma_pa_operation* pOP;
  24996. 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);
  24997. if (pOP == NULL) {
  24998. return MA_ERROR;
  24999. }
  25000. return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25001. }
  25002. static ma_result ma_context_get_default_device_index__pulse(ma_context* pContext, ma_device_type deviceType, ma_uint32* pIndex)
  25003. {
  25004. ma_result result;
  25005. MA_ASSERT(pContext != NULL);
  25006. MA_ASSERT(pIndex != NULL);
  25007. if (pIndex != NULL) {
  25008. *pIndex = (ma_uint32)-1;
  25009. }
  25010. if (deviceType == ma_device_type_playback) {
  25011. ma_pa_sink_info sinkInfo;
  25012. result = ma_context_get_sink_info__pulse(pContext, NULL, &sinkInfo);
  25013. if (result != MA_SUCCESS) {
  25014. return result;
  25015. }
  25016. if (pIndex != NULL) {
  25017. *pIndex = sinkInfo.index;
  25018. }
  25019. }
  25020. if (deviceType == ma_device_type_capture) {
  25021. ma_pa_source_info sourceInfo;
  25022. result = ma_context_get_source_info__pulse(pContext, NULL, &sourceInfo);
  25023. if (result != MA_SUCCESS) {
  25024. return result;
  25025. }
  25026. if (pIndex != NULL) {
  25027. *pIndex = sourceInfo.index;
  25028. }
  25029. }
  25030. return MA_SUCCESS;
  25031. }
  25032. typedef struct
  25033. {
  25034. ma_context* pContext;
  25035. ma_enum_devices_callback_proc callback;
  25036. void* pUserData;
  25037. ma_bool32 isTerminated;
  25038. ma_uint32 defaultDeviceIndexPlayback;
  25039. ma_uint32 defaultDeviceIndexCapture;
  25040. } ma_context_enumerate_devices_callback_data__pulse;
  25041. static void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pSinkInfo, int endOfList, void* pUserData)
  25042. {
  25043. ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData;
  25044. ma_device_info deviceInfo;
  25045. MA_ASSERT(pData != NULL);
  25046. if (endOfList || pData->isTerminated) {
  25047. return;
  25048. }
  25049. MA_ZERO_OBJECT(&deviceInfo);
  25050. /* The name from PulseAudio is the ID for miniaudio. */
  25051. if (pSinkInfo->name != NULL) {
  25052. ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1);
  25053. }
  25054. /* The description from PulseAudio is the name for miniaudio. */
  25055. if (pSinkInfo->description != NULL) {
  25056. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1);
  25057. }
  25058. if (pSinkInfo->index == pData->defaultDeviceIndexPlayback) {
  25059. deviceInfo.isDefault = MA_TRUE;
  25060. }
  25061. pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_playback, &deviceInfo, pData->pUserData);
  25062. (void)pPulseContext; /* Unused. */
  25063. }
  25064. static void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSourceInfo, int endOfList, void* pUserData)
  25065. {
  25066. ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData;
  25067. ma_device_info deviceInfo;
  25068. MA_ASSERT(pData != NULL);
  25069. if (endOfList || pData->isTerminated) {
  25070. return;
  25071. }
  25072. MA_ZERO_OBJECT(&deviceInfo);
  25073. /* The name from PulseAudio is the ID for miniaudio. */
  25074. if (pSourceInfo->name != NULL) {
  25075. ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSourceInfo->name, (size_t)-1);
  25076. }
  25077. /* The description from PulseAudio is the name for miniaudio. */
  25078. if (pSourceInfo->description != NULL) {
  25079. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSourceInfo->description, (size_t)-1);
  25080. }
  25081. if (pSourceInfo->index == pData->defaultDeviceIndexCapture) {
  25082. deviceInfo.isDefault = MA_TRUE;
  25083. }
  25084. pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_capture, &deviceInfo, pData->pUserData);
  25085. (void)pPulseContext; /* Unused. */
  25086. }
  25087. static ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  25088. {
  25089. ma_result result = MA_SUCCESS;
  25090. ma_context_enumerate_devices_callback_data__pulse callbackData;
  25091. ma_pa_operation* pOP = NULL;
  25092. MA_ASSERT(pContext != NULL);
  25093. MA_ASSERT(callback != NULL);
  25094. callbackData.pContext = pContext;
  25095. callbackData.callback = callback;
  25096. callbackData.pUserData = pUserData;
  25097. callbackData.isTerminated = MA_FALSE;
  25098. callbackData.defaultDeviceIndexPlayback = (ma_uint32)-1;
  25099. callbackData.defaultDeviceIndexCapture = (ma_uint32)-1;
  25100. /* We need to get the index of the default devices. */
  25101. ma_context_get_default_device_index__pulse(pContext, ma_device_type_playback, &callbackData.defaultDeviceIndexPlayback);
  25102. ma_context_get_default_device_index__pulse(pContext, ma_device_type_capture, &callbackData.defaultDeviceIndexCapture);
  25103. /* Playback. */
  25104. if (!callbackData.isTerminated) {
  25105. 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);
  25106. if (pOP == NULL) {
  25107. result = MA_ERROR;
  25108. goto done;
  25109. }
  25110. result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25111. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  25112. if (result != MA_SUCCESS) {
  25113. goto done;
  25114. }
  25115. }
  25116. /* Capture. */
  25117. if (!callbackData.isTerminated) {
  25118. 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);
  25119. if (pOP == NULL) {
  25120. result = MA_ERROR;
  25121. goto done;
  25122. }
  25123. result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25124. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  25125. if (result != MA_SUCCESS) {
  25126. goto done;
  25127. }
  25128. }
  25129. done:
  25130. return result;
  25131. }
  25132. typedef struct
  25133. {
  25134. ma_device_info* pDeviceInfo;
  25135. ma_uint32 defaultDeviceIndex;
  25136. ma_bool32 foundDevice;
  25137. } ma_context_get_device_info_callback_data__pulse;
  25138. static void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  25139. {
  25140. ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData;
  25141. if (endOfList > 0) {
  25142. return;
  25143. }
  25144. MA_ASSERT(pData != NULL);
  25145. pData->foundDevice = MA_TRUE;
  25146. if (pInfo->name != NULL) {
  25147. ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1);
  25148. }
  25149. if (pInfo->description != NULL) {
  25150. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1);
  25151. }
  25152. /*
  25153. We're just reporting a single data format here. I think technically PulseAudio might support
  25154. all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to
  25155. report the "native" device format.
  25156. */
  25157. pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format);
  25158. pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels;
  25159. pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate;
  25160. pData->pDeviceInfo->nativeDataFormats[0].flags = 0;
  25161. pData->pDeviceInfo->nativeDataFormatCount = 1;
  25162. if (pData->defaultDeviceIndex == pInfo->index) {
  25163. pData->pDeviceInfo->isDefault = MA_TRUE;
  25164. }
  25165. (void)pPulseContext; /* Unused. */
  25166. }
  25167. static void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  25168. {
  25169. ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData;
  25170. if (endOfList > 0) {
  25171. return;
  25172. }
  25173. MA_ASSERT(pData != NULL);
  25174. pData->foundDevice = MA_TRUE;
  25175. if (pInfo->name != NULL) {
  25176. ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1);
  25177. }
  25178. if (pInfo->description != NULL) {
  25179. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1);
  25180. }
  25181. /*
  25182. We're just reporting a single data format here. I think technically PulseAudio might support
  25183. all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to
  25184. report the "native" device format.
  25185. */
  25186. pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format);
  25187. pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels;
  25188. pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate;
  25189. pData->pDeviceInfo->nativeDataFormats[0].flags = 0;
  25190. pData->pDeviceInfo->nativeDataFormatCount = 1;
  25191. if (pData->defaultDeviceIndex == pInfo->index) {
  25192. pData->pDeviceInfo->isDefault = MA_TRUE;
  25193. }
  25194. (void)pPulseContext; /* Unused. */
  25195. }
  25196. 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)
  25197. {
  25198. ma_result result = MA_SUCCESS;
  25199. ma_context_get_device_info_callback_data__pulse callbackData;
  25200. ma_pa_operation* pOP = NULL;
  25201. const char* pDeviceName = NULL;
  25202. MA_ASSERT(pContext != NULL);
  25203. callbackData.pDeviceInfo = pDeviceInfo;
  25204. callbackData.foundDevice = MA_FALSE;
  25205. if (pDeviceID != NULL) {
  25206. pDeviceName = pDeviceID->pulse;
  25207. } else {
  25208. pDeviceName = NULL;
  25209. }
  25210. result = ma_context_get_default_device_index__pulse(pContext, deviceType, &callbackData.defaultDeviceIndex);
  25211. if (deviceType == ma_device_type_playback) {
  25212. 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);
  25213. } else {
  25214. 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);
  25215. }
  25216. if (pOP != NULL) {
  25217. ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  25218. } else {
  25219. result = MA_ERROR;
  25220. goto done;
  25221. }
  25222. if (!callbackData.foundDevice) {
  25223. result = MA_NO_DEVICE;
  25224. goto done;
  25225. }
  25226. done:
  25227. return result;
  25228. }
  25229. static ma_result ma_device_uninit__pulse(ma_device* pDevice)
  25230. {
  25231. ma_context* pContext;
  25232. MA_ASSERT(pDevice != NULL);
  25233. pContext = pDevice->pContext;
  25234. MA_ASSERT(pContext != NULL);
  25235. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25236. ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25237. ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25238. }
  25239. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25240. ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25241. ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25242. }
  25243. if (pDevice->type == ma_device_type_duplex) {
  25244. ma_duplex_rb_uninit(&pDevice->duplexRB);
  25245. }
  25246. ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext);
  25247. ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext);
  25248. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
  25249. return MA_SUCCESS;
  25250. }
  25251. static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss)
  25252. {
  25253. ma_pa_buffer_attr attr;
  25254. attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels);
  25255. attr.tlength = attr.maxlength / periods;
  25256. attr.prebuf = (ma_uint32)-1;
  25257. attr.minreq = (ma_uint32)-1;
  25258. attr.fragsize = attr.maxlength / periods;
  25259. return attr;
  25260. }
  25261. 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)
  25262. {
  25263. static int g_StreamCounter = 0;
  25264. char actualStreamName[256];
  25265. if (pStreamName != NULL) {
  25266. ma_strncpy_s(actualStreamName, sizeof(actualStreamName), pStreamName, (size_t)-1);
  25267. } else {
  25268. ma_strcpy_s(actualStreamName, sizeof(actualStreamName), "miniaudio:");
  25269. ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); /* 8 = strlen("miniaudio:") */
  25270. }
  25271. g_StreamCounter += 1;
  25272. return ((ma_pa_stream_new_proc)pDevice->pContext->pulse.pa_stream_new)((ma_pa_context*)pDevice->pulse.pPulseContext, actualStreamName, ss, cmap);
  25273. }
  25274. static void ma_device_on_read__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData)
  25275. {
  25276. ma_device* pDevice = (ma_device*)pUserData;
  25277. ma_uint32 bpf;
  25278. ma_uint32 deviceState;
  25279. ma_uint64 frameCount;
  25280. ma_uint64 framesProcessed;
  25281. MA_ASSERT(pDevice != NULL);
  25282. /*
  25283. Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio
  25284. can fire this callback before the stream has even started. Ridiculous.
  25285. */
  25286. deviceState = ma_device_get_state(pDevice);
  25287. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  25288. return;
  25289. }
  25290. bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  25291. MA_ASSERT(bpf > 0);
  25292. frameCount = byteCount / bpf;
  25293. framesProcessed = 0;
  25294. while (ma_device_get_state(pDevice) == ma_device_state_started && framesProcessed < frameCount) {
  25295. const void* pMappedPCMFrames;
  25296. size_t bytesMapped;
  25297. ma_uint64 framesMapped;
  25298. int pulseResult = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)(pStream, &pMappedPCMFrames, &bytesMapped);
  25299. if (pulseResult < 0) {
  25300. break; /* Failed to map. Abort. */
  25301. }
  25302. framesMapped = bytesMapped / bpf;
  25303. if (framesMapped > 0) {
  25304. if (pMappedPCMFrames != NULL) {
  25305. ma_device_handle_backend_data_callback(pDevice, NULL, pMappedPCMFrames, framesMapped);
  25306. } else {
  25307. /* It's a hole. */
  25308. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[PulseAudio] ma_device_on_read__pulse: Hole.\n");
  25309. }
  25310. pulseResult = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)(pStream);
  25311. if (pulseResult < 0) {
  25312. break; /* Failed to drop the buffer. */
  25313. }
  25314. framesProcessed += framesMapped;
  25315. } else {
  25316. /* Nothing was mapped. Just abort. */
  25317. break;
  25318. }
  25319. }
  25320. }
  25321. static ma_result ma_device_write_to_stream__pulse(ma_device* pDevice, ma_pa_stream* pStream, ma_uint64* pFramesProcessed)
  25322. {
  25323. ma_result result = MA_SUCCESS;
  25324. ma_uint64 framesProcessed = 0;
  25325. size_t bytesMapped;
  25326. ma_uint32 bpf;
  25327. ma_uint32 deviceState;
  25328. MA_ASSERT(pDevice != NULL);
  25329. MA_ASSERT(pStream != NULL);
  25330. bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  25331. MA_ASSERT(bpf > 0);
  25332. deviceState = ma_device_get_state(pDevice);
  25333. bytesMapped = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)(pStream);
  25334. if (bytesMapped != (size_t)-1) {
  25335. if (bytesMapped > 0) {
  25336. ma_uint64 framesMapped;
  25337. void* pMappedPCMFrames;
  25338. int pulseResult = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)(pStream, &pMappedPCMFrames, &bytesMapped);
  25339. if (pulseResult < 0) {
  25340. result = ma_result_from_pulse(pulseResult);
  25341. goto done;
  25342. }
  25343. framesMapped = bytesMapped / bpf;
  25344. 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. */
  25345. ma_device_handle_backend_data_callback(pDevice, pMappedPCMFrames, NULL, framesMapped);
  25346. } else {
  25347. /* Device is not started. Write silence. */
  25348. ma_silence_pcm_frames(pMappedPCMFrames, framesMapped, pDevice->playback.format, pDevice->playback.channels);
  25349. }
  25350. pulseResult = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)(pStream, pMappedPCMFrames, bytesMapped, NULL, 0, MA_PA_SEEK_RELATIVE);
  25351. if (pulseResult < 0) {
  25352. result = ma_result_from_pulse(pulseResult);
  25353. goto done; /* Failed to write data to stream. */
  25354. }
  25355. framesProcessed += framesMapped;
  25356. } else {
  25357. result = MA_SUCCESS; /* No data available for writing. */
  25358. goto done;
  25359. }
  25360. } else {
  25361. result = MA_ERROR; /* Failed to retrieve the writable size. Abort. */
  25362. goto done;
  25363. }
  25364. done:
  25365. if (pFramesProcessed != NULL) {
  25366. *pFramesProcessed = framesProcessed;
  25367. }
  25368. return result;
  25369. }
  25370. static void ma_device_on_write__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData)
  25371. {
  25372. ma_device* pDevice = (ma_device*)pUserData;
  25373. ma_uint32 bpf;
  25374. ma_uint64 frameCount;
  25375. ma_uint64 framesProcessed;
  25376. ma_uint32 deviceState;
  25377. ma_result result;
  25378. MA_ASSERT(pDevice != NULL);
  25379. /*
  25380. Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio
  25381. can fire this callback before the stream has even started. Ridiculous.
  25382. */
  25383. deviceState = ma_device_get_state(pDevice);
  25384. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  25385. return;
  25386. }
  25387. bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  25388. MA_ASSERT(bpf > 0);
  25389. frameCount = byteCount / bpf;
  25390. framesProcessed = 0;
  25391. while (framesProcessed < frameCount) {
  25392. ma_uint64 framesProcessedThisIteration;
  25393. /* Don't keep trying to process frames if the device isn't started. */
  25394. deviceState = ma_device_get_state(pDevice);
  25395. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  25396. break;
  25397. }
  25398. result = ma_device_write_to_stream__pulse(pDevice, pStream, &framesProcessedThisIteration);
  25399. if (result != MA_SUCCESS) {
  25400. break;
  25401. }
  25402. framesProcessed += framesProcessedThisIteration;
  25403. }
  25404. }
  25405. static void ma_device_on_suspended__pulse(ma_pa_stream* pStream, void* pUserData)
  25406. {
  25407. ma_device* pDevice = (ma_device*)pUserData;
  25408. int suspended;
  25409. (void)pStream;
  25410. suspended = ((ma_pa_stream_is_suspended_proc)pDevice->pContext->pulse.pa_stream_is_suspended)(pStream);
  25411. 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);
  25412. if (suspended < 0) {
  25413. return;
  25414. }
  25415. if (suspended == 1) {
  25416. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Suspended.\n");
  25417. ma_device__on_notification_stopped(pDevice);
  25418. } else {
  25419. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Resumed.\n");
  25420. ma_device__on_notification_started(pDevice);
  25421. }
  25422. }
  25423. static void ma_device_on_rerouted__pulse(ma_pa_stream* pStream, void* pUserData)
  25424. {
  25425. ma_device* pDevice = (ma_device*)pUserData;
  25426. (void)pStream;
  25427. (void)pUserData;
  25428. ma_device__on_notification_rerouted(pDevice);
  25429. }
  25430. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__pulse(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  25431. {
  25432. /*
  25433. There have been reports from users where buffers of < ~20ms result glitches when running through
  25434. PipeWire. To work around this we're going to have to use a different default buffer size.
  25435. */
  25436. const ma_uint32 defaultPeriodSizeInMilliseconds_LowLatency = 25;
  25437. const ma_uint32 defaultPeriodSizeInMilliseconds_Conservative = MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE;
  25438. MA_ASSERT(nativeSampleRate != 0);
  25439. if (pDescriptor->periodSizeInFrames == 0) {
  25440. if (pDescriptor->periodSizeInMilliseconds == 0) {
  25441. if (performanceProfile == ma_performance_profile_low_latency) {
  25442. return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_LowLatency, nativeSampleRate);
  25443. } else {
  25444. return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_Conservative, nativeSampleRate);
  25445. }
  25446. } else {
  25447. return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  25448. }
  25449. } else {
  25450. return pDescriptor->periodSizeInFrames;
  25451. }
  25452. }
  25453. static ma_result ma_device_init__pulse(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  25454. {
  25455. /*
  25456. Notes for PulseAudio:
  25457. - When both the period size in frames and milliseconds are 0, we default to miniaudio's
  25458. default buffer sizes rather than leaving it up to PulseAudio because I don't trust
  25459. PulseAudio to give us any kind of reasonable latency by default.
  25460. - Do not ever, *ever* forget to use MA_PA_STREAM_ADJUST_LATENCY. If you don't specify this
  25461. flag, capture mode will just not work properly until you open another PulseAudio app.
  25462. */
  25463. ma_result result = MA_SUCCESS;
  25464. int error = 0;
  25465. const char* devPlayback = NULL;
  25466. const char* devCapture = NULL;
  25467. ma_format format = ma_format_unknown;
  25468. ma_uint32 channels = 0;
  25469. ma_uint32 sampleRate = 0;
  25470. ma_pa_sink_info sinkInfo;
  25471. ma_pa_source_info sourceInfo;
  25472. ma_pa_sample_spec ss;
  25473. ma_pa_channel_map cmap;
  25474. ma_pa_buffer_attr attr;
  25475. const ma_pa_sample_spec* pActualSS = NULL;
  25476. const ma_pa_buffer_attr* pActualAttr = NULL;
  25477. ma_uint32 iChannel;
  25478. ma_pa_stream_flags_t streamFlags;
  25479. MA_ASSERT(pDevice != NULL);
  25480. MA_ZERO_OBJECT(&pDevice->pulse);
  25481. if (pConfig->deviceType == ma_device_type_loopback) {
  25482. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  25483. }
  25484. /* No exclusive mode with the PulseAudio backend. */
  25485. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
  25486. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
  25487. return MA_SHARE_MODE_NOT_SUPPORTED;
  25488. }
  25489. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25490. if (pDescriptorPlayback->pDeviceID != NULL) {
  25491. devPlayback = pDescriptorPlayback->pDeviceID->pulse;
  25492. }
  25493. format = pDescriptorPlayback->format;
  25494. channels = pDescriptorPlayback->channels;
  25495. sampleRate = pDescriptorPlayback->sampleRate;
  25496. }
  25497. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25498. if (pDescriptorCapture->pDeviceID != NULL) {
  25499. devCapture = pDescriptorCapture->pDeviceID->pulse;
  25500. }
  25501. format = pDescriptorCapture->format;
  25502. channels = pDescriptorCapture->channels;
  25503. sampleRate = pDescriptorCapture->sampleRate;
  25504. }
  25505. 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);
  25506. if (result != MA_SUCCESS) {
  25507. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize PA mainloop and context for device.\n");
  25508. return result;
  25509. }
  25510. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25511. result = ma_context_get_source_info__pulse(pDevice->pContext, devCapture, &sourceInfo);
  25512. if (result != MA_SUCCESS) {
  25513. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve source info for capture device.");
  25514. goto on_error0;
  25515. }
  25516. ss = sourceInfo.sample_spec;
  25517. cmap = sourceInfo.channel_map;
  25518. /* Use the requested channel count if we have one. */
  25519. if (pDescriptorCapture->channels != 0) {
  25520. ss.channels = pDescriptorCapture->channels;
  25521. }
  25522. /* Use a default channel map. */
  25523. ((ma_pa_channel_map_init_extend_proc)pDevice->pContext->pulse.pa_channel_map_init_extend)(&cmap, ss.channels, MA_PA_CHANNEL_MAP_DEFAULT);
  25524. /* Use the requested sample rate if one was specified. */
  25525. if (pDescriptorCapture->sampleRate != 0) {
  25526. ss.rate = pDescriptorCapture->sampleRate;
  25527. }
  25528. streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY;
  25529. if (ma_format_from_pulse(ss.format) == ma_format_unknown) {
  25530. if (ma_is_little_endian()) {
  25531. ss.format = MA_PA_SAMPLE_FLOAT32LE;
  25532. } else {
  25533. ss.format = MA_PA_SAMPLE_FLOAT32BE;
  25534. }
  25535. streamFlags |= MA_PA_STREAM_FIX_FORMAT;
  25536. 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");
  25537. }
  25538. if (ss.rate == 0) {
  25539. ss.rate = MA_DEFAULT_SAMPLE_RATE;
  25540. streamFlags |= MA_PA_STREAM_FIX_RATE;
  25541. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate);
  25542. }
  25543. if (ss.channels == 0) {
  25544. ss.channels = MA_DEFAULT_CHANNELS;
  25545. streamFlags |= MA_PA_STREAM_FIX_CHANNELS;
  25546. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
  25547. }
  25548. /* We now have enough information to calculate our actual period size in frames. */
  25549. pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorCapture, ss.rate, pConfig->performanceProfile);
  25550. attr = ma_device__pa_buffer_attr_new(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodCount, &ss);
  25551. 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);
  25552. pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap);
  25553. if (pDevice->pulse.pStreamCapture == NULL) {
  25554. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.\n");
  25555. result = MA_ERROR;
  25556. goto on_error0;
  25557. }
  25558. /* The callback needs to be set before connecting the stream. */
  25559. ((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);
  25560. /* State callback for checking when the device has been corked. */
  25561. ((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);
  25562. /* Rerouting notification. */
  25563. ((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);
  25564. /* Connect after we've got all of our internal state set up. */
  25565. if (devCapture != NULL) {
  25566. streamFlags |= MA_PA_STREAM_DONT_MOVE;
  25567. }
  25568. error = ((ma_pa_stream_connect_record_proc)pDevice->pContext->pulse.pa_stream_connect_record)((ma_pa_stream*)pDevice->pulse.pStreamCapture, devCapture, &attr, streamFlags);
  25569. if (error != MA_PA_OK) {
  25570. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio capture stream.");
  25571. result = ma_result_from_pulse(error);
  25572. goto on_error1;
  25573. }
  25574. result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25575. if (result != MA_SUCCESS) {
  25576. goto on_error2;
  25577. }
  25578. /* Internal format. */
  25579. pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25580. if (pActualSS != NULL) {
  25581. ss = *pActualSS;
  25582. 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);
  25583. } else {
  25584. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve capture sample spec.\n");
  25585. }
  25586. pDescriptorCapture->format = ma_format_from_pulse(ss.format);
  25587. pDescriptorCapture->channels = ss.channels;
  25588. pDescriptorCapture->sampleRate = ss.rate;
  25589. if (pDescriptorCapture->format == ma_format_unknown || pDescriptorCapture->channels == 0 || pDescriptorCapture->sampleRate == 0) {
  25590. 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);
  25591. result = MA_ERROR;
  25592. goto on_error4;
  25593. }
  25594. /* Internal channel map. */
  25595. /*
  25596. Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting
  25597. the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono
  25598. and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For
  25599. all other channel counts we need to just put up with whatever PipeWire reports and hope it gets
  25600. fixed sooner than later. I might remove this hack later.
  25601. */
  25602. if (pDescriptorCapture->channels > 2) {
  25603. for (iChannel = 0; iChannel < pDescriptorCapture->channels; ++iChannel) {
  25604. pDescriptorCapture->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
  25605. }
  25606. } else {
  25607. /* Hack for mono and stereo. */
  25608. if (pDescriptorCapture->channels == 1) {
  25609. pDescriptorCapture->channelMap[0] = MA_CHANNEL_MONO;
  25610. } else if (pDescriptorCapture->channels == 2) {
  25611. pDescriptorCapture->channelMap[0] = MA_CHANNEL_FRONT_LEFT;
  25612. pDescriptorCapture->channelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  25613. } else {
  25614. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  25615. }
  25616. }
  25617. /* Buffer. */
  25618. pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25619. if (pActualAttr != NULL) {
  25620. attr = *pActualAttr;
  25621. }
  25622. if (attr.fragsize > 0) {
  25623. pDescriptorCapture->periodCount = ma_max(attr.maxlength / attr.fragsize, 1);
  25624. } else {
  25625. pDescriptorCapture->periodCount = 1;
  25626. }
  25627. pDescriptorCapture->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / pDescriptorCapture->periodCount;
  25628. 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);
  25629. }
  25630. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25631. result = ma_context_get_sink_info__pulse(pDevice->pContext, devPlayback, &sinkInfo);
  25632. if (result != MA_SUCCESS) {
  25633. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.\n");
  25634. goto on_error2;
  25635. }
  25636. ss = sinkInfo.sample_spec;
  25637. cmap = sinkInfo.channel_map;
  25638. /* Use the requested channel count if we have one. */
  25639. if (pDescriptorPlayback->channels != 0) {
  25640. ss.channels = pDescriptorPlayback->channels;
  25641. }
  25642. /* Use a default channel map. */
  25643. ((ma_pa_channel_map_init_extend_proc)pDevice->pContext->pulse.pa_channel_map_init_extend)(&cmap, ss.channels, MA_PA_CHANNEL_MAP_DEFAULT);
  25644. /* Use the requested sample rate if one was specified. */
  25645. if (pDescriptorPlayback->sampleRate != 0) {
  25646. ss.rate = pDescriptorPlayback->sampleRate;
  25647. }
  25648. streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY;
  25649. if (ma_format_from_pulse(ss.format) == ma_format_unknown) {
  25650. if (ma_is_little_endian()) {
  25651. ss.format = MA_PA_SAMPLE_FLOAT32LE;
  25652. } else {
  25653. ss.format = MA_PA_SAMPLE_FLOAT32BE;
  25654. }
  25655. streamFlags |= MA_PA_STREAM_FIX_FORMAT;
  25656. 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");
  25657. }
  25658. if (ss.rate == 0) {
  25659. ss.rate = MA_DEFAULT_SAMPLE_RATE;
  25660. streamFlags |= MA_PA_STREAM_FIX_RATE;
  25661. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate);
  25662. }
  25663. if (ss.channels == 0) {
  25664. ss.channels = MA_DEFAULT_CHANNELS;
  25665. streamFlags |= MA_PA_STREAM_FIX_CHANNELS;
  25666. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
  25667. }
  25668. /* We now have enough information to calculate the actual buffer size in frames. */
  25669. pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorPlayback, ss.rate, pConfig->performanceProfile);
  25670. attr = ma_device__pa_buffer_attr_new(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodCount, &ss);
  25671. 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);
  25672. pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap);
  25673. if (pDevice->pulse.pStreamPlayback == NULL) {
  25674. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.\n");
  25675. result = MA_ERROR;
  25676. goto on_error2;
  25677. }
  25678. /*
  25679. 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
  25680. device state of ma_device_state_uninitialized.
  25681. */
  25682. ((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);
  25683. /* State callback for checking when the device has been corked. */
  25684. ((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);
  25685. /* Rerouting notification. */
  25686. ((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);
  25687. /* Connect after we've got all of our internal state set up. */
  25688. if (devPlayback != NULL) {
  25689. streamFlags |= MA_PA_STREAM_DONT_MOVE;
  25690. }
  25691. 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);
  25692. if (error != MA_PA_OK) {
  25693. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio playback stream.");
  25694. result = ma_result_from_pulse(error);
  25695. goto on_error3;
  25696. }
  25697. result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25698. if (result != MA_SUCCESS) {
  25699. goto on_error3;
  25700. }
  25701. /* Internal format. */
  25702. pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25703. if (pActualSS != NULL) {
  25704. ss = *pActualSS;
  25705. 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);
  25706. } else {
  25707. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve playback sample spec.\n");
  25708. }
  25709. pDescriptorPlayback->format = ma_format_from_pulse(ss.format);
  25710. pDescriptorPlayback->channels = ss.channels;
  25711. pDescriptorPlayback->sampleRate = ss.rate;
  25712. if (pDescriptorPlayback->format == ma_format_unknown || pDescriptorPlayback->channels == 0 || pDescriptorPlayback->sampleRate == 0) {
  25713. 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);
  25714. result = MA_ERROR;
  25715. goto on_error4;
  25716. }
  25717. /* Internal channel map. */
  25718. /*
  25719. Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting
  25720. the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono
  25721. and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For
  25722. all other channel counts we need to just put up with whatever PipeWire reports and hope it gets
  25723. fixed sooner than later. I might remove this hack later.
  25724. */
  25725. if (pDescriptorPlayback->channels > 2) {
  25726. for (iChannel = 0; iChannel < pDescriptorPlayback->channels; ++iChannel) {
  25727. pDescriptorPlayback->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
  25728. }
  25729. } else {
  25730. /* Hack for mono and stereo. */
  25731. if (pDescriptorPlayback->channels == 1) {
  25732. pDescriptorPlayback->channelMap[0] = MA_CHANNEL_MONO;
  25733. } else if (pDescriptorPlayback->channels == 2) {
  25734. pDescriptorPlayback->channelMap[0] = MA_CHANNEL_FRONT_LEFT;
  25735. pDescriptorPlayback->channelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  25736. } else {
  25737. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  25738. }
  25739. }
  25740. /* Buffer. */
  25741. pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25742. if (pActualAttr != NULL) {
  25743. attr = *pActualAttr;
  25744. }
  25745. if (attr.tlength > 0) {
  25746. pDescriptorPlayback->periodCount = ma_max(attr.maxlength / attr.tlength, 1);
  25747. } else {
  25748. pDescriptorPlayback->periodCount = 1;
  25749. }
  25750. pDescriptorPlayback->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) / pDescriptorPlayback->periodCount;
  25751. 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);
  25752. }
  25753. /*
  25754. We need a ring buffer for handling duplex mode. We can use the main duplex ring buffer in the main
  25755. part of the ma_device struct. We cannot, however, depend on ma_device_init() initializing this for
  25756. us later on because that will only do it if it's a fully asynchronous backend - i.e. the
  25757. onDeviceDataLoop callback is NULL, which is not the case for PulseAudio.
  25758. */
  25759. if (pConfig->deviceType == ma_device_type_duplex) {
  25760. ma_format rbFormat = (format != ma_format_unknown) ? format : pDescriptorCapture->format;
  25761. ma_uint32 rbChannels = (channels > 0) ? channels : pDescriptorCapture->channels;
  25762. ma_uint32 rbSampleRate = (sampleRate > 0) ? sampleRate : pDescriptorCapture->sampleRate;
  25763. result = ma_duplex_rb_init(rbFormat, rbChannels, rbSampleRate, pDescriptorCapture->sampleRate, pDescriptorCapture->periodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB);
  25764. if (result != MA_SUCCESS) {
  25765. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize ring buffer. %s.\n", ma_result_description(result));
  25766. goto on_error4;
  25767. }
  25768. }
  25769. return MA_SUCCESS;
  25770. on_error4:
  25771. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25772. ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25773. }
  25774. on_error3:
  25775. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25776. ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  25777. }
  25778. on_error2:
  25779. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25780. ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25781. }
  25782. on_error1:
  25783. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25784. ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  25785. }
  25786. on_error0:
  25787. return result;
  25788. }
  25789. static void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData)
  25790. {
  25791. ma_bool32* pIsSuccessful = (ma_bool32*)pUserData;
  25792. MA_ASSERT(pIsSuccessful != NULL);
  25793. *pIsSuccessful = (ma_bool32)success;
  25794. (void)pStream; /* Unused. */
  25795. }
  25796. static ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork)
  25797. {
  25798. ma_context* pContext = pDevice->pContext;
  25799. ma_bool32 wasSuccessful;
  25800. ma_pa_stream* pStream;
  25801. ma_pa_operation* pOP;
  25802. ma_result result;
  25803. /* This should not be called with a duplex device type. */
  25804. if (deviceType == ma_device_type_duplex) {
  25805. return MA_INVALID_ARGS;
  25806. }
  25807. wasSuccessful = MA_FALSE;
  25808. pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback);
  25809. MA_ASSERT(pStream != NULL);
  25810. pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful);
  25811. if (pOP == NULL) {
  25812. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.");
  25813. return MA_ERROR;
  25814. }
  25815. result = ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP);
  25816. if (result != MA_SUCCESS) {
  25817. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork.");
  25818. return result;
  25819. }
  25820. if (!wasSuccessful) {
  25821. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to %s PulseAudio stream.", (cork) ? "stop" : "start");
  25822. return MA_ERROR;
  25823. }
  25824. return MA_SUCCESS;
  25825. }
  25826. static ma_result ma_device_start__pulse(ma_device* pDevice)
  25827. {
  25828. ma_result result;
  25829. MA_ASSERT(pDevice != NULL);
  25830. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25831. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 0);
  25832. if (result != MA_SUCCESS) {
  25833. return result;
  25834. }
  25835. }
  25836. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25837. /*
  25838. We need to fill some data before uncorking. Not doing this will result in the write callback
  25839. never getting fired. We're not going to abort if writing fails because I still want the device
  25840. to get uncorked.
  25841. */
  25842. 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.*/
  25843. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 0);
  25844. if (result != MA_SUCCESS) {
  25845. return result;
  25846. }
  25847. }
  25848. return MA_SUCCESS;
  25849. }
  25850. static ma_result ma_device_stop__pulse(ma_device* pDevice)
  25851. {
  25852. ma_result result;
  25853. MA_ASSERT(pDevice != NULL);
  25854. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25855. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 1);
  25856. if (result != MA_SUCCESS) {
  25857. return result;
  25858. }
  25859. }
  25860. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25861. /*
  25862. Ideally we would drain the device here, but there's been cases where PulseAudio seems to be
  25863. broken on some systems to the point where no audio processing seems to happen. When this
  25864. happens, draining never completes and we get stuck here. For now I'm disabling draining of
  25865. the device so we don't just freeze the application.
  25866. */
  25867. #if 0
  25868. 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);
  25869. ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP);
  25870. #endif
  25871. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 1);
  25872. if (result != MA_SUCCESS) {
  25873. return result;
  25874. }
  25875. }
  25876. return MA_SUCCESS;
  25877. }
  25878. static ma_result ma_device_data_loop__pulse(ma_device* pDevice)
  25879. {
  25880. int resultPA;
  25881. MA_ASSERT(pDevice != NULL);
  25882. /* NOTE: Don't start the device here. It'll be done at a higher level. */
  25883. /*
  25884. All data is handled through callbacks. All we need to do is iterate over the main loop and let
  25885. the callbacks deal with it.
  25886. */
  25887. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  25888. resultPA = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
  25889. if (resultPA < 0) {
  25890. break;
  25891. }
  25892. }
  25893. /* NOTE: Don't stop the device here. It'll be done at a higher level. */
  25894. return MA_SUCCESS;
  25895. }
  25896. static ma_result ma_device_data_loop_wakeup__pulse(ma_device* pDevice)
  25897. {
  25898. MA_ASSERT(pDevice != NULL);
  25899. ((ma_pa_mainloop_wakeup_proc)pDevice->pContext->pulse.pa_mainloop_wakeup)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
  25900. return MA_SUCCESS;
  25901. }
  25902. static ma_result ma_context_uninit__pulse(ma_context* pContext)
  25903. {
  25904. MA_ASSERT(pContext != NULL);
  25905. MA_ASSERT(pContext->backend == ma_backend_pulseaudio);
  25906. ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pContext->pulse.pPulseContext);
  25907. ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pContext->pulse.pPulseContext);
  25908. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pContext->pulse.pMainLoop);
  25909. ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
  25910. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  25911. #ifndef MA_NO_RUNTIME_LINKING
  25912. ma_dlclose(ma_context_get_log(pContext), pContext->pulse.pulseSO);
  25913. #endif
  25914. return MA_SUCCESS;
  25915. }
  25916. static ma_result ma_context_init__pulse(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  25917. {
  25918. ma_result result;
  25919. #ifndef MA_NO_RUNTIME_LINKING
  25920. const char* libpulseNames[] = {
  25921. "libpulse.so",
  25922. "libpulse.so.0"
  25923. };
  25924. size_t i;
  25925. for (i = 0; i < ma_countof(libpulseNames); ++i) {
  25926. pContext->pulse.pulseSO = ma_dlopen(ma_context_get_log(pContext), libpulseNames[i]);
  25927. if (pContext->pulse.pulseSO != NULL) {
  25928. break;
  25929. }
  25930. }
  25931. if (pContext->pulse.pulseSO == NULL) {
  25932. return MA_NO_BACKEND;
  25933. }
  25934. pContext->pulse.pa_mainloop_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_new");
  25935. pContext->pulse.pa_mainloop_free = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_free");
  25936. pContext->pulse.pa_mainloop_quit = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_quit");
  25937. pContext->pulse.pa_mainloop_get_api = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_get_api");
  25938. pContext->pulse.pa_mainloop_iterate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_iterate");
  25939. pContext->pulse.pa_mainloop_wakeup = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_mainloop_wakeup");
  25940. pContext->pulse.pa_threaded_mainloop_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_new");
  25941. pContext->pulse.pa_threaded_mainloop_free = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_free");
  25942. pContext->pulse.pa_threaded_mainloop_start = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_start");
  25943. pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_stop");
  25944. pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_lock");
  25945. pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_unlock");
  25946. pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_wait");
  25947. pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_signal");
  25948. pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_accept");
  25949. pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_get_retval");
  25950. pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_get_api");
  25951. pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_in_thread");
  25952. pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_threaded_mainloop_set_name");
  25953. pContext->pulse.pa_context_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_new");
  25954. pContext->pulse.pa_context_unref = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_unref");
  25955. pContext->pulse.pa_context_connect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_connect");
  25956. pContext->pulse.pa_context_disconnect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_disconnect");
  25957. pContext->pulse.pa_context_set_state_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_set_state_callback");
  25958. pContext->pulse.pa_context_get_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_state");
  25959. pContext->pulse.pa_context_get_sink_info_list = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_sink_info_list");
  25960. pContext->pulse.pa_context_get_source_info_list = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_source_info_list");
  25961. pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_sink_info_by_name");
  25962. pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_context_get_source_info_by_name");
  25963. pContext->pulse.pa_operation_unref = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_operation_unref");
  25964. pContext->pulse.pa_operation_get_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_operation_get_state");
  25965. pContext->pulse.pa_channel_map_init_extend = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_channel_map_init_extend");
  25966. pContext->pulse.pa_channel_map_valid = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_channel_map_valid");
  25967. pContext->pulse.pa_channel_map_compatible = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_channel_map_compatible");
  25968. pContext->pulse.pa_stream_new = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_new");
  25969. pContext->pulse.pa_stream_unref = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_unref");
  25970. pContext->pulse.pa_stream_connect_playback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_connect_playback");
  25971. pContext->pulse.pa_stream_connect_record = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_connect_record");
  25972. pContext->pulse.pa_stream_disconnect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_disconnect");
  25973. pContext->pulse.pa_stream_get_state = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_state");
  25974. pContext->pulse.pa_stream_get_sample_spec = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_sample_spec");
  25975. pContext->pulse.pa_stream_get_channel_map = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_channel_map");
  25976. pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_buffer_attr");
  25977. pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_buffer_attr");
  25978. pContext->pulse.pa_stream_get_device_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_get_device_name");
  25979. pContext->pulse.pa_stream_set_write_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_write_callback");
  25980. pContext->pulse.pa_stream_set_read_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_read_callback");
  25981. pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_suspended_callback");
  25982. pContext->pulse.pa_stream_set_moved_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_set_moved_callback");
  25983. pContext->pulse.pa_stream_is_suspended = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_is_suspended");
  25984. pContext->pulse.pa_stream_flush = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_flush");
  25985. pContext->pulse.pa_stream_drain = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_drain");
  25986. pContext->pulse.pa_stream_is_corked = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_is_corked");
  25987. pContext->pulse.pa_stream_cork = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_cork");
  25988. pContext->pulse.pa_stream_trigger = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_trigger");
  25989. pContext->pulse.pa_stream_begin_write = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_begin_write");
  25990. pContext->pulse.pa_stream_write = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_write");
  25991. pContext->pulse.pa_stream_peek = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_peek");
  25992. pContext->pulse.pa_stream_drop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_drop");
  25993. pContext->pulse.pa_stream_writable_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_writable_size");
  25994. pContext->pulse.pa_stream_readable_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->pulse.pulseSO, "pa_stream_readable_size");
  25995. #else
  25996. /* This strange assignment system is just for type safety. */
  25997. ma_pa_mainloop_new_proc _pa_mainloop_new = pa_mainloop_new;
  25998. ma_pa_mainloop_free_proc _pa_mainloop_free = pa_mainloop_free;
  25999. ma_pa_mainloop_quit_proc _pa_mainloop_quit = pa_mainloop_quit;
  26000. ma_pa_mainloop_get_api_proc _pa_mainloop_get_api = pa_mainloop_get_api;
  26001. ma_pa_mainloop_iterate_proc _pa_mainloop_iterate = pa_mainloop_iterate;
  26002. ma_pa_mainloop_wakeup_proc _pa_mainloop_wakeup = pa_mainloop_wakeup;
  26003. ma_pa_threaded_mainloop_new_proc _pa_threaded_mainloop_new = pa_threaded_mainloop_new;
  26004. ma_pa_threaded_mainloop_free_proc _pa_threaded_mainloop_free = pa_threaded_mainloop_free;
  26005. ma_pa_threaded_mainloop_start_proc _pa_threaded_mainloop_start = pa_threaded_mainloop_start;
  26006. ma_pa_threaded_mainloop_stop_proc _pa_threaded_mainloop_stop = pa_threaded_mainloop_stop;
  26007. ma_pa_threaded_mainloop_lock_proc _pa_threaded_mainloop_lock = pa_threaded_mainloop_lock;
  26008. ma_pa_threaded_mainloop_unlock_proc _pa_threaded_mainloop_unlock = pa_threaded_mainloop_unlock;
  26009. ma_pa_threaded_mainloop_wait_proc _pa_threaded_mainloop_wait = pa_threaded_mainloop_wait;
  26010. ma_pa_threaded_mainloop_signal_proc _pa_threaded_mainloop_signal = pa_threaded_mainloop_signal;
  26011. ma_pa_threaded_mainloop_accept_proc _pa_threaded_mainloop_accept = pa_threaded_mainloop_accept;
  26012. ma_pa_threaded_mainloop_get_retval_proc _pa_threaded_mainloop_get_retval = pa_threaded_mainloop_get_retval;
  26013. ma_pa_threaded_mainloop_get_api_proc _pa_threaded_mainloop_get_api = pa_threaded_mainloop_get_api;
  26014. ma_pa_threaded_mainloop_in_thread_proc _pa_threaded_mainloop_in_thread = pa_threaded_mainloop_in_thread;
  26015. ma_pa_threaded_mainloop_set_name_proc _pa_threaded_mainloop_set_name = pa_threaded_mainloop_set_name;
  26016. ma_pa_context_new_proc _pa_context_new = pa_context_new;
  26017. ma_pa_context_unref_proc _pa_context_unref = pa_context_unref;
  26018. ma_pa_context_connect_proc _pa_context_connect = pa_context_connect;
  26019. ma_pa_context_disconnect_proc _pa_context_disconnect = pa_context_disconnect;
  26020. ma_pa_context_set_state_callback_proc _pa_context_set_state_callback = pa_context_set_state_callback;
  26021. ma_pa_context_get_state_proc _pa_context_get_state = pa_context_get_state;
  26022. ma_pa_context_get_sink_info_list_proc _pa_context_get_sink_info_list = pa_context_get_sink_info_list;
  26023. ma_pa_context_get_source_info_list_proc _pa_context_get_source_info_list = pa_context_get_source_info_list;
  26024. ma_pa_context_get_sink_info_by_name_proc _pa_context_get_sink_info_by_name = pa_context_get_sink_info_by_name;
  26025. ma_pa_context_get_source_info_by_name_proc _pa_context_get_source_info_by_name= pa_context_get_source_info_by_name;
  26026. ma_pa_operation_unref_proc _pa_operation_unref = pa_operation_unref;
  26027. ma_pa_operation_get_state_proc _pa_operation_get_state = pa_operation_get_state;
  26028. ma_pa_channel_map_init_extend_proc _pa_channel_map_init_extend = pa_channel_map_init_extend;
  26029. ma_pa_channel_map_valid_proc _pa_channel_map_valid = pa_channel_map_valid;
  26030. ma_pa_channel_map_compatible_proc _pa_channel_map_compatible = pa_channel_map_compatible;
  26031. ma_pa_stream_new_proc _pa_stream_new = pa_stream_new;
  26032. ma_pa_stream_unref_proc _pa_stream_unref = pa_stream_unref;
  26033. ma_pa_stream_connect_playback_proc _pa_stream_connect_playback = pa_stream_connect_playback;
  26034. ma_pa_stream_connect_record_proc _pa_stream_connect_record = pa_stream_connect_record;
  26035. ma_pa_stream_disconnect_proc _pa_stream_disconnect = pa_stream_disconnect;
  26036. ma_pa_stream_get_state_proc _pa_stream_get_state = pa_stream_get_state;
  26037. ma_pa_stream_get_sample_spec_proc _pa_stream_get_sample_spec = pa_stream_get_sample_spec;
  26038. ma_pa_stream_get_channel_map_proc _pa_stream_get_channel_map = pa_stream_get_channel_map;
  26039. ma_pa_stream_get_buffer_attr_proc _pa_stream_get_buffer_attr = pa_stream_get_buffer_attr;
  26040. ma_pa_stream_set_buffer_attr_proc _pa_stream_set_buffer_attr = pa_stream_set_buffer_attr;
  26041. ma_pa_stream_get_device_name_proc _pa_stream_get_device_name = pa_stream_get_device_name;
  26042. ma_pa_stream_set_write_callback_proc _pa_stream_set_write_callback = pa_stream_set_write_callback;
  26043. ma_pa_stream_set_read_callback_proc _pa_stream_set_read_callback = pa_stream_set_read_callback;
  26044. ma_pa_stream_set_suspended_callback_proc _pa_stream_set_suspended_callback = pa_stream_set_suspended_callback;
  26045. ma_pa_stream_set_moved_callback_proc _pa_stream_set_moved_callback = pa_stream_set_moved_callback;
  26046. ma_pa_stream_is_suspended_proc _pa_stream_is_suspended = pa_stream_is_suspended;
  26047. ma_pa_stream_flush_proc _pa_stream_flush = pa_stream_flush;
  26048. ma_pa_stream_drain_proc _pa_stream_drain = pa_stream_drain;
  26049. ma_pa_stream_is_corked_proc _pa_stream_is_corked = pa_stream_is_corked;
  26050. ma_pa_stream_cork_proc _pa_stream_cork = pa_stream_cork;
  26051. ma_pa_stream_trigger_proc _pa_stream_trigger = pa_stream_trigger;
  26052. ma_pa_stream_begin_write_proc _pa_stream_begin_write = pa_stream_begin_write;
  26053. ma_pa_stream_write_proc _pa_stream_write = pa_stream_write;
  26054. ma_pa_stream_peek_proc _pa_stream_peek = pa_stream_peek;
  26055. ma_pa_stream_drop_proc _pa_stream_drop = pa_stream_drop;
  26056. ma_pa_stream_writable_size_proc _pa_stream_writable_size = pa_stream_writable_size;
  26057. ma_pa_stream_readable_size_proc _pa_stream_readable_size = pa_stream_readable_size;
  26058. pContext->pulse.pa_mainloop_new = (ma_proc)_pa_mainloop_new;
  26059. pContext->pulse.pa_mainloop_free = (ma_proc)_pa_mainloop_free;
  26060. pContext->pulse.pa_mainloop_quit = (ma_proc)_pa_mainloop_quit;
  26061. pContext->pulse.pa_mainloop_get_api = (ma_proc)_pa_mainloop_get_api;
  26062. pContext->pulse.pa_mainloop_iterate = (ma_proc)_pa_mainloop_iterate;
  26063. pContext->pulse.pa_mainloop_wakeup = (ma_proc)_pa_mainloop_wakeup;
  26064. pContext->pulse.pa_threaded_mainloop_new = (ma_proc)_pa_threaded_mainloop_new;
  26065. pContext->pulse.pa_threaded_mainloop_free = (ma_proc)_pa_threaded_mainloop_free;
  26066. pContext->pulse.pa_threaded_mainloop_start = (ma_proc)_pa_threaded_mainloop_start;
  26067. pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)_pa_threaded_mainloop_stop;
  26068. pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)_pa_threaded_mainloop_lock;
  26069. pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)_pa_threaded_mainloop_unlock;
  26070. pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)_pa_threaded_mainloop_wait;
  26071. pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)_pa_threaded_mainloop_signal;
  26072. pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)_pa_threaded_mainloop_accept;
  26073. pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)_pa_threaded_mainloop_get_retval;
  26074. pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)_pa_threaded_mainloop_get_api;
  26075. pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)_pa_threaded_mainloop_in_thread;
  26076. pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)_pa_threaded_mainloop_set_name;
  26077. pContext->pulse.pa_context_new = (ma_proc)_pa_context_new;
  26078. pContext->pulse.pa_context_unref = (ma_proc)_pa_context_unref;
  26079. pContext->pulse.pa_context_connect = (ma_proc)_pa_context_connect;
  26080. pContext->pulse.pa_context_disconnect = (ma_proc)_pa_context_disconnect;
  26081. pContext->pulse.pa_context_set_state_callback = (ma_proc)_pa_context_set_state_callback;
  26082. pContext->pulse.pa_context_get_state = (ma_proc)_pa_context_get_state;
  26083. pContext->pulse.pa_context_get_sink_info_list = (ma_proc)_pa_context_get_sink_info_list;
  26084. pContext->pulse.pa_context_get_source_info_list = (ma_proc)_pa_context_get_source_info_list;
  26085. pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)_pa_context_get_sink_info_by_name;
  26086. pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)_pa_context_get_source_info_by_name;
  26087. pContext->pulse.pa_operation_unref = (ma_proc)_pa_operation_unref;
  26088. pContext->pulse.pa_operation_get_state = (ma_proc)_pa_operation_get_state;
  26089. pContext->pulse.pa_channel_map_init_extend = (ma_proc)_pa_channel_map_init_extend;
  26090. pContext->pulse.pa_channel_map_valid = (ma_proc)_pa_channel_map_valid;
  26091. pContext->pulse.pa_channel_map_compatible = (ma_proc)_pa_channel_map_compatible;
  26092. pContext->pulse.pa_stream_new = (ma_proc)_pa_stream_new;
  26093. pContext->pulse.pa_stream_unref = (ma_proc)_pa_stream_unref;
  26094. pContext->pulse.pa_stream_connect_playback = (ma_proc)_pa_stream_connect_playback;
  26095. pContext->pulse.pa_stream_connect_record = (ma_proc)_pa_stream_connect_record;
  26096. pContext->pulse.pa_stream_disconnect = (ma_proc)_pa_stream_disconnect;
  26097. pContext->pulse.pa_stream_get_state = (ma_proc)_pa_stream_get_state;
  26098. pContext->pulse.pa_stream_get_sample_spec = (ma_proc)_pa_stream_get_sample_spec;
  26099. pContext->pulse.pa_stream_get_channel_map = (ma_proc)_pa_stream_get_channel_map;
  26100. pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)_pa_stream_get_buffer_attr;
  26101. pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)_pa_stream_set_buffer_attr;
  26102. pContext->pulse.pa_stream_get_device_name = (ma_proc)_pa_stream_get_device_name;
  26103. pContext->pulse.pa_stream_set_write_callback = (ma_proc)_pa_stream_set_write_callback;
  26104. pContext->pulse.pa_stream_set_read_callback = (ma_proc)_pa_stream_set_read_callback;
  26105. pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)_pa_stream_set_suspended_callback;
  26106. pContext->pulse.pa_stream_set_moved_callback = (ma_proc)_pa_stream_set_moved_callback;
  26107. pContext->pulse.pa_stream_is_suspended = (ma_proc)_pa_stream_is_suspended;
  26108. pContext->pulse.pa_stream_flush = (ma_proc)_pa_stream_flush;
  26109. pContext->pulse.pa_stream_drain = (ma_proc)_pa_stream_drain;
  26110. pContext->pulse.pa_stream_is_corked = (ma_proc)_pa_stream_is_corked;
  26111. pContext->pulse.pa_stream_cork = (ma_proc)_pa_stream_cork;
  26112. pContext->pulse.pa_stream_trigger = (ma_proc)_pa_stream_trigger;
  26113. pContext->pulse.pa_stream_begin_write = (ma_proc)_pa_stream_begin_write;
  26114. pContext->pulse.pa_stream_write = (ma_proc)_pa_stream_write;
  26115. pContext->pulse.pa_stream_peek = (ma_proc)_pa_stream_peek;
  26116. pContext->pulse.pa_stream_drop = (ma_proc)_pa_stream_drop;
  26117. pContext->pulse.pa_stream_writable_size = (ma_proc)_pa_stream_writable_size;
  26118. pContext->pulse.pa_stream_readable_size = (ma_proc)_pa_stream_readable_size;
  26119. #endif
  26120. /* We need to make a copy of the application and server names so we can pass them to the pa_context of each device. */
  26121. pContext->pulse.pApplicationName = ma_copy_string(pConfig->pulse.pApplicationName, &pContext->allocationCallbacks);
  26122. if (pContext->pulse.pApplicationName == NULL && pConfig->pulse.pApplicationName != NULL) {
  26123. return MA_OUT_OF_MEMORY;
  26124. }
  26125. pContext->pulse.pServerName = ma_copy_string(pConfig->pulse.pServerName, &pContext->allocationCallbacks);
  26126. if (pContext->pulse.pServerName == NULL && pConfig->pulse.pServerName != NULL) {
  26127. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  26128. return MA_OUT_OF_MEMORY;
  26129. }
  26130. 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);
  26131. if (result != MA_SUCCESS) {
  26132. ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
  26133. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  26134. #ifndef MA_NO_RUNTIME_LINKING
  26135. ma_dlclose(ma_context_get_log(pContext), pContext->pulse.pulseSO);
  26136. #endif
  26137. return result;
  26138. }
  26139. /* With pa_mainloop we run a synchronous backend, but we implement our own main loop. */
  26140. pCallbacks->onContextInit = ma_context_init__pulse;
  26141. pCallbacks->onContextUninit = ma_context_uninit__pulse;
  26142. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__pulse;
  26143. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__pulse;
  26144. pCallbacks->onDeviceInit = ma_device_init__pulse;
  26145. pCallbacks->onDeviceUninit = ma_device_uninit__pulse;
  26146. pCallbacks->onDeviceStart = ma_device_start__pulse;
  26147. pCallbacks->onDeviceStop = ma_device_stop__pulse;
  26148. pCallbacks->onDeviceRead = NULL; /* Not used because we're implementing onDeviceDataLoop. */
  26149. pCallbacks->onDeviceWrite = NULL; /* Not used because we're implementing onDeviceDataLoop. */
  26150. pCallbacks->onDeviceDataLoop = ma_device_data_loop__pulse;
  26151. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__pulse;
  26152. return MA_SUCCESS;
  26153. }
  26154. #endif
  26155. /******************************************************************************
  26156. JACK Backend
  26157. ******************************************************************************/
  26158. #ifdef MA_HAS_JACK
  26159. /* It is assumed jack.h is available when compile-time linking is being used. */
  26160. #ifdef MA_NO_RUNTIME_LINKING
  26161. #include <jack/jack.h>
  26162. typedef jack_nframes_t ma_jack_nframes_t;
  26163. typedef jack_options_t ma_jack_options_t;
  26164. typedef jack_status_t ma_jack_status_t;
  26165. typedef jack_client_t ma_jack_client_t;
  26166. typedef jack_port_t ma_jack_port_t;
  26167. typedef JackProcessCallback ma_JackProcessCallback;
  26168. typedef JackBufferSizeCallback ma_JackBufferSizeCallback;
  26169. typedef JackShutdownCallback ma_JackShutdownCallback;
  26170. #define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE
  26171. #define ma_JackNoStartServer JackNoStartServer
  26172. #define ma_JackPortIsInput JackPortIsInput
  26173. #define ma_JackPortIsOutput JackPortIsOutput
  26174. #define ma_JackPortIsPhysical JackPortIsPhysical
  26175. #else
  26176. typedef ma_uint32 ma_jack_nframes_t;
  26177. typedef int ma_jack_options_t;
  26178. typedef int ma_jack_status_t;
  26179. typedef struct ma_jack_client_t ma_jack_client_t;
  26180. typedef struct ma_jack_port_t ma_jack_port_t;
  26181. typedef int (* ma_JackProcessCallback) (ma_jack_nframes_t nframes, void* arg);
  26182. typedef int (* ma_JackBufferSizeCallback)(ma_jack_nframes_t nframes, void* arg);
  26183. typedef void (* ma_JackShutdownCallback) (void* arg);
  26184. #define MA_JACK_DEFAULT_AUDIO_TYPE "32 bit float mono audio"
  26185. #define ma_JackNoStartServer 1
  26186. #define ma_JackPortIsInput 1
  26187. #define ma_JackPortIsOutput 2
  26188. #define ma_JackPortIsPhysical 4
  26189. #endif
  26190. typedef ma_jack_client_t* (* ma_jack_client_open_proc) (const char* client_name, ma_jack_options_t options, ma_jack_status_t* status, ...);
  26191. typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client);
  26192. typedef int (* ma_jack_client_name_size_proc) (void);
  26193. typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg);
  26194. typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg);
  26195. typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg);
  26196. typedef ma_jack_nframes_t (* ma_jack_get_sample_rate_proc) (ma_jack_client_t* client);
  26197. typedef ma_jack_nframes_t (* ma_jack_get_buffer_size_proc) (ma_jack_client_t* client);
  26198. 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);
  26199. typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client);
  26200. typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client);
  26201. typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port);
  26202. 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);
  26203. typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port);
  26204. typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes);
  26205. typedef void (* ma_jack_free_proc) (void* ptr);
  26206. static ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient)
  26207. {
  26208. size_t maxClientNameSize;
  26209. char clientName[256];
  26210. ma_jack_status_t status;
  26211. ma_jack_client_t* pClient;
  26212. MA_ASSERT(pContext != NULL);
  26213. MA_ASSERT(ppClient != NULL);
  26214. if (ppClient) {
  26215. *ppClient = NULL;
  26216. }
  26217. maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); /* Includes null terminator. */
  26218. ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->jack.pClientName != NULL) ? pContext->jack.pClientName : "miniaudio", (size_t)-1);
  26219. pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL);
  26220. if (pClient == NULL) {
  26221. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26222. }
  26223. if (ppClient) {
  26224. *ppClient = pClient;
  26225. }
  26226. return MA_SUCCESS;
  26227. }
  26228. static ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  26229. {
  26230. ma_bool32 cbResult = MA_TRUE;
  26231. MA_ASSERT(pContext != NULL);
  26232. MA_ASSERT(callback != NULL);
  26233. /* Playback. */
  26234. if (cbResult) {
  26235. ma_device_info deviceInfo;
  26236. MA_ZERO_OBJECT(&deviceInfo);
  26237. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  26238. deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */
  26239. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  26240. }
  26241. /* Capture. */
  26242. if (cbResult) {
  26243. ma_device_info deviceInfo;
  26244. MA_ZERO_OBJECT(&deviceInfo);
  26245. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  26246. deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */
  26247. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  26248. }
  26249. (void)cbResult; /* For silencing a static analysis warning. */
  26250. return MA_SUCCESS;
  26251. }
  26252. 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)
  26253. {
  26254. ma_jack_client_t* pClient;
  26255. ma_result result;
  26256. const char** ppPorts;
  26257. MA_ASSERT(pContext != NULL);
  26258. if (pDeviceID != NULL && pDeviceID->jack != 0) {
  26259. return MA_NO_DEVICE; /* Don't know the device. */
  26260. }
  26261. /* Name / Description */
  26262. if (deviceType == ma_device_type_playback) {
  26263. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  26264. } else {
  26265. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  26266. }
  26267. /* Jack only uses default devices. */
  26268. pDeviceInfo->isDefault = MA_TRUE;
  26269. /* Jack only supports f32 and has a specific channel count and sample rate. */
  26270. pDeviceInfo->nativeDataFormats[0].format = ma_format_f32;
  26271. /* The channel count and sample rate can only be determined by opening the device. */
  26272. result = ma_context_open_client__jack(pContext, &pClient);
  26273. if (result != MA_SUCCESS) {
  26274. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.");
  26275. return result;
  26276. }
  26277. pDeviceInfo->nativeDataFormats[0].sampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pClient);
  26278. pDeviceInfo->nativeDataFormats[0].channels = 0;
  26279. 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));
  26280. if (ppPorts == NULL) {
  26281. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
  26282. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  26283. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26284. }
  26285. while (ppPorts[pDeviceInfo->nativeDataFormats[0].channels] != NULL) {
  26286. pDeviceInfo->nativeDataFormats[0].channels += 1;
  26287. }
  26288. pDeviceInfo->nativeDataFormats[0].flags = 0;
  26289. pDeviceInfo->nativeDataFormatCount = 1;
  26290. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
  26291. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
  26292. (void)pContext;
  26293. return MA_SUCCESS;
  26294. }
  26295. static ma_result ma_device_uninit__jack(ma_device* pDevice)
  26296. {
  26297. ma_context* pContext;
  26298. MA_ASSERT(pDevice != NULL);
  26299. pContext = pDevice->pContext;
  26300. MA_ASSERT(pContext != NULL);
  26301. if (pDevice->jack.pClient != NULL) {
  26302. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDevice->jack.pClient);
  26303. }
  26304. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26305. ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  26306. ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks);
  26307. }
  26308. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26309. ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  26310. ma_free(pDevice->jack.ppPortsPlayback, &pDevice->pContext->allocationCallbacks);
  26311. }
  26312. return MA_SUCCESS;
  26313. }
  26314. static void ma_device__jack_shutdown_callback(void* pUserData)
  26315. {
  26316. /* JACK died. Stop the device. */
  26317. ma_device* pDevice = (ma_device*)pUserData;
  26318. MA_ASSERT(pDevice != NULL);
  26319. ma_device_stop(pDevice);
  26320. }
  26321. static int ma_device__jack_buffer_size_callback(ma_jack_nframes_t frameCount, void* pUserData)
  26322. {
  26323. ma_device* pDevice = (ma_device*)pUserData;
  26324. MA_ASSERT(pDevice != NULL);
  26325. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26326. size_t newBufferSize = frameCount * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
  26327. float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks);
  26328. if (pNewBuffer == NULL) {
  26329. return MA_OUT_OF_MEMORY;
  26330. }
  26331. ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  26332. pDevice->jack.pIntermediaryBufferCapture = pNewBuffer;
  26333. pDevice->playback.internalPeriodSizeInFrames = frameCount;
  26334. }
  26335. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26336. size_t newBufferSize = frameCount * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
  26337. float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks);
  26338. if (pNewBuffer == NULL) {
  26339. return MA_OUT_OF_MEMORY;
  26340. }
  26341. ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  26342. pDevice->jack.pIntermediaryBufferPlayback = pNewBuffer;
  26343. pDevice->playback.internalPeriodSizeInFrames = frameCount;
  26344. }
  26345. return 0;
  26346. }
  26347. static int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData)
  26348. {
  26349. ma_device* pDevice;
  26350. ma_context* pContext;
  26351. ma_uint32 iChannel;
  26352. pDevice = (ma_device*)pUserData;
  26353. MA_ASSERT(pDevice != NULL);
  26354. pContext = pDevice->pContext;
  26355. MA_ASSERT(pContext != NULL);
  26356. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26357. /* Channels need to be interleaved. */
  26358. for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
  26359. 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);
  26360. if (pSrc != NULL) {
  26361. float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel;
  26362. ma_jack_nframes_t iFrame;
  26363. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  26364. *pDst = *pSrc;
  26365. pDst += pDevice->capture.internalChannels;
  26366. pSrc += 1;
  26367. }
  26368. }
  26369. }
  26370. ma_device_handle_backend_data_callback(pDevice, NULL, pDevice->jack.pIntermediaryBufferCapture, frameCount);
  26371. }
  26372. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26373. ma_device_handle_backend_data_callback(pDevice, pDevice->jack.pIntermediaryBufferPlayback, NULL, frameCount);
  26374. /* Channels need to be deinterleaved. */
  26375. for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
  26376. float* pDst = (float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.ppPortsPlayback[iChannel], frameCount);
  26377. if (pDst != NULL) {
  26378. const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel;
  26379. ma_jack_nframes_t iFrame;
  26380. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  26381. *pDst = *pSrc;
  26382. pDst += 1;
  26383. pSrc += pDevice->playback.internalChannels;
  26384. }
  26385. }
  26386. }
  26387. }
  26388. return 0;
  26389. }
  26390. static ma_result ma_device_init__jack(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  26391. {
  26392. ma_result result;
  26393. ma_uint32 periodSizeInFrames;
  26394. MA_ASSERT(pConfig != NULL);
  26395. MA_ASSERT(pDevice != NULL);
  26396. if (pConfig->deviceType == ma_device_type_loopback) {
  26397. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Loopback mode not supported.");
  26398. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  26399. }
  26400. /* Only supporting default devices with JACK. */
  26401. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->pDeviceID != NULL && pDescriptorPlayback->pDeviceID->jack != 0) ||
  26402. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->pDeviceID != NULL && pDescriptorCapture->pDeviceID->jack != 0)) {
  26403. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Only default devices are supported.");
  26404. return MA_NO_DEVICE;
  26405. }
  26406. /* No exclusive mode with the JACK backend. */
  26407. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  26408. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  26409. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Exclusive mode not supported.");
  26410. return MA_SHARE_MODE_NOT_SUPPORTED;
  26411. }
  26412. /* Open the client. */
  26413. result = ma_context_open_client__jack(pDevice->pContext, (ma_jack_client_t**)&pDevice->jack.pClient);
  26414. if (result != MA_SUCCESS) {
  26415. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.");
  26416. return result;
  26417. }
  26418. /* Callbacks. */
  26419. 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) {
  26420. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback.");
  26421. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26422. }
  26423. 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) {
  26424. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback.");
  26425. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26426. }
  26427. ((ma_jack_on_shutdown_proc)pDevice->pContext->jack.jack_on_shutdown)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_shutdown_callback, pDevice);
  26428. /* The buffer size in frames can change. */
  26429. periodSizeInFrames = ((ma_jack_get_buffer_size_proc)pDevice->pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient);
  26430. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  26431. ma_uint32 iPort;
  26432. const char** ppPorts;
  26433. pDescriptorCapture->format = ma_format_f32;
  26434. pDescriptorCapture->channels = 0;
  26435. pDescriptorCapture->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
  26436. ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  26437. 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);
  26438. if (ppPorts == NULL) {
  26439. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  26440. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26441. }
  26442. /* Need to count the number of ports first so we can allocate some memory. */
  26443. while (ppPorts[pDescriptorCapture->channels] != NULL) {
  26444. pDescriptorCapture->channels += 1;
  26445. }
  26446. pDevice->jack.ppPortsCapture = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsCapture) * pDescriptorCapture->channels, &pDevice->pContext->allocationCallbacks);
  26447. if (pDevice->jack.ppPortsCapture == NULL) {
  26448. return MA_OUT_OF_MEMORY;
  26449. }
  26450. for (iPort = 0; iPort < pDescriptorCapture->channels; iPort += 1) {
  26451. char name[64];
  26452. ma_strcpy_s(name, sizeof(name), "capture");
  26453. ma_itoa_s((int)iPort, name+7, sizeof(name)-7, 10); /* 7 = length of "capture" */
  26454. 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);
  26455. if (pDevice->jack.ppPortsCapture[iPort] == NULL) {
  26456. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26457. ma_device_uninit__jack(pDevice);
  26458. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.");
  26459. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26460. }
  26461. }
  26462. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26463. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  26464. pDescriptorCapture->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */
  26465. pDevice->jack.pIntermediaryBufferCapture = (float*)ma_calloc(pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels), &pDevice->pContext->allocationCallbacks);
  26466. if (pDevice->jack.pIntermediaryBufferCapture == NULL) {
  26467. ma_device_uninit__jack(pDevice);
  26468. return MA_OUT_OF_MEMORY;
  26469. }
  26470. }
  26471. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  26472. ma_uint32 iPort;
  26473. const char** ppPorts;
  26474. pDescriptorPlayback->format = ma_format_f32;
  26475. pDescriptorPlayback->channels = 0;
  26476. pDescriptorPlayback->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
  26477. ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  26478. 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);
  26479. if (ppPorts == NULL) {
  26480. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  26481. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26482. }
  26483. /* Need to count the number of ports first so we can allocate some memory. */
  26484. while (ppPorts[pDescriptorPlayback->channels] != NULL) {
  26485. pDescriptorPlayback->channels += 1;
  26486. }
  26487. pDevice->jack.ppPortsPlayback = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsPlayback) * pDescriptorPlayback->channels, &pDevice->pContext->allocationCallbacks);
  26488. if (pDevice->jack.ppPortsPlayback == NULL) {
  26489. ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks);
  26490. return MA_OUT_OF_MEMORY;
  26491. }
  26492. for (iPort = 0; iPort < pDescriptorPlayback->channels; iPort += 1) {
  26493. char name[64];
  26494. ma_strcpy_s(name, sizeof(name), "playback");
  26495. ma_itoa_s((int)iPort, name+8, sizeof(name)-8, 10); /* 8 = length of "playback" */
  26496. 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);
  26497. if (pDevice->jack.ppPortsPlayback[iPort] == NULL) {
  26498. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26499. ma_device_uninit__jack(pDevice);
  26500. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.");
  26501. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  26502. }
  26503. }
  26504. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  26505. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  26506. pDescriptorPlayback->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */
  26507. pDevice->jack.pIntermediaryBufferPlayback = (float*)ma_calloc(pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels), &pDevice->pContext->allocationCallbacks);
  26508. if (pDevice->jack.pIntermediaryBufferPlayback == NULL) {
  26509. ma_device_uninit__jack(pDevice);
  26510. return MA_OUT_OF_MEMORY;
  26511. }
  26512. }
  26513. return MA_SUCCESS;
  26514. }
  26515. static ma_result ma_device_start__jack(ma_device* pDevice)
  26516. {
  26517. ma_context* pContext = pDevice->pContext;
  26518. int resultJACK;
  26519. size_t i;
  26520. resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient);
  26521. if (resultJACK != 0) {
  26522. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.");
  26523. return MA_FAILED_TO_START_BACKEND_DEVICE;
  26524. }
  26525. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  26526. 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);
  26527. if (ppServerPorts == NULL) {
  26528. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26529. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.");
  26530. return MA_ERROR;
  26531. }
  26532. for (i = 0; ppServerPorts[i] != NULL; ++i) {
  26533. const char* pServerPort = ppServerPorts[i];
  26534. const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.ppPortsCapture[i]);
  26535. resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pServerPort, pClientPort);
  26536. if (resultJACK != 0) {
  26537. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26538. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26539. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.");
  26540. return MA_ERROR;
  26541. }
  26542. }
  26543. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26544. }
  26545. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  26546. 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);
  26547. if (ppServerPorts == NULL) {
  26548. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26549. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.");
  26550. return MA_ERROR;
  26551. }
  26552. for (i = 0; ppServerPorts[i] != NULL; ++i) {
  26553. const char* pServerPort = ppServerPorts[i];
  26554. const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.ppPortsPlayback[i]);
  26555. resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pClientPort, pServerPort);
  26556. if (resultJACK != 0) {
  26557. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26558. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  26559. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.");
  26560. return MA_ERROR;
  26561. }
  26562. }
  26563. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  26564. }
  26565. return MA_SUCCESS;
  26566. }
  26567. static ma_result ma_device_stop__jack(ma_device* pDevice)
  26568. {
  26569. ma_context* pContext = pDevice->pContext;
  26570. if (((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient) != 0) {
  26571. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client.");
  26572. return MA_ERROR;
  26573. }
  26574. ma_device__on_notification_stopped(pDevice);
  26575. return MA_SUCCESS;
  26576. }
  26577. static ma_result ma_context_uninit__jack(ma_context* pContext)
  26578. {
  26579. MA_ASSERT(pContext != NULL);
  26580. MA_ASSERT(pContext->backend == ma_backend_jack);
  26581. ma_free(pContext->jack.pClientName, &pContext->allocationCallbacks);
  26582. pContext->jack.pClientName = NULL;
  26583. #ifndef MA_NO_RUNTIME_LINKING
  26584. ma_dlclose(ma_context_get_log(pContext), pContext->jack.jackSO);
  26585. #endif
  26586. return MA_SUCCESS;
  26587. }
  26588. static ma_result ma_context_init__jack(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  26589. {
  26590. #ifndef MA_NO_RUNTIME_LINKING
  26591. const char* libjackNames[] = {
  26592. #if defined(MA_WIN32)
  26593. "libjack.dll",
  26594. "libjack64.dll"
  26595. #endif
  26596. #if defined(MA_UNIX)
  26597. "libjack.so",
  26598. "libjack.so.0"
  26599. #endif
  26600. };
  26601. size_t i;
  26602. for (i = 0; i < ma_countof(libjackNames); ++i) {
  26603. pContext->jack.jackSO = ma_dlopen(ma_context_get_log(pContext), libjackNames[i]);
  26604. if (pContext->jack.jackSO != NULL) {
  26605. break;
  26606. }
  26607. }
  26608. if (pContext->jack.jackSO == NULL) {
  26609. return MA_NO_BACKEND;
  26610. }
  26611. pContext->jack.jack_client_open = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_client_open");
  26612. pContext->jack.jack_client_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_client_close");
  26613. pContext->jack.jack_client_name_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_client_name_size");
  26614. pContext->jack.jack_set_process_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_set_process_callback");
  26615. pContext->jack.jack_set_buffer_size_callback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_set_buffer_size_callback");
  26616. pContext->jack.jack_on_shutdown = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_on_shutdown");
  26617. pContext->jack.jack_get_sample_rate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_get_sample_rate");
  26618. pContext->jack.jack_get_buffer_size = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_get_buffer_size");
  26619. pContext->jack.jack_get_ports = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_get_ports");
  26620. pContext->jack.jack_activate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_activate");
  26621. pContext->jack.jack_deactivate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_deactivate");
  26622. pContext->jack.jack_connect = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_connect");
  26623. pContext->jack.jack_port_register = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_port_register");
  26624. pContext->jack.jack_port_name = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_port_name");
  26625. pContext->jack.jack_port_get_buffer = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_port_get_buffer");
  26626. pContext->jack.jack_free = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->jack.jackSO, "jack_free");
  26627. #else
  26628. /*
  26629. This strange assignment system is here just to ensure type safety of miniaudio's function pointer
  26630. types. If anything differs slightly the compiler should throw a warning.
  26631. */
  26632. ma_jack_client_open_proc _jack_client_open = jack_client_open;
  26633. ma_jack_client_close_proc _jack_client_close = jack_client_close;
  26634. ma_jack_client_name_size_proc _jack_client_name_size = jack_client_name_size;
  26635. ma_jack_set_process_callback_proc _jack_set_process_callback = jack_set_process_callback;
  26636. ma_jack_set_buffer_size_callback_proc _jack_set_buffer_size_callback = jack_set_buffer_size_callback;
  26637. ma_jack_on_shutdown_proc _jack_on_shutdown = jack_on_shutdown;
  26638. ma_jack_get_sample_rate_proc _jack_get_sample_rate = jack_get_sample_rate;
  26639. ma_jack_get_buffer_size_proc _jack_get_buffer_size = jack_get_buffer_size;
  26640. ma_jack_get_ports_proc _jack_get_ports = jack_get_ports;
  26641. ma_jack_activate_proc _jack_activate = jack_activate;
  26642. ma_jack_deactivate_proc _jack_deactivate = jack_deactivate;
  26643. ma_jack_connect_proc _jack_connect = jack_connect;
  26644. ma_jack_port_register_proc _jack_port_register = jack_port_register;
  26645. ma_jack_port_name_proc _jack_port_name = jack_port_name;
  26646. ma_jack_port_get_buffer_proc _jack_port_get_buffer = jack_port_get_buffer;
  26647. ma_jack_free_proc _jack_free = jack_free;
  26648. pContext->jack.jack_client_open = (ma_proc)_jack_client_open;
  26649. pContext->jack.jack_client_close = (ma_proc)_jack_client_close;
  26650. pContext->jack.jack_client_name_size = (ma_proc)_jack_client_name_size;
  26651. pContext->jack.jack_set_process_callback = (ma_proc)_jack_set_process_callback;
  26652. pContext->jack.jack_set_buffer_size_callback = (ma_proc)_jack_set_buffer_size_callback;
  26653. pContext->jack.jack_on_shutdown = (ma_proc)_jack_on_shutdown;
  26654. pContext->jack.jack_get_sample_rate = (ma_proc)_jack_get_sample_rate;
  26655. pContext->jack.jack_get_buffer_size = (ma_proc)_jack_get_buffer_size;
  26656. pContext->jack.jack_get_ports = (ma_proc)_jack_get_ports;
  26657. pContext->jack.jack_activate = (ma_proc)_jack_activate;
  26658. pContext->jack.jack_deactivate = (ma_proc)_jack_deactivate;
  26659. pContext->jack.jack_connect = (ma_proc)_jack_connect;
  26660. pContext->jack.jack_port_register = (ma_proc)_jack_port_register;
  26661. pContext->jack.jack_port_name = (ma_proc)_jack_port_name;
  26662. pContext->jack.jack_port_get_buffer = (ma_proc)_jack_port_get_buffer;
  26663. pContext->jack.jack_free = (ma_proc)_jack_free;
  26664. #endif
  26665. if (pConfig->jack.pClientName != NULL) {
  26666. pContext->jack.pClientName = ma_copy_string(pConfig->jack.pClientName, &pContext->allocationCallbacks);
  26667. }
  26668. pContext->jack.tryStartServer = pConfig->jack.tryStartServer;
  26669. /*
  26670. 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
  26671. a temporary client.
  26672. */
  26673. {
  26674. ma_jack_client_t* pDummyClient;
  26675. ma_result result = ma_context_open_client__jack(pContext, &pDummyClient);
  26676. if (result != MA_SUCCESS) {
  26677. ma_free(pContext->jack.pClientName, &pContext->allocationCallbacks);
  26678. #ifndef MA_NO_RUNTIME_LINKING
  26679. ma_dlclose(ma_context_get_log(pContext), pContext->jack.jackSO);
  26680. #endif
  26681. return MA_NO_BACKEND;
  26682. }
  26683. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient);
  26684. }
  26685. pCallbacks->onContextInit = ma_context_init__jack;
  26686. pCallbacks->onContextUninit = ma_context_uninit__jack;
  26687. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__jack;
  26688. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__jack;
  26689. pCallbacks->onDeviceInit = ma_device_init__jack;
  26690. pCallbacks->onDeviceUninit = ma_device_uninit__jack;
  26691. pCallbacks->onDeviceStart = ma_device_start__jack;
  26692. pCallbacks->onDeviceStop = ma_device_stop__jack;
  26693. pCallbacks->onDeviceRead = NULL; /* Not used because JACK is asynchronous. */
  26694. pCallbacks->onDeviceWrite = NULL; /* Not used because JACK is asynchronous. */
  26695. pCallbacks->onDeviceDataLoop = NULL; /* Not used because JACK is asynchronous. */
  26696. return MA_SUCCESS;
  26697. }
  26698. #endif /* JACK */
  26699. /******************************************************************************
  26700. Core Audio Backend
  26701. References
  26702. ==========
  26703. - Technical Note TN2091: Device input using the HAL Output Audio Unit
  26704. https://developer.apple.com/library/archive/technotes/tn2091/_index.html
  26705. ******************************************************************************/
  26706. #ifdef MA_HAS_COREAUDIO
  26707. #include <TargetConditionals.h>
  26708. #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1
  26709. #define MA_APPLE_MOBILE
  26710. #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
  26711. #define MA_APPLE_TV
  26712. #endif
  26713. #if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
  26714. #define MA_APPLE_WATCH
  26715. #endif
  26716. #if __has_feature(objc_arc)
  26717. #define MA_BRIDGE_TRANSFER __bridge_transfer
  26718. #define MA_BRIDGE_RETAINED __bridge_retained
  26719. #else
  26720. #define MA_BRIDGE_TRANSFER
  26721. #define MA_BRIDGE_RETAINED
  26722. #endif
  26723. #else
  26724. #define MA_APPLE_DESKTOP
  26725. #endif
  26726. #if defined(MA_APPLE_DESKTOP)
  26727. #include <CoreAudio/CoreAudio.h>
  26728. #else
  26729. #include <AVFoundation/AVFoundation.h>
  26730. #endif
  26731. #include <AudioToolbox/AudioToolbox.h>
  26732. /* CoreFoundation */
  26733. typedef Boolean (* ma_CFStringGetCString_proc)(CFStringRef theString, char* buffer, CFIndex bufferSize, CFStringEncoding encoding);
  26734. typedef void (* ma_CFRelease_proc)(CFTypeRef cf);
  26735. /* CoreAudio */
  26736. #if defined(MA_APPLE_DESKTOP)
  26737. typedef OSStatus (* ma_AudioObjectGetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* ioDataSize, void* outData);
  26738. typedef OSStatus (* ma_AudioObjectGetPropertyDataSize_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* outDataSize);
  26739. typedef OSStatus (* ma_AudioObjectSetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData);
  26740. typedef OSStatus (* ma_AudioObjectAddPropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData);
  26741. typedef OSStatus (* ma_AudioObjectRemovePropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData);
  26742. #endif
  26743. /* AudioToolbox */
  26744. typedef AudioComponent (* ma_AudioComponentFindNext_proc)(AudioComponent inComponent, const AudioComponentDescription* inDesc);
  26745. typedef OSStatus (* ma_AudioComponentInstanceDispose_proc)(AudioComponentInstance inInstance);
  26746. typedef OSStatus (* ma_AudioComponentInstanceNew_proc)(AudioComponent inComponent, AudioComponentInstance* outInstance);
  26747. typedef OSStatus (* ma_AudioOutputUnitStart_proc)(AudioUnit inUnit);
  26748. typedef OSStatus (* ma_AudioOutputUnitStop_proc)(AudioUnit inUnit);
  26749. typedef OSStatus (* ma_AudioUnitAddPropertyListener_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitPropertyListenerProc inProc, void* inProcUserData);
  26750. typedef OSStatus (* ma_AudioUnitGetPropertyInfo_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32* outDataSize, Boolean* outWriteable);
  26751. typedef OSStatus (* ma_AudioUnitGetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void* outData, UInt32* ioDataSize);
  26752. typedef OSStatus (* ma_AudioUnitSetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, const void* inData, UInt32 inDataSize);
  26753. typedef OSStatus (* ma_AudioUnitInitialize_proc)(AudioUnit inUnit);
  26754. typedef OSStatus (* ma_AudioUnitRender_proc)(AudioUnit inUnit, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData);
  26755. #define MA_COREAUDIO_OUTPUT_BUS 0
  26756. #define MA_COREAUDIO_INPUT_BUS 1
  26757. #if defined(MA_APPLE_DESKTOP)
  26758. static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit);
  26759. #endif
  26760. /*
  26761. Core Audio
  26762. So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation
  26763. apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose
  26764. needing to figure out how this darn thing works, I'm going to outline a few things here.
  26765. Since miniaudio is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be
  26766. 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
  26767. that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent
  26768. and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the
  26769. distinction between playback and capture in particular). Therefore, miniaudio is using the AudioObject API.
  26770. Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When
  26771. retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific
  26772. data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the
  26773. devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be
  26774. the central APIs for retrieving information about the system and specific devices.
  26775. To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a
  26776. structure with three variables and is used to identify which property you are getting or setting. The first is the "selector"
  26777. which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is
  26778. typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and
  26779. kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to
  26780. kAudioObjectPropertyElementMain in miniaudio's case. I don't know of any cases where this would be set to anything different.
  26781. Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size
  26782. of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property
  26783. address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the
  26784. size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of
  26785. AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count.
  26786. */
  26787. static ma_result ma_result_from_OSStatus(OSStatus status)
  26788. {
  26789. switch (status)
  26790. {
  26791. case noErr: return MA_SUCCESS;
  26792. #if defined(MA_APPLE_DESKTOP)
  26793. case kAudioHardwareNotRunningError: return MA_DEVICE_NOT_STARTED;
  26794. case kAudioHardwareUnspecifiedError: return MA_ERROR;
  26795. case kAudioHardwareUnknownPropertyError: return MA_INVALID_ARGS;
  26796. case kAudioHardwareBadPropertySizeError: return MA_INVALID_OPERATION;
  26797. case kAudioHardwareIllegalOperationError: return MA_INVALID_OPERATION;
  26798. case kAudioHardwareBadObjectError: return MA_INVALID_ARGS;
  26799. case kAudioHardwareBadDeviceError: return MA_INVALID_ARGS;
  26800. case kAudioHardwareBadStreamError: return MA_INVALID_ARGS;
  26801. case kAudioHardwareUnsupportedOperationError: return MA_INVALID_OPERATION;
  26802. case kAudioDeviceUnsupportedFormatError: return MA_FORMAT_NOT_SUPPORTED;
  26803. case kAudioDevicePermissionsError: return MA_ACCESS_DENIED;
  26804. #endif
  26805. default: return MA_ERROR;
  26806. }
  26807. }
  26808. #if 0
  26809. static ma_channel ma_channel_from_AudioChannelBitmap(AudioChannelBitmap bit)
  26810. {
  26811. switch (bit)
  26812. {
  26813. case kAudioChannelBit_Left: return MA_CHANNEL_LEFT;
  26814. case kAudioChannelBit_Right: return MA_CHANNEL_RIGHT;
  26815. case kAudioChannelBit_Center: return MA_CHANNEL_FRONT_CENTER;
  26816. case kAudioChannelBit_LFEScreen: return MA_CHANNEL_LFE;
  26817. case kAudioChannelBit_LeftSurround: return MA_CHANNEL_BACK_LEFT;
  26818. case kAudioChannelBit_RightSurround: return MA_CHANNEL_BACK_RIGHT;
  26819. case kAudioChannelBit_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER;
  26820. case kAudioChannelBit_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  26821. case kAudioChannelBit_CenterSurround: return MA_CHANNEL_BACK_CENTER;
  26822. case kAudioChannelBit_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT;
  26823. case kAudioChannelBit_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT;
  26824. case kAudioChannelBit_TopCenterSurround: return MA_CHANNEL_TOP_CENTER;
  26825. case kAudioChannelBit_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT;
  26826. case kAudioChannelBit_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER;
  26827. case kAudioChannelBit_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT;
  26828. case kAudioChannelBit_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT;
  26829. case kAudioChannelBit_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER;
  26830. case kAudioChannelBit_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT;
  26831. default: return MA_CHANNEL_NONE;
  26832. }
  26833. }
  26834. #endif
  26835. static ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescription* pDescription, ma_format* pFormatOut)
  26836. {
  26837. MA_ASSERT(pDescription != NULL);
  26838. MA_ASSERT(pFormatOut != NULL);
  26839. *pFormatOut = ma_format_unknown; /* Safety. */
  26840. /* There's a few things miniaudio doesn't support. */
  26841. if (pDescription->mFormatID != kAudioFormatLinearPCM) {
  26842. return MA_FORMAT_NOT_SUPPORTED;
  26843. }
  26844. /* We don't support any non-packed formats that are aligned high. */
  26845. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) != 0) {
  26846. return MA_FORMAT_NOT_SUPPORTED;
  26847. }
  26848. /* Only supporting native-endian. */
  26849. if ((ma_is_little_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) || (ma_is_big_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0)) {
  26850. return MA_FORMAT_NOT_SUPPORTED;
  26851. }
  26852. /* We are not currently supporting non-interleaved formats (this will be added in a future version of miniaudio). */
  26853. /*if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) {
  26854. return MA_FORMAT_NOT_SUPPORTED;
  26855. }*/
  26856. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) {
  26857. if (pDescription->mBitsPerChannel == 32) {
  26858. *pFormatOut = ma_format_f32;
  26859. return MA_SUCCESS;
  26860. }
  26861. } else {
  26862. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) != 0) {
  26863. if (pDescription->mBitsPerChannel == 16) {
  26864. *pFormatOut = ma_format_s16;
  26865. return MA_SUCCESS;
  26866. } else if (pDescription->mBitsPerChannel == 24) {
  26867. if (pDescription->mBytesPerFrame == (pDescription->mBitsPerChannel/8 * pDescription->mChannelsPerFrame)) {
  26868. *pFormatOut = ma_format_s24;
  26869. return MA_SUCCESS;
  26870. } else {
  26871. if (pDescription->mBytesPerFrame/pDescription->mChannelsPerFrame == sizeof(ma_int32)) {
  26872. /* TODO: Implement ma_format_s24_32. */
  26873. /**pFormatOut = ma_format_s24_32;*/
  26874. /*return MA_SUCCESS;*/
  26875. return MA_FORMAT_NOT_SUPPORTED;
  26876. }
  26877. }
  26878. } else if (pDescription->mBitsPerChannel == 32) {
  26879. *pFormatOut = ma_format_s32;
  26880. return MA_SUCCESS;
  26881. }
  26882. } else {
  26883. if (pDescription->mBitsPerChannel == 8) {
  26884. *pFormatOut = ma_format_u8;
  26885. return MA_SUCCESS;
  26886. }
  26887. }
  26888. }
  26889. /* Getting here means the format is not supported. */
  26890. return MA_FORMAT_NOT_SUPPORTED;
  26891. }
  26892. #if defined(MA_APPLE_DESKTOP)
  26893. static ma_channel ma_channel_from_AudioChannelLabel(AudioChannelLabel label)
  26894. {
  26895. switch (label)
  26896. {
  26897. case kAudioChannelLabel_Unknown: return MA_CHANNEL_NONE;
  26898. case kAudioChannelLabel_Unused: return MA_CHANNEL_NONE;
  26899. case kAudioChannelLabel_UseCoordinates: return MA_CHANNEL_NONE;
  26900. case kAudioChannelLabel_Left: return MA_CHANNEL_LEFT;
  26901. case kAudioChannelLabel_Right: return MA_CHANNEL_RIGHT;
  26902. case kAudioChannelLabel_Center: return MA_CHANNEL_FRONT_CENTER;
  26903. case kAudioChannelLabel_LFEScreen: return MA_CHANNEL_LFE;
  26904. case kAudioChannelLabel_LeftSurround: return MA_CHANNEL_BACK_LEFT;
  26905. case kAudioChannelLabel_RightSurround: return MA_CHANNEL_BACK_RIGHT;
  26906. case kAudioChannelLabel_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER;
  26907. case kAudioChannelLabel_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  26908. case kAudioChannelLabel_CenterSurround: return MA_CHANNEL_BACK_CENTER;
  26909. case kAudioChannelLabel_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT;
  26910. case kAudioChannelLabel_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT;
  26911. case kAudioChannelLabel_TopCenterSurround: return MA_CHANNEL_TOP_CENTER;
  26912. case kAudioChannelLabel_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT;
  26913. case kAudioChannelLabel_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER;
  26914. case kAudioChannelLabel_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT;
  26915. case kAudioChannelLabel_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT;
  26916. case kAudioChannelLabel_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER;
  26917. case kAudioChannelLabel_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT;
  26918. case kAudioChannelLabel_RearSurroundLeft: return MA_CHANNEL_BACK_LEFT;
  26919. case kAudioChannelLabel_RearSurroundRight: return MA_CHANNEL_BACK_RIGHT;
  26920. case kAudioChannelLabel_LeftWide: return MA_CHANNEL_SIDE_LEFT;
  26921. case kAudioChannelLabel_RightWide: return MA_CHANNEL_SIDE_RIGHT;
  26922. case kAudioChannelLabel_LFE2: return MA_CHANNEL_LFE;
  26923. case kAudioChannelLabel_LeftTotal: return MA_CHANNEL_LEFT;
  26924. case kAudioChannelLabel_RightTotal: return MA_CHANNEL_RIGHT;
  26925. case kAudioChannelLabel_HearingImpaired: return MA_CHANNEL_NONE;
  26926. case kAudioChannelLabel_Narration: return MA_CHANNEL_MONO;
  26927. case kAudioChannelLabel_Mono: return MA_CHANNEL_MONO;
  26928. case kAudioChannelLabel_DialogCentricMix: return MA_CHANNEL_MONO;
  26929. case kAudioChannelLabel_CenterSurroundDirect: return MA_CHANNEL_BACK_CENTER;
  26930. case kAudioChannelLabel_Haptic: return MA_CHANNEL_NONE;
  26931. case kAudioChannelLabel_Ambisonic_W: return MA_CHANNEL_NONE;
  26932. case kAudioChannelLabel_Ambisonic_X: return MA_CHANNEL_NONE;
  26933. case kAudioChannelLabel_Ambisonic_Y: return MA_CHANNEL_NONE;
  26934. case kAudioChannelLabel_Ambisonic_Z: return MA_CHANNEL_NONE;
  26935. case kAudioChannelLabel_MS_Mid: return MA_CHANNEL_LEFT;
  26936. case kAudioChannelLabel_MS_Side: return MA_CHANNEL_RIGHT;
  26937. case kAudioChannelLabel_XY_X: return MA_CHANNEL_LEFT;
  26938. case kAudioChannelLabel_XY_Y: return MA_CHANNEL_RIGHT;
  26939. case kAudioChannelLabel_HeadphonesLeft: return MA_CHANNEL_LEFT;
  26940. case kAudioChannelLabel_HeadphonesRight: return MA_CHANNEL_RIGHT;
  26941. case kAudioChannelLabel_ClickTrack: return MA_CHANNEL_NONE;
  26942. case kAudioChannelLabel_ForeignLanguage: return MA_CHANNEL_NONE;
  26943. case kAudioChannelLabel_Discrete: return MA_CHANNEL_NONE;
  26944. case kAudioChannelLabel_Discrete_0: return MA_CHANNEL_AUX_0;
  26945. case kAudioChannelLabel_Discrete_1: return MA_CHANNEL_AUX_1;
  26946. case kAudioChannelLabel_Discrete_2: return MA_CHANNEL_AUX_2;
  26947. case kAudioChannelLabel_Discrete_3: return MA_CHANNEL_AUX_3;
  26948. case kAudioChannelLabel_Discrete_4: return MA_CHANNEL_AUX_4;
  26949. case kAudioChannelLabel_Discrete_5: return MA_CHANNEL_AUX_5;
  26950. case kAudioChannelLabel_Discrete_6: return MA_CHANNEL_AUX_6;
  26951. case kAudioChannelLabel_Discrete_7: return MA_CHANNEL_AUX_7;
  26952. case kAudioChannelLabel_Discrete_8: return MA_CHANNEL_AUX_8;
  26953. case kAudioChannelLabel_Discrete_9: return MA_CHANNEL_AUX_9;
  26954. case kAudioChannelLabel_Discrete_10: return MA_CHANNEL_AUX_10;
  26955. case kAudioChannelLabel_Discrete_11: return MA_CHANNEL_AUX_11;
  26956. case kAudioChannelLabel_Discrete_12: return MA_CHANNEL_AUX_12;
  26957. case kAudioChannelLabel_Discrete_13: return MA_CHANNEL_AUX_13;
  26958. case kAudioChannelLabel_Discrete_14: return MA_CHANNEL_AUX_14;
  26959. case kAudioChannelLabel_Discrete_15: return MA_CHANNEL_AUX_15;
  26960. case kAudioChannelLabel_Discrete_65535: return MA_CHANNEL_NONE;
  26961. #if 0 /* Introduced in a later version of macOS. */
  26962. case kAudioChannelLabel_HOA_ACN: return MA_CHANNEL_NONE;
  26963. case kAudioChannelLabel_HOA_ACN_0: return MA_CHANNEL_AUX_0;
  26964. case kAudioChannelLabel_HOA_ACN_1: return MA_CHANNEL_AUX_1;
  26965. case kAudioChannelLabel_HOA_ACN_2: return MA_CHANNEL_AUX_2;
  26966. case kAudioChannelLabel_HOA_ACN_3: return MA_CHANNEL_AUX_3;
  26967. case kAudioChannelLabel_HOA_ACN_4: return MA_CHANNEL_AUX_4;
  26968. case kAudioChannelLabel_HOA_ACN_5: return MA_CHANNEL_AUX_5;
  26969. case kAudioChannelLabel_HOA_ACN_6: return MA_CHANNEL_AUX_6;
  26970. case kAudioChannelLabel_HOA_ACN_7: return MA_CHANNEL_AUX_7;
  26971. case kAudioChannelLabel_HOA_ACN_8: return MA_CHANNEL_AUX_8;
  26972. case kAudioChannelLabel_HOA_ACN_9: return MA_CHANNEL_AUX_9;
  26973. case kAudioChannelLabel_HOA_ACN_10: return MA_CHANNEL_AUX_10;
  26974. case kAudioChannelLabel_HOA_ACN_11: return MA_CHANNEL_AUX_11;
  26975. case kAudioChannelLabel_HOA_ACN_12: return MA_CHANNEL_AUX_12;
  26976. case kAudioChannelLabel_HOA_ACN_13: return MA_CHANNEL_AUX_13;
  26977. case kAudioChannelLabel_HOA_ACN_14: return MA_CHANNEL_AUX_14;
  26978. case kAudioChannelLabel_HOA_ACN_15: return MA_CHANNEL_AUX_15;
  26979. case kAudioChannelLabel_HOA_ACN_65024: return MA_CHANNEL_NONE;
  26980. #endif
  26981. default: return MA_CHANNEL_NONE;
  26982. }
  26983. }
  26984. static ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChannelLayout, ma_channel* pChannelMap, size_t channelMapCap)
  26985. {
  26986. MA_ASSERT(pChannelLayout != NULL);
  26987. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) {
  26988. UInt32 iChannel;
  26989. for (iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions && iChannel < channelMapCap; ++iChannel) {
  26990. pChannelMap[iChannel] = ma_channel_from_AudioChannelLabel(pChannelLayout->mChannelDescriptions[iChannel].mChannelLabel);
  26991. }
  26992. } else
  26993. #if 0
  26994. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
  26995. /* This is the same kind of system that's used by Windows audio APIs. */
  26996. UInt32 iChannel = 0;
  26997. UInt32 iBit;
  26998. AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap;
  26999. for (iBit = 0; iBit < 32 && iChannel < channelMapCap; ++iBit) {
  27000. AudioChannelBitmap bit = bitmap & (1 << iBit);
  27001. if (bit != 0) {
  27002. pChannelMap[iChannel++] = ma_channel_from_AudioChannelBit(bit);
  27003. }
  27004. }
  27005. } else
  27006. #endif
  27007. {
  27008. /*
  27009. 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
  27010. be updated to determine the mapping based on the tag.
  27011. */
  27012. UInt32 channelCount;
  27013. /* Our channel map retrieval APIs below take 32-bit integers, so we'll want to clamp the channel map capacity. */
  27014. if (channelMapCap > 0xFFFFFFFF) {
  27015. channelMapCap = 0xFFFFFFFF;
  27016. }
  27017. channelCount = ma_min(AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag), (UInt32)channelMapCap);
  27018. switch (pChannelLayout->mChannelLayoutTag)
  27019. {
  27020. case kAudioChannelLayoutTag_Mono:
  27021. case kAudioChannelLayoutTag_Stereo:
  27022. case kAudioChannelLayoutTag_StereoHeadphones:
  27023. case kAudioChannelLayoutTag_MatrixStereo:
  27024. case kAudioChannelLayoutTag_MidSide:
  27025. case kAudioChannelLayoutTag_XY:
  27026. case kAudioChannelLayoutTag_Binaural:
  27027. case kAudioChannelLayoutTag_Ambisonic_B_Format:
  27028. {
  27029. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  27030. } break;
  27031. case kAudioChannelLayoutTag_Octagonal:
  27032. {
  27033. pChannelMap[7] = MA_CHANNEL_SIDE_RIGHT;
  27034. pChannelMap[6] = MA_CHANNEL_SIDE_LEFT;
  27035. } MA_FALLTHROUGH; /* Intentional fallthrough. */
  27036. case kAudioChannelLayoutTag_Hexagonal:
  27037. {
  27038. pChannelMap[5] = MA_CHANNEL_BACK_CENTER;
  27039. } MA_FALLTHROUGH; /* Intentional fallthrough. */
  27040. case kAudioChannelLayoutTag_Pentagonal:
  27041. {
  27042. pChannelMap[4] = MA_CHANNEL_FRONT_CENTER;
  27043. } MA_FALLTHROUGH; /* Intentional fallthrough. */
  27044. case kAudioChannelLayoutTag_Quadraphonic:
  27045. {
  27046. pChannelMap[3] = MA_CHANNEL_BACK_RIGHT;
  27047. pChannelMap[2] = MA_CHANNEL_BACK_LEFT;
  27048. pChannelMap[1] = MA_CHANNEL_RIGHT;
  27049. pChannelMap[0] = MA_CHANNEL_LEFT;
  27050. } break;
  27051. /* TODO: Add support for more tags here. */
  27052. default:
  27053. {
  27054. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  27055. } break;
  27056. }
  27057. }
  27058. return MA_SUCCESS;
  27059. }
  27060. #if (defined(MAC_OS_VERSION_12_0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_12_0) || \
  27061. (defined(__IPHONE_15_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_0)
  27062. #define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMain
  27063. #else
  27064. /* kAudioObjectPropertyElementMaster is deprecated. */
  27065. #define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMaster
  27066. #endif
  27067. static ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) /* NOTE: Free the returned buffer with ma_free(). */
  27068. {
  27069. AudioObjectPropertyAddress propAddressDevices;
  27070. UInt32 deviceObjectsDataSize;
  27071. OSStatus status;
  27072. AudioObjectID* pDeviceObjectIDs;
  27073. MA_ASSERT(pContext != NULL);
  27074. MA_ASSERT(pDeviceCount != NULL);
  27075. MA_ASSERT(ppDeviceObjectIDs != NULL);
  27076. /* Safety. */
  27077. *pDeviceCount = 0;
  27078. *ppDeviceObjectIDs = NULL;
  27079. propAddressDevices.mSelector = kAudioHardwarePropertyDevices;
  27080. propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal;
  27081. propAddressDevices.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27082. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize);
  27083. if (status != noErr) {
  27084. return ma_result_from_OSStatus(status);
  27085. }
  27086. pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize, &pContext->allocationCallbacks);
  27087. if (pDeviceObjectIDs == NULL) {
  27088. return MA_OUT_OF_MEMORY;
  27089. }
  27090. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize, pDeviceObjectIDs);
  27091. if (status != noErr) {
  27092. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27093. return ma_result_from_OSStatus(status);
  27094. }
  27095. *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID);
  27096. *ppDeviceObjectIDs = pDeviceObjectIDs;
  27097. return MA_SUCCESS;
  27098. }
  27099. static ma_result ma_get_AudioObject_uid_as_CFStringRef(ma_context* pContext, AudioObjectID objectID, CFStringRef* pUID)
  27100. {
  27101. AudioObjectPropertyAddress propAddress;
  27102. UInt32 dataSize;
  27103. OSStatus status;
  27104. MA_ASSERT(pContext != NULL);
  27105. propAddress.mSelector = kAudioDevicePropertyDeviceUID;
  27106. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  27107. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27108. dataSize = sizeof(*pUID);
  27109. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID);
  27110. if (status != noErr) {
  27111. return ma_result_from_OSStatus(status);
  27112. }
  27113. return MA_SUCCESS;
  27114. }
  27115. static ma_result ma_get_AudioObject_uid(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut)
  27116. {
  27117. CFStringRef uid;
  27118. ma_result result;
  27119. MA_ASSERT(pContext != NULL);
  27120. result = ma_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid);
  27121. if (result != MA_SUCCESS) {
  27122. return result;
  27123. }
  27124. if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(uid, bufferOut, bufferSize, kCFStringEncodingUTF8)) {
  27125. return MA_ERROR;
  27126. }
  27127. ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(uid);
  27128. return MA_SUCCESS;
  27129. }
  27130. static ma_result ma_get_AudioObject_name(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut)
  27131. {
  27132. AudioObjectPropertyAddress propAddress;
  27133. CFStringRef deviceName = NULL;
  27134. UInt32 dataSize;
  27135. OSStatus status;
  27136. MA_ASSERT(pContext != NULL);
  27137. propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString;
  27138. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  27139. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27140. dataSize = sizeof(deviceName);
  27141. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName);
  27142. if (status != noErr) {
  27143. return ma_result_from_OSStatus(status);
  27144. }
  27145. if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(deviceName, bufferOut, bufferSize, kCFStringEncodingUTF8)) {
  27146. return MA_ERROR;
  27147. }
  27148. ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(deviceName);
  27149. return MA_SUCCESS;
  27150. }
  27151. static ma_bool32 ma_does_AudioObject_support_scope(ma_context* pContext, AudioObjectID deviceObjectID, AudioObjectPropertyScope scope)
  27152. {
  27153. AudioObjectPropertyAddress propAddress;
  27154. UInt32 dataSize;
  27155. OSStatus status;
  27156. AudioBufferList* pBufferList;
  27157. ma_bool32 isSupported;
  27158. MA_ASSERT(pContext != NULL);
  27159. /* 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. */
  27160. propAddress.mSelector = kAudioDevicePropertyStreamConfiguration;
  27161. propAddress.mScope = scope;
  27162. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27163. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27164. if (status != noErr) {
  27165. return MA_FALSE;
  27166. }
  27167. pBufferList = (AudioBufferList*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27168. if (pBufferList == NULL) {
  27169. return MA_FALSE; /* Out of memory. */
  27170. }
  27171. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pBufferList);
  27172. if (status != noErr) {
  27173. ma_free(pBufferList, &pContext->allocationCallbacks);
  27174. return MA_FALSE;
  27175. }
  27176. isSupported = MA_FALSE;
  27177. if (pBufferList->mNumberBuffers > 0) {
  27178. isSupported = MA_TRUE;
  27179. }
  27180. ma_free(pBufferList, &pContext->allocationCallbacks);
  27181. return isSupported;
  27182. }
  27183. static ma_bool32 ma_does_AudioObject_support_playback(ma_context* pContext, AudioObjectID deviceObjectID)
  27184. {
  27185. return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeOutput);
  27186. }
  27187. static ma_bool32 ma_does_AudioObject_support_capture(ma_context* pContext, AudioObjectID deviceObjectID)
  27188. {
  27189. return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeInput);
  27190. }
  27191. 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(). */
  27192. {
  27193. AudioObjectPropertyAddress propAddress;
  27194. UInt32 dataSize;
  27195. OSStatus status;
  27196. AudioStreamRangedDescription* pDescriptions;
  27197. MA_ASSERT(pContext != NULL);
  27198. MA_ASSERT(pDescriptionCount != NULL);
  27199. MA_ASSERT(ppDescriptions != NULL);
  27200. /*
  27201. TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My
  27202. MacBook Pro uses s24/32 format, however, which miniaudio does not currently support.
  27203. */
  27204. propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; /*kAudioStreamPropertyAvailablePhysicalFormats;*/
  27205. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27206. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27207. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27208. if (status != noErr) {
  27209. return ma_result_from_OSStatus(status);
  27210. }
  27211. pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27212. if (pDescriptions == NULL) {
  27213. return MA_OUT_OF_MEMORY;
  27214. }
  27215. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pDescriptions);
  27216. if (status != noErr) {
  27217. ma_free(pDescriptions, &pContext->allocationCallbacks);
  27218. return ma_result_from_OSStatus(status);
  27219. }
  27220. *pDescriptionCount = dataSize / sizeof(*pDescriptions);
  27221. *ppDescriptions = pDescriptions;
  27222. return MA_SUCCESS;
  27223. }
  27224. 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(). */
  27225. {
  27226. AudioObjectPropertyAddress propAddress;
  27227. UInt32 dataSize;
  27228. OSStatus status;
  27229. AudioChannelLayout* pChannelLayout;
  27230. MA_ASSERT(pContext != NULL);
  27231. MA_ASSERT(ppChannelLayout != NULL);
  27232. *ppChannelLayout = NULL; /* Safety. */
  27233. propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
  27234. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27235. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27236. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27237. if (status != noErr) {
  27238. return ma_result_from_OSStatus(status);
  27239. }
  27240. pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27241. if (pChannelLayout == NULL) {
  27242. return MA_OUT_OF_MEMORY;
  27243. }
  27244. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pChannelLayout);
  27245. if (status != noErr) {
  27246. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27247. return ma_result_from_OSStatus(status);
  27248. }
  27249. *ppChannelLayout = pChannelLayout;
  27250. return MA_SUCCESS;
  27251. }
  27252. static ma_result ma_get_AudioObject_channel_count(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pChannelCount)
  27253. {
  27254. AudioChannelLayout* pChannelLayout;
  27255. ma_result result;
  27256. MA_ASSERT(pContext != NULL);
  27257. MA_ASSERT(pChannelCount != NULL);
  27258. *pChannelCount = 0; /* Safety. */
  27259. result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout);
  27260. if (result != MA_SUCCESS) {
  27261. return result;
  27262. }
  27263. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) {
  27264. *pChannelCount = pChannelLayout->mNumberChannelDescriptions;
  27265. } else if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
  27266. *pChannelCount = ma_count_set_bits(pChannelLayout->mChannelBitmap);
  27267. } else {
  27268. *pChannelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag);
  27269. }
  27270. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27271. return MA_SUCCESS;
  27272. }
  27273. #if 0
  27274. static ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap)
  27275. {
  27276. AudioChannelLayout* pChannelLayout;
  27277. ma_result result;
  27278. MA_ASSERT(pContext != NULL);
  27279. result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout);
  27280. if (result != MA_SUCCESS) {
  27281. return result; /* Rather than always failing here, would it be more robust to simply assume a default? */
  27282. }
  27283. result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap);
  27284. if (result != MA_SUCCESS) {
  27285. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27286. return result;
  27287. }
  27288. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27289. return result;
  27290. }
  27291. #endif
  27292. 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(). */
  27293. {
  27294. AudioObjectPropertyAddress propAddress;
  27295. UInt32 dataSize;
  27296. OSStatus status;
  27297. AudioValueRange* pSampleRateRanges;
  27298. MA_ASSERT(pContext != NULL);
  27299. MA_ASSERT(pSampleRateRangesCount != NULL);
  27300. MA_ASSERT(ppSampleRateRanges != NULL);
  27301. /* Safety. */
  27302. *pSampleRateRangesCount = 0;
  27303. *ppSampleRateRanges = NULL;
  27304. propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  27305. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27306. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27307. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  27308. if (status != noErr) {
  27309. return ma_result_from_OSStatus(status);
  27310. }
  27311. pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  27312. if (pSampleRateRanges == NULL) {
  27313. return MA_OUT_OF_MEMORY;
  27314. }
  27315. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pSampleRateRanges);
  27316. if (status != noErr) {
  27317. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27318. return ma_result_from_OSStatus(status);
  27319. }
  27320. *pSampleRateRangesCount = dataSize / sizeof(*pSampleRateRanges);
  27321. *ppSampleRateRanges = pSampleRateRanges;
  27322. return MA_SUCCESS;
  27323. }
  27324. #if 0
  27325. 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)
  27326. {
  27327. UInt32 sampleRateRangeCount;
  27328. AudioValueRange* pSampleRateRanges;
  27329. ma_result result;
  27330. MA_ASSERT(pContext != NULL);
  27331. MA_ASSERT(pSampleRateOut != NULL);
  27332. *pSampleRateOut = 0; /* Safety. */
  27333. result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges);
  27334. if (result != MA_SUCCESS) {
  27335. return result;
  27336. }
  27337. if (sampleRateRangeCount == 0) {
  27338. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27339. return MA_ERROR; /* Should never hit this case should we? */
  27340. }
  27341. if (sampleRateIn == 0) {
  27342. /* Search in order of miniaudio's preferred priority. */
  27343. UInt32 iMALSampleRate;
  27344. for (iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) {
  27345. ma_uint32 malSampleRate = g_maStandardSampleRatePriorities[iMALSampleRate];
  27346. UInt32 iCASampleRate;
  27347. for (iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) {
  27348. AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate];
  27349. if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) {
  27350. *pSampleRateOut = malSampleRate;
  27351. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27352. return MA_SUCCESS;
  27353. }
  27354. }
  27355. }
  27356. /*
  27357. 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
  27358. case we just fall back to the first one reported by Core Audio.
  27359. */
  27360. MA_ASSERT(sampleRateRangeCount > 0);
  27361. *pSampleRateOut = pSampleRateRanges[0].mMinimum;
  27362. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27363. return MA_SUCCESS;
  27364. } else {
  27365. /* Find the closest match to this sample rate. */
  27366. UInt32 currentAbsoluteDifference = INT32_MAX;
  27367. UInt32 iCurrentClosestRange = (UInt32)-1;
  27368. UInt32 iRange;
  27369. for (iRange = 0; iRange < sampleRateRangeCount; ++iRange) {
  27370. if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) {
  27371. *pSampleRateOut = sampleRateIn;
  27372. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27373. return MA_SUCCESS;
  27374. } else {
  27375. UInt32 absoluteDifference;
  27376. if (pSampleRateRanges[iRange].mMinimum > sampleRateIn) {
  27377. absoluteDifference = pSampleRateRanges[iRange].mMinimum - sampleRateIn;
  27378. } else {
  27379. absoluteDifference = sampleRateIn - pSampleRateRanges[iRange].mMaximum;
  27380. }
  27381. if (currentAbsoluteDifference > absoluteDifference) {
  27382. currentAbsoluteDifference = absoluteDifference;
  27383. iCurrentClosestRange = iRange;
  27384. }
  27385. }
  27386. }
  27387. MA_ASSERT(iCurrentClosestRange != (UInt32)-1);
  27388. *pSampleRateOut = pSampleRateRanges[iCurrentClosestRange].mMinimum;
  27389. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27390. return MA_SUCCESS;
  27391. }
  27392. /* Should never get here, but it would mean we weren't able to find any suitable sample rates. */
  27393. /*ma_free(pSampleRateRanges, &pContext->allocationCallbacks);*/
  27394. /*return MA_ERROR;*/
  27395. }
  27396. #endif
  27397. 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)
  27398. {
  27399. AudioObjectPropertyAddress propAddress;
  27400. AudioValueRange bufferSizeRange;
  27401. UInt32 dataSize;
  27402. OSStatus status;
  27403. MA_ASSERT(pContext != NULL);
  27404. MA_ASSERT(pBufferSizeInFramesOut != NULL);
  27405. *pBufferSizeInFramesOut = 0; /* Safety. */
  27406. propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  27407. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27408. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27409. dataSize = sizeof(bufferSizeRange);
  27410. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange);
  27411. if (status != noErr) {
  27412. return ma_result_from_OSStatus(status);
  27413. }
  27414. /* This is just a clamp. */
  27415. if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) {
  27416. *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMinimum;
  27417. } else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) {
  27418. *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMaximum;
  27419. } else {
  27420. *pBufferSizeInFramesOut = bufferSizeInFramesIn;
  27421. }
  27422. return MA_SUCCESS;
  27423. }
  27424. static ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pPeriodSizeInOut)
  27425. {
  27426. ma_result result;
  27427. ma_uint32 chosenBufferSizeInFrames;
  27428. AudioObjectPropertyAddress propAddress;
  27429. UInt32 dataSize;
  27430. OSStatus status;
  27431. MA_ASSERT(pContext != NULL);
  27432. result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pPeriodSizeInOut, &chosenBufferSizeInFrames);
  27433. if (result != MA_SUCCESS) {
  27434. return result;
  27435. }
  27436. /* Try setting the size of the buffer... If this fails we just use whatever is currently set. */
  27437. propAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
  27438. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27439. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27440. ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames);
  27441. /* Get the actual size of the buffer. */
  27442. dataSize = sizeof(*pPeriodSizeInOut);
  27443. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames);
  27444. if (status != noErr) {
  27445. return ma_result_from_OSStatus(status);
  27446. }
  27447. *pPeriodSizeInOut = chosenBufferSizeInFrames;
  27448. return MA_SUCCESS;
  27449. }
  27450. static ma_result ma_find_default_AudioObjectID(ma_context* pContext, ma_device_type deviceType, AudioObjectID* pDeviceObjectID)
  27451. {
  27452. AudioObjectPropertyAddress propAddressDefaultDevice;
  27453. UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID);
  27454. AudioObjectID defaultDeviceObjectID;
  27455. OSStatus status;
  27456. MA_ASSERT(pContext != NULL);
  27457. MA_ASSERT(pDeviceObjectID != NULL);
  27458. /* Safety. */
  27459. *pDeviceObjectID = 0;
  27460. propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal;
  27461. propAddressDefaultDevice.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27462. if (deviceType == ma_device_type_playback) {
  27463. propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  27464. } else {
  27465. propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  27466. }
  27467. defaultDeviceObjectIDSize = sizeof(AudioObjectID);
  27468. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID);
  27469. if (status == noErr) {
  27470. *pDeviceObjectID = defaultDeviceObjectID;
  27471. return MA_SUCCESS;
  27472. }
  27473. /* If we get here it means we couldn't find the device. */
  27474. return MA_NO_DEVICE;
  27475. }
  27476. static ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, AudioObjectID* pDeviceObjectID)
  27477. {
  27478. MA_ASSERT(pContext != NULL);
  27479. MA_ASSERT(pDeviceObjectID != NULL);
  27480. /* Safety. */
  27481. *pDeviceObjectID = 0;
  27482. if (pDeviceID == NULL) {
  27483. /* Default device. */
  27484. return ma_find_default_AudioObjectID(pContext, deviceType, pDeviceObjectID);
  27485. } else {
  27486. /* Explicit device. */
  27487. UInt32 deviceCount;
  27488. AudioObjectID* pDeviceObjectIDs;
  27489. ma_result result;
  27490. UInt32 iDevice;
  27491. result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
  27492. if (result != MA_SUCCESS) {
  27493. return result;
  27494. }
  27495. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  27496. AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice];
  27497. char uid[256];
  27498. if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(uid), uid) != MA_SUCCESS) {
  27499. continue;
  27500. }
  27501. if (deviceType == ma_device_type_playback) {
  27502. if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) {
  27503. if (strcmp(uid, pDeviceID->coreaudio) == 0) {
  27504. *pDeviceObjectID = deviceObjectID;
  27505. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27506. return MA_SUCCESS;
  27507. }
  27508. }
  27509. } else {
  27510. if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) {
  27511. if (strcmp(uid, pDeviceID->coreaudio) == 0) {
  27512. *pDeviceObjectID = deviceObjectID;
  27513. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27514. return MA_SUCCESS;
  27515. }
  27516. }
  27517. }
  27518. }
  27519. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27520. }
  27521. /* If we get here it means we couldn't find the device. */
  27522. return MA_NO_DEVICE;
  27523. }
  27524. 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)
  27525. {
  27526. UInt32 deviceFormatDescriptionCount;
  27527. AudioStreamRangedDescription* pDeviceFormatDescriptions;
  27528. ma_result result;
  27529. ma_uint32 desiredSampleRate;
  27530. ma_uint32 desiredChannelCount;
  27531. ma_format desiredFormat;
  27532. AudioStreamBasicDescription bestDeviceFormatSoFar;
  27533. ma_bool32 hasSupportedFormat;
  27534. UInt32 iFormat;
  27535. result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions);
  27536. if (result != MA_SUCCESS) {
  27537. return result;
  27538. }
  27539. desiredSampleRate = sampleRate;
  27540. if (desiredSampleRate == 0) {
  27541. desiredSampleRate = pOrigFormat->mSampleRate;
  27542. }
  27543. desiredChannelCount = channels;
  27544. if (desiredChannelCount == 0) {
  27545. desiredChannelCount = pOrigFormat->mChannelsPerFrame;
  27546. }
  27547. desiredFormat = format;
  27548. if (desiredFormat == ma_format_unknown) {
  27549. result = ma_format_from_AudioStreamBasicDescription(pOrigFormat, &desiredFormat);
  27550. if (result != MA_SUCCESS || desiredFormat == ma_format_unknown) {
  27551. desiredFormat = g_maFormatPriorities[0];
  27552. }
  27553. }
  27554. /*
  27555. 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
  27556. 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.
  27557. */
  27558. MA_ZERO_OBJECT(&bestDeviceFormatSoFar);
  27559. hasSupportedFormat = MA_FALSE;
  27560. for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) {
  27561. ma_format format;
  27562. ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &format);
  27563. if (formatResult == MA_SUCCESS && format != ma_format_unknown) {
  27564. hasSupportedFormat = MA_TRUE;
  27565. bestDeviceFormatSoFar = pDeviceFormatDescriptions[iFormat].mFormat;
  27566. break;
  27567. }
  27568. }
  27569. if (!hasSupportedFormat) {
  27570. ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks);
  27571. return MA_FORMAT_NOT_SUPPORTED;
  27572. }
  27573. for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) {
  27574. AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat;
  27575. ma_format thisSampleFormat;
  27576. ma_result formatResult;
  27577. ma_format bestSampleFormatSoFar;
  27578. /* If the format is not supported by miniaudio we need to skip this one entirely. */
  27579. formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat);
  27580. if (formatResult != MA_SUCCESS || thisSampleFormat == ma_format_unknown) {
  27581. continue; /* The format is not supported by miniaudio. Skip. */
  27582. }
  27583. ma_format_from_AudioStreamBasicDescription(&bestDeviceFormatSoFar, &bestSampleFormatSoFar);
  27584. /* Getting here means the format is supported by miniaudio which makes this format a candidate. */
  27585. if (thisDeviceFormat.mSampleRate != desiredSampleRate) {
  27586. /*
  27587. The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format
  27588. so far has an equal sample rate we can just ignore this one.
  27589. */
  27590. if (bestDeviceFormatSoFar.mSampleRate == desiredSampleRate) {
  27591. 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. */
  27592. } else {
  27593. /* In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. */
  27594. if (thisDeviceFormat.mChannelsPerFrame != desiredChannelCount) {
  27595. /* This format has a different sample rate _and_ a different channel count. */
  27596. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  27597. continue; /* No change to the best format. */
  27598. } else {
  27599. /*
  27600. Both this format and the best so far have different sample rates and different channel counts. Whichever has the
  27601. best format is the new best.
  27602. */
  27603. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27604. bestDeviceFormatSoFar = thisDeviceFormat;
  27605. continue;
  27606. } else {
  27607. continue; /* No change to the best format. */
  27608. }
  27609. }
  27610. } else {
  27611. /* This format has a different sample rate but the desired channel count. */
  27612. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  27613. /* Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. */
  27614. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27615. bestDeviceFormatSoFar = thisDeviceFormat;
  27616. continue;
  27617. } else {
  27618. continue; /* No change to the best format for now. */
  27619. }
  27620. } else {
  27621. /* This format has the desired channel count, but the best so far does not. We have a new best. */
  27622. bestDeviceFormatSoFar = thisDeviceFormat;
  27623. continue;
  27624. }
  27625. }
  27626. }
  27627. } else {
  27628. /*
  27629. The sample rates match which makes this format a very high priority contender. If the best format so far has a different
  27630. sample rate it needs to be replaced with this one.
  27631. */
  27632. if (bestDeviceFormatSoFar.mSampleRate != desiredSampleRate) {
  27633. bestDeviceFormatSoFar = thisDeviceFormat;
  27634. continue;
  27635. } else {
  27636. /* In this case both this format and the best format so far have the same sample rate. Check the channel count next. */
  27637. if (thisDeviceFormat.mChannelsPerFrame == desiredChannelCount) {
  27638. /*
  27639. In this case this format has the same channel count as what the client is requesting. If the best format so far has
  27640. a different count, this one becomes the new best.
  27641. */
  27642. if (bestDeviceFormatSoFar.mChannelsPerFrame != desiredChannelCount) {
  27643. bestDeviceFormatSoFar = thisDeviceFormat;
  27644. continue;
  27645. } else {
  27646. /* In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. */
  27647. if (thisSampleFormat == desiredFormat) {
  27648. bestDeviceFormatSoFar = thisDeviceFormat;
  27649. break; /* Found the exact match. */
  27650. } else {
  27651. /* The formats are different. The new best format is the one with the highest priority format according to miniaudio. */
  27652. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27653. bestDeviceFormatSoFar = thisDeviceFormat;
  27654. continue;
  27655. } else {
  27656. continue; /* No change to the best format for now. */
  27657. }
  27658. }
  27659. }
  27660. } else {
  27661. /*
  27662. In this case the channel count is different to what the client has requested. If the best so far has the same channel
  27663. count as the requested count then it remains the best.
  27664. */
  27665. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  27666. continue;
  27667. } else {
  27668. /*
  27669. This is the case where both have the same sample rate (good) but different channel counts. Right now both have about
  27670. the same priority, but we need to compare the format now.
  27671. */
  27672. if (thisSampleFormat == bestSampleFormatSoFar) {
  27673. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  27674. bestDeviceFormatSoFar = thisDeviceFormat;
  27675. continue;
  27676. } else {
  27677. continue; /* No change to the best format for now. */
  27678. }
  27679. }
  27680. }
  27681. }
  27682. }
  27683. }
  27684. }
  27685. *pFormat = bestDeviceFormatSoFar;
  27686. ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks);
  27687. return MA_SUCCESS;
  27688. }
  27689. static ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap)
  27690. {
  27691. AudioUnitScope deviceScope;
  27692. AudioUnitElement deviceBus;
  27693. UInt32 channelLayoutSize;
  27694. OSStatus status;
  27695. AudioChannelLayout* pChannelLayout;
  27696. ma_result result;
  27697. MA_ASSERT(pContext != NULL);
  27698. if (deviceType == ma_device_type_playback) {
  27699. deviceScope = kAudioUnitScope_Input;
  27700. deviceBus = MA_COREAUDIO_OUTPUT_BUS;
  27701. } else {
  27702. deviceScope = kAudioUnitScope_Output;
  27703. deviceBus = MA_COREAUDIO_INPUT_BUS;
  27704. }
  27705. status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL);
  27706. if (status != noErr) {
  27707. return ma_result_from_OSStatus(status);
  27708. }
  27709. pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize, &pContext->allocationCallbacks);
  27710. if (pChannelLayout == NULL) {
  27711. return MA_OUT_OF_MEMORY;
  27712. }
  27713. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, pChannelLayout, &channelLayoutSize);
  27714. if (status != noErr) {
  27715. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27716. return ma_result_from_OSStatus(status);
  27717. }
  27718. result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap);
  27719. if (result != MA_SUCCESS) {
  27720. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27721. return result;
  27722. }
  27723. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  27724. return MA_SUCCESS;
  27725. }
  27726. #endif /* MA_APPLE_DESKTOP */
  27727. #if !defined(MA_APPLE_DESKTOP)
  27728. static void ma_AVAudioSessionPortDescription_to_device_info(AVAudioSessionPortDescription* pPortDesc, ma_device_info* pInfo)
  27729. {
  27730. MA_ZERO_OBJECT(pInfo);
  27731. ma_strncpy_s(pInfo->name, sizeof(pInfo->name), [pPortDesc.portName UTF8String], (size_t)-1);
  27732. ma_strncpy_s(pInfo->id.coreaudio, sizeof(pInfo->id.coreaudio), [pPortDesc.UID UTF8String], (size_t)-1);
  27733. }
  27734. #endif
  27735. static ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  27736. {
  27737. #if defined(MA_APPLE_DESKTOP)
  27738. UInt32 deviceCount;
  27739. AudioObjectID* pDeviceObjectIDs;
  27740. AudioObjectID defaultDeviceObjectIDPlayback;
  27741. AudioObjectID defaultDeviceObjectIDCapture;
  27742. ma_result result;
  27743. UInt32 iDevice;
  27744. ma_find_default_AudioObjectID(pContext, ma_device_type_playback, &defaultDeviceObjectIDPlayback); /* OK if this fails. */
  27745. ma_find_default_AudioObjectID(pContext, ma_device_type_capture, &defaultDeviceObjectIDCapture); /* OK if this fails. */
  27746. result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
  27747. if (result != MA_SUCCESS) {
  27748. return result;
  27749. }
  27750. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  27751. AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice];
  27752. ma_device_info info;
  27753. MA_ZERO_OBJECT(&info);
  27754. if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(info.id.coreaudio), info.id.coreaudio) != MA_SUCCESS) {
  27755. continue;
  27756. }
  27757. if (ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(info.name), info.name) != MA_SUCCESS) {
  27758. continue;
  27759. }
  27760. if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) {
  27761. if (deviceObjectID == defaultDeviceObjectIDPlayback) {
  27762. info.isDefault = MA_TRUE;
  27763. }
  27764. if (!callback(pContext, ma_device_type_playback, &info, pUserData)) {
  27765. break;
  27766. }
  27767. }
  27768. if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) {
  27769. if (deviceObjectID == defaultDeviceObjectIDCapture) {
  27770. info.isDefault = MA_TRUE;
  27771. }
  27772. if (!callback(pContext, ma_device_type_capture, &info, pUserData)) {
  27773. break;
  27774. }
  27775. }
  27776. }
  27777. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  27778. #else
  27779. ma_device_info info;
  27780. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  27781. NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
  27782. for (AVAudioSessionPortDescription* pPortDesc in pOutputs) {
  27783. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info);
  27784. if (!callback(pContext, ma_device_type_playback, &info, pUserData)) {
  27785. return MA_SUCCESS;
  27786. }
  27787. }
  27788. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  27789. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info);
  27790. if (!callback(pContext, ma_device_type_capture, &info, pUserData)) {
  27791. return MA_SUCCESS;
  27792. }
  27793. }
  27794. #endif
  27795. return MA_SUCCESS;
  27796. }
  27797. 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)
  27798. {
  27799. ma_result result;
  27800. MA_ASSERT(pContext != NULL);
  27801. #if defined(MA_APPLE_DESKTOP)
  27802. /* Desktop */
  27803. {
  27804. AudioObjectID deviceObjectID;
  27805. AudioObjectID defaultDeviceObjectID;
  27806. UInt32 streamDescriptionCount;
  27807. AudioStreamRangedDescription* pStreamDescriptions;
  27808. UInt32 iStreamDescription;
  27809. UInt32 sampleRateRangeCount;
  27810. AudioValueRange* pSampleRateRanges;
  27811. ma_find_default_AudioObjectID(pContext, deviceType, &defaultDeviceObjectID); /* OK if this fails. */
  27812. result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID);
  27813. if (result != MA_SUCCESS) {
  27814. return result;
  27815. }
  27816. result = ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio);
  27817. if (result != MA_SUCCESS) {
  27818. return result;
  27819. }
  27820. result = ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name);
  27821. if (result != MA_SUCCESS) {
  27822. return result;
  27823. }
  27824. if (deviceObjectID == defaultDeviceObjectID) {
  27825. pDeviceInfo->isDefault = MA_TRUE;
  27826. }
  27827. /*
  27828. There could be a large number of permutations here. Fortunately there is only a single channel count
  27829. being reported which reduces this quite a bit. For sample rates we're only reporting those that are
  27830. one of miniaudio's recognized "standard" rates. If there are still more formats than can fit into
  27831. our fixed sized array we'll just need to truncate them. This is unlikely and will probably only happen
  27832. if some driver performs software data conversion and therefore reports every possible format and
  27833. sample rate.
  27834. */
  27835. pDeviceInfo->nativeDataFormatCount = 0;
  27836. /* Formats. */
  27837. {
  27838. ma_format uniqueFormats[ma_format_count];
  27839. ma_uint32 uniqueFormatCount = 0;
  27840. ma_uint32 channels;
  27841. /* Channels. */
  27842. result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &channels);
  27843. if (result != MA_SUCCESS) {
  27844. return result;
  27845. }
  27846. /* Formats. */
  27847. result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions);
  27848. if (result != MA_SUCCESS) {
  27849. return result;
  27850. }
  27851. for (iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) {
  27852. ma_format format;
  27853. ma_bool32 hasFormatBeenHandled = MA_FALSE;
  27854. ma_uint32 iOutputFormat;
  27855. ma_uint32 iSampleRate;
  27856. result = ma_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format);
  27857. if (result != MA_SUCCESS) {
  27858. continue;
  27859. }
  27860. MA_ASSERT(format != ma_format_unknown);
  27861. /* Make sure the format isn't already in the output list. */
  27862. for (iOutputFormat = 0; iOutputFormat < uniqueFormatCount; ++iOutputFormat) {
  27863. if (uniqueFormats[iOutputFormat] == format) {
  27864. hasFormatBeenHandled = MA_TRUE;
  27865. break;
  27866. }
  27867. }
  27868. /* If we've already handled this format just skip it. */
  27869. if (hasFormatBeenHandled) {
  27870. continue;
  27871. }
  27872. uniqueFormats[uniqueFormatCount] = format;
  27873. uniqueFormatCount += 1;
  27874. /* Sample Rates */
  27875. result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges);
  27876. if (result != MA_SUCCESS) {
  27877. return result;
  27878. }
  27879. /*
  27880. Annoyingly Core Audio reports a sample rate range. We just get all the standard rates that are
  27881. between this range.
  27882. */
  27883. for (iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) {
  27884. ma_uint32 iStandardSampleRate;
  27885. for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
  27886. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
  27887. if (standardSampleRate >= pSampleRateRanges[iSampleRate].mMinimum && standardSampleRate <= pSampleRateRanges[iSampleRate].mMaximum) {
  27888. /* We have a new data format. Add it to the list. */
  27889. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  27890. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  27891. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = standardSampleRate;
  27892. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  27893. pDeviceInfo->nativeDataFormatCount += 1;
  27894. if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) {
  27895. break; /* No more room for any more formats. */
  27896. }
  27897. }
  27898. }
  27899. }
  27900. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  27901. if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) {
  27902. break; /* No more room for any more formats. */
  27903. }
  27904. }
  27905. ma_free(pStreamDescriptions, &pContext->allocationCallbacks);
  27906. }
  27907. }
  27908. #else
  27909. /* Mobile */
  27910. {
  27911. AudioComponentDescription desc;
  27912. AudioComponent component;
  27913. AudioUnit audioUnit;
  27914. OSStatus status;
  27915. AudioUnitScope formatScope;
  27916. AudioUnitElement formatElement;
  27917. AudioStreamBasicDescription bestFormat;
  27918. UInt32 propSize;
  27919. /* We want to ensure we use a consistent device name to device enumeration. */
  27920. if (pDeviceID != NULL && pDeviceID->coreaudio[0] != '\0') {
  27921. ma_bool32 found = MA_FALSE;
  27922. if (deviceType == ma_device_type_playback) {
  27923. NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
  27924. for (AVAudioSessionPortDescription* pPortDesc in pOutputs) {
  27925. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27926. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo);
  27927. found = MA_TRUE;
  27928. break;
  27929. }
  27930. }
  27931. } else {
  27932. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  27933. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  27934. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27935. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo);
  27936. found = MA_TRUE;
  27937. break;
  27938. }
  27939. }
  27940. }
  27941. if (!found) {
  27942. return MA_DOES_NOT_EXIST;
  27943. }
  27944. } else {
  27945. if (deviceType == ma_device_type_playback) {
  27946. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  27947. } else {
  27948. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  27949. }
  27950. }
  27951. /*
  27952. Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is
  27953. 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
  27954. retrieve from the AVAudioSession shared instance.
  27955. */
  27956. desc.componentType = kAudioUnitType_Output;
  27957. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  27958. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  27959. desc.componentFlags = 0;
  27960. desc.componentFlagsMask = 0;
  27961. component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
  27962. if (component == NULL) {
  27963. return MA_FAILED_TO_INIT_BACKEND;
  27964. }
  27965. status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit);
  27966. if (status != noErr) {
  27967. return ma_result_from_OSStatus(status);
  27968. }
  27969. formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
  27970. formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
  27971. propSize = sizeof(bestFormat);
  27972. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize);
  27973. if (status != noErr) {
  27974. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
  27975. return ma_result_from_OSStatus(status);
  27976. }
  27977. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
  27978. audioUnit = NULL;
  27979. /* Only a single format is being reported for iOS. */
  27980. pDeviceInfo->nativeDataFormatCount = 1;
  27981. result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->nativeDataFormats[0].format);
  27982. if (result != MA_SUCCESS) {
  27983. return result;
  27984. }
  27985. pDeviceInfo->nativeDataFormats[0].channels = bestFormat.mChannelsPerFrame;
  27986. /*
  27987. It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do
  27988. this we just get the shared instance and inspect.
  27989. */
  27990. @autoreleasepool {
  27991. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  27992. MA_ASSERT(pAudioSession != NULL);
  27993. pDeviceInfo->nativeDataFormats[0].sampleRate = (ma_uint32)pAudioSession.sampleRate;
  27994. }
  27995. }
  27996. #endif
  27997. (void)pDeviceInfo; /* Unused. */
  27998. return MA_SUCCESS;
  27999. }
  28000. static AudioBufferList* ma_allocate_AudioBufferList__coreaudio(ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout, const ma_allocation_callbacks* pAllocationCallbacks)
  28001. {
  28002. AudioBufferList* pBufferList;
  28003. UInt32 audioBufferSizeInBytes;
  28004. size_t allocationSize;
  28005. MA_ASSERT(sizeInFrames > 0);
  28006. MA_ASSERT(format != ma_format_unknown);
  28007. MA_ASSERT(channels > 0);
  28008. allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); /* Subtract sizeof(AudioBuffer) because that part is dynamically sized. */
  28009. if (layout == ma_stream_layout_interleaved) {
  28010. /* Interleaved case. This is the simple case because we just have one buffer. */
  28011. allocationSize += sizeof(AudioBuffer) * 1;
  28012. } else {
  28013. /* Non-interleaved case. This is the more complex case because there's more than one buffer. */
  28014. allocationSize += sizeof(AudioBuffer) * channels;
  28015. }
  28016. allocationSize += sizeInFrames * ma_get_bytes_per_frame(format, channels);
  28017. pBufferList = (AudioBufferList*)ma_malloc(allocationSize, pAllocationCallbacks);
  28018. if (pBufferList == NULL) {
  28019. return NULL;
  28020. }
  28021. audioBufferSizeInBytes = (UInt32)(sizeInFrames * ma_get_bytes_per_sample(format));
  28022. if (layout == ma_stream_layout_interleaved) {
  28023. pBufferList->mNumberBuffers = 1;
  28024. pBufferList->mBuffers[0].mNumberChannels = channels;
  28025. pBufferList->mBuffers[0].mDataByteSize = audioBufferSizeInBytes * channels;
  28026. pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList);
  28027. } else {
  28028. ma_uint32 iBuffer;
  28029. pBufferList->mNumberBuffers = channels;
  28030. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
  28031. pBufferList->mBuffers[iBuffer].mNumberChannels = 1;
  28032. pBufferList->mBuffers[iBuffer].mDataByteSize = audioBufferSizeInBytes;
  28033. pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * channels)) + (audioBufferSizeInBytes * iBuffer);
  28034. }
  28035. }
  28036. return pBufferList;
  28037. }
  28038. static ma_result ma_device_realloc_AudioBufferList__coreaudio(ma_device* pDevice, ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout)
  28039. {
  28040. MA_ASSERT(pDevice != NULL);
  28041. MA_ASSERT(format != ma_format_unknown);
  28042. MA_ASSERT(channels > 0);
  28043. /* Only resize the buffer if necessary. */
  28044. if (pDevice->coreaudio.audioBufferCapInFrames < sizeInFrames) {
  28045. AudioBufferList* pNewAudioBufferList;
  28046. pNewAudioBufferList = ma_allocate_AudioBufferList__coreaudio(sizeInFrames, format, channels, layout, &pDevice->pContext->allocationCallbacks);
  28047. if (pNewAudioBufferList == NULL) {
  28048. return MA_OUT_OF_MEMORY;
  28049. }
  28050. /* At this point we'll have a new AudioBufferList and we can free the old one. */
  28051. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28052. pDevice->coreaudio.pAudioBufferList = pNewAudioBufferList;
  28053. pDevice->coreaudio.audioBufferCapInFrames = sizeInFrames;
  28054. }
  28055. /* Getting here means the capacity of the audio is fine. */
  28056. return MA_SUCCESS;
  28057. }
  28058. static OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList)
  28059. {
  28060. ma_device* pDevice = (ma_device*)pUserData;
  28061. ma_stream_layout layout;
  28062. MA_ASSERT(pDevice != NULL);
  28063. /*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);*/
  28064. /* 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. */
  28065. layout = ma_stream_layout_interleaved;
  28066. if (pBufferList->mBuffers[0].mNumberChannels != pDevice->playback.internalChannels) {
  28067. layout = ma_stream_layout_deinterleaved;
  28068. }
  28069. if (layout == ma_stream_layout_interleaved) {
  28070. /* For now we can assume everything is interleaved. */
  28071. UInt32 iBuffer;
  28072. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
  28073. if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->playback.internalChannels) {
  28074. ma_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  28075. if (frameCountForThisBuffer > 0) {
  28076. ma_device_handle_backend_data_callback(pDevice, pBufferList->mBuffers[iBuffer].mData, NULL, frameCountForThisBuffer);
  28077. }
  28078. /*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);*/
  28079. } else {
  28080. /*
  28081. This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
  28082. not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just
  28083. output silence here.
  28084. */
  28085. MA_ZERO_MEMORY(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize);
  28086. /*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);*/
  28087. }
  28088. }
  28089. } else {
  28090. /* This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This assumes each buffer is the same size. */
  28091. MA_ASSERT(pDevice->playback.internalChannels <= MA_MAX_CHANNELS); /* This should heve been validated at initialization time. */
  28092. /*
  28093. For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
  28094. very strange has happened and we're not going to support it.
  28095. */
  28096. if ((pBufferList->mNumberBuffers % pDevice->playback.internalChannels) == 0) {
  28097. ma_uint8 tempBuffer[4096];
  28098. UInt32 iBuffer;
  28099. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) {
  28100. ma_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_sample(pDevice->playback.internalFormat);
  28101. ma_uint32 framesRemaining = frameCountPerBuffer;
  28102. while (framesRemaining > 0) {
  28103. void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
  28104. ma_uint32 iChannel;
  28105. ma_uint32 framesToRead = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  28106. if (framesToRead > framesRemaining) {
  28107. framesToRead = framesRemaining;
  28108. }
  28109. ma_device_handle_backend_data_callback(pDevice, tempBuffer, NULL, framesToRead);
  28110. for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
  28111. ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer+iChannel].mData, (frameCountPerBuffer - framesRemaining) * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
  28112. }
  28113. ma_deinterleave_pcm_frames(pDevice->playback.internalFormat, pDevice->playback.internalChannels, framesToRead, tempBuffer, ppDeinterleavedBuffers);
  28114. framesRemaining -= framesToRead;
  28115. }
  28116. }
  28117. }
  28118. }
  28119. (void)pActionFlags;
  28120. (void)pTimeStamp;
  28121. (void)busNumber;
  28122. (void)frameCount;
  28123. return noErr;
  28124. }
  28125. static OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList)
  28126. {
  28127. ma_device* pDevice = (ma_device*)pUserData;
  28128. AudioBufferList* pRenderedBufferList;
  28129. ma_result result;
  28130. ma_stream_layout layout;
  28131. ma_uint32 iBuffer;
  28132. OSStatus status;
  28133. MA_ASSERT(pDevice != NULL);
  28134. pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
  28135. MA_ASSERT(pRenderedBufferList);
  28136. /* 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. */
  28137. layout = ma_stream_layout_interleaved;
  28138. if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) {
  28139. layout = ma_stream_layout_deinterleaved;
  28140. }
  28141. /*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);*/
  28142. /*
  28143. There has been a situation reported where frame count passed into this function is greater than the capacity of
  28144. our capture buffer. There doesn't seem to be a reliable way to determine what the maximum frame count will be,
  28145. so we need to instead resort to dynamically reallocating our buffer to ensure it's large enough to capture the
  28146. number of frames requested by this callback.
  28147. */
  28148. result = ma_device_realloc_AudioBufferList__coreaudio(pDevice, frameCount, pDevice->capture.internalFormat, pDevice->capture.internalChannels, layout);
  28149. if (result != MA_SUCCESS) {
  28150. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "Failed to allocate AudioBufferList for capture.\n");
  28151. return noErr;
  28152. }
  28153. pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
  28154. MA_ASSERT(pRenderedBufferList);
  28155. /*
  28156. When you call AudioUnitRender(), Core Audio tries to be helpful by setting the mDataByteSize to the number of bytes
  28157. that were actually rendered. The problem with this is that the next call can fail with -50 due to the size no longer
  28158. being set to the capacity of the buffer, but instead the size in bytes of the previous render. This will cause a
  28159. problem when a future call to this callback specifies a larger number of frames.
  28160. To work around this we need to explicitly set the size of each buffer to their respective size in bytes.
  28161. */
  28162. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
  28163. pRenderedBufferList->mBuffers[iBuffer].mDataByteSize = pDevice->coreaudio.audioBufferCapInFrames * ma_get_bytes_per_sample(pDevice->capture.internalFormat) * pRenderedBufferList->mBuffers[iBuffer].mNumberChannels;
  28164. }
  28165. status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList);
  28166. if (status != noErr) {
  28167. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " ERROR: AudioUnitRender() failed with %d.\n", (int)status);
  28168. return status;
  28169. }
  28170. if (layout == ma_stream_layout_interleaved) {
  28171. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
  28172. if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) {
  28173. ma_device_handle_backend_data_callback(pDevice, NULL, pRenderedBufferList->mBuffers[iBuffer].mData, frameCount);
  28174. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " mDataByteSize=%d.\n", (int)pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);*/
  28175. } else {
  28176. /*
  28177. This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
  28178. not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams.
  28179. */
  28180. ma_uint8 silentBuffer[4096];
  28181. ma_uint32 framesRemaining;
  28182. MA_ZERO_MEMORY(silentBuffer, sizeof(silentBuffer));
  28183. framesRemaining = frameCount;
  28184. while (framesRemaining > 0) {
  28185. ma_uint32 framesToSend = sizeof(silentBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  28186. if (framesToSend > framesRemaining) {
  28187. framesToSend = framesRemaining;
  28188. }
  28189. ma_device_handle_backend_data_callback(pDevice, NULL, silentBuffer, framesToSend);
  28190. framesRemaining -= framesToSend;
  28191. }
  28192. /*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);*/
  28193. }
  28194. }
  28195. } else {
  28196. /* 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. */
  28197. MA_ASSERT(pDevice->capture.internalChannels <= MA_MAX_CHANNELS); /* This should have been validated at initialization time. */
  28198. /*
  28199. For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
  28200. very strange has happened and we're not going to support it.
  28201. */
  28202. if ((pRenderedBufferList->mNumberBuffers % pDevice->capture.internalChannels) == 0) {
  28203. ma_uint8 tempBuffer[4096];
  28204. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) {
  28205. ma_uint32 framesRemaining = frameCount;
  28206. while (framesRemaining > 0) {
  28207. void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
  28208. ma_uint32 iChannel;
  28209. ma_uint32 framesToSend = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  28210. if (framesToSend > framesRemaining) {
  28211. framesToSend = framesRemaining;
  28212. }
  28213. for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
  28214. ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer+iChannel].mData, (frameCount - framesRemaining) * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
  28215. }
  28216. ma_interleave_pcm_frames(pDevice->capture.internalFormat, pDevice->capture.internalChannels, framesToSend, (const void**)ppDeinterleavedBuffers, tempBuffer);
  28217. ma_device_handle_backend_data_callback(pDevice, NULL, tempBuffer, framesToSend);
  28218. framesRemaining -= framesToSend;
  28219. }
  28220. }
  28221. }
  28222. }
  28223. (void)pActionFlags;
  28224. (void)pTimeStamp;
  28225. (void)busNumber;
  28226. (void)frameCount;
  28227. (void)pUnusedBufferList;
  28228. return noErr;
  28229. }
  28230. static void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element)
  28231. {
  28232. ma_device* pDevice = (ma_device*)pUserData;
  28233. MA_ASSERT(pDevice != NULL);
  28234. /* Don't do anything if it looks like we're just reinitializing due to a device switch. */
  28235. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
  28236. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
  28237. return;
  28238. }
  28239. /*
  28240. There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like
  28241. AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit)
  28242. can try waiting on the same lock. I'm going to try working around this by not calling any Core
  28243. Audio APIs in the callback when the device has been stopped or uninitialized.
  28244. */
  28245. 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) {
  28246. ma_device__on_notification_stopped(pDevice);
  28247. } else {
  28248. UInt32 isRunning;
  28249. UInt32 isRunningSize = sizeof(isRunning);
  28250. OSStatus status = ((ma_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize);
  28251. if (status != noErr) {
  28252. goto done; /* Don't really know what to do in this case... just ignore it, I suppose... */
  28253. }
  28254. if (!isRunning) {
  28255. /*
  28256. 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:
  28257. 1) When the device is unplugged, this will be called _before_ the default device change notification.
  28258. 2) When the device is changed via the default device change notification, this will be called _after_ the switch.
  28259. 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.
  28260. */
  28261. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isDefaultPlaybackDevice) ||
  28262. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isDefaultCaptureDevice)) {
  28263. /*
  28264. It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device
  28265. via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the
  28266. 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
  28267. hasn't!).
  28268. */
  28269. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
  28270. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
  28271. goto done;
  28272. }
  28273. /*
  28274. 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
  28275. 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
  28276. likely be successful in switching to the new device.
  28277. TODO: Try to predict if Core Audio will switch devices. If not, the stopped callback needs to be posted.
  28278. */
  28279. goto done;
  28280. }
  28281. /* Getting here means we need to stop the device. */
  28282. ma_device__on_notification_stopped(pDevice);
  28283. }
  28284. }
  28285. (void)propertyID; /* Unused. */
  28286. done:
  28287. /* Always signal the stop event. It's possible for the "else" case to get hit which can happen during an interruption. */
  28288. ma_event_signal(&pDevice->coreaudio.stopEvent);
  28289. }
  28290. #if defined(MA_APPLE_DESKTOP)
  28291. 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. */
  28292. static ma_uint32 g_DeviceTrackingInitCounter_CoreAudio = 0;
  28293. static ma_mutex g_DeviceTrackingMutex_CoreAudio;
  28294. static ma_device** g_ppTrackedDevices_CoreAudio = NULL;
  28295. static ma_uint32 g_TrackedDeviceCap_CoreAudio = 0;
  28296. static ma_uint32 g_TrackedDeviceCount_CoreAudio = 0;
  28297. static OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData)
  28298. {
  28299. ma_device_type deviceType;
  28300. /* Not sure if I really need to check this, but it makes me feel better. */
  28301. if (addressCount == 0) {
  28302. return noErr;
  28303. }
  28304. if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultOutputDevice) {
  28305. deviceType = ma_device_type_playback;
  28306. } else if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice) {
  28307. deviceType = ma_device_type_capture;
  28308. } else {
  28309. return noErr; /* Should never hit this. */
  28310. }
  28311. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  28312. {
  28313. ma_uint32 iDevice;
  28314. for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) {
  28315. ma_result reinitResult;
  28316. ma_device* pDevice;
  28317. pDevice = g_ppTrackedDevices_CoreAudio[iDevice];
  28318. if (pDevice->type == deviceType || pDevice->type == ma_device_type_duplex) {
  28319. if (deviceType == ma_device_type_playback) {
  28320. pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE;
  28321. reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE);
  28322. pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE;
  28323. } else {
  28324. pDevice->coreaudio.isSwitchingCaptureDevice = MA_TRUE;
  28325. reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE);
  28326. pDevice->coreaudio.isSwitchingCaptureDevice = MA_FALSE;
  28327. }
  28328. if (reinitResult == MA_SUCCESS) {
  28329. ma_device__post_init_setup(pDevice, deviceType);
  28330. /* Restart the device if required. If this fails we need to stop the device entirely. */
  28331. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  28332. OSStatus status;
  28333. if (deviceType == ma_device_type_playback) {
  28334. status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28335. if (status != noErr) {
  28336. if (pDevice->type == ma_device_type_duplex) {
  28337. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28338. }
  28339. ma_device__set_state(pDevice, ma_device_state_stopped);
  28340. }
  28341. } else if (deviceType == ma_device_type_capture) {
  28342. status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28343. if (status != noErr) {
  28344. if (pDevice->type == ma_device_type_duplex) {
  28345. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28346. }
  28347. ma_device__set_state(pDevice, ma_device_state_stopped);
  28348. }
  28349. }
  28350. }
  28351. ma_device__on_notification_rerouted(pDevice);
  28352. }
  28353. }
  28354. }
  28355. }
  28356. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28357. /* Unused parameters. */
  28358. (void)objectID;
  28359. (void)pUserData;
  28360. return noErr;
  28361. }
  28362. static ma_result ma_context__init_device_tracking__coreaudio(ma_context* pContext)
  28363. {
  28364. MA_ASSERT(pContext != NULL);
  28365. ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio);
  28366. {
  28367. /* Don't do anything if we've already initializd device tracking. */
  28368. if (g_DeviceTrackingInitCounter_CoreAudio == 0) {
  28369. AudioObjectPropertyAddress propAddress;
  28370. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  28371. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  28372. ma_mutex_init(&g_DeviceTrackingMutex_CoreAudio);
  28373. propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  28374. ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28375. propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  28376. ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28377. }
  28378. g_DeviceTrackingInitCounter_CoreAudio += 1;
  28379. }
  28380. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  28381. return MA_SUCCESS;
  28382. }
  28383. static ma_result ma_context__uninit_device_tracking__coreaudio(ma_context* pContext)
  28384. {
  28385. MA_ASSERT(pContext != NULL);
  28386. ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio);
  28387. {
  28388. if (g_DeviceTrackingInitCounter_CoreAudio > 0)
  28389. g_DeviceTrackingInitCounter_CoreAudio -= 1;
  28390. if (g_DeviceTrackingInitCounter_CoreAudio == 0) {
  28391. AudioObjectPropertyAddress propAddress;
  28392. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  28393. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  28394. propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  28395. ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28396. propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  28397. ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  28398. /* At this point there should be no tracked devices. If not there's an error somewhere. */
  28399. if (g_ppTrackedDevices_CoreAudio != NULL) {
  28400. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "You have uninitialized all contexts while an associated device is still active.");
  28401. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  28402. return MA_INVALID_OPERATION;
  28403. }
  28404. ma_mutex_uninit(&g_DeviceTrackingMutex_CoreAudio);
  28405. }
  28406. }
  28407. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  28408. return MA_SUCCESS;
  28409. }
  28410. static ma_result ma_device__track__coreaudio(ma_device* pDevice)
  28411. {
  28412. MA_ASSERT(pDevice != NULL);
  28413. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  28414. {
  28415. /* Allocate memory if required. */
  28416. if (g_TrackedDeviceCap_CoreAudio <= g_TrackedDeviceCount_CoreAudio) {
  28417. ma_uint32 newCap;
  28418. ma_device** ppNewDevices;
  28419. newCap = g_TrackedDeviceCap_CoreAudio * 2;
  28420. if (newCap == 0) {
  28421. newCap = 1;
  28422. }
  28423. ppNewDevices = (ma_device**)ma_realloc(g_ppTrackedDevices_CoreAudio, sizeof(*g_ppTrackedDevices_CoreAudio)*newCap, &pDevice->pContext->allocationCallbacks);
  28424. if (ppNewDevices == NULL) {
  28425. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28426. return MA_OUT_OF_MEMORY;
  28427. }
  28428. g_ppTrackedDevices_CoreAudio = ppNewDevices;
  28429. g_TrackedDeviceCap_CoreAudio = newCap;
  28430. }
  28431. g_ppTrackedDevices_CoreAudio[g_TrackedDeviceCount_CoreAudio] = pDevice;
  28432. g_TrackedDeviceCount_CoreAudio += 1;
  28433. }
  28434. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28435. return MA_SUCCESS;
  28436. }
  28437. static ma_result ma_device__untrack__coreaudio(ma_device* pDevice)
  28438. {
  28439. MA_ASSERT(pDevice != NULL);
  28440. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  28441. {
  28442. ma_uint32 iDevice;
  28443. for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) {
  28444. if (g_ppTrackedDevices_CoreAudio[iDevice] == pDevice) {
  28445. /* We've found the device. We now need to remove it from the list. */
  28446. ma_uint32 jDevice;
  28447. for (jDevice = iDevice; jDevice < g_TrackedDeviceCount_CoreAudio-1; jDevice += 1) {
  28448. g_ppTrackedDevices_CoreAudio[jDevice] = g_ppTrackedDevices_CoreAudio[jDevice+1];
  28449. }
  28450. g_TrackedDeviceCount_CoreAudio -= 1;
  28451. /* If there's nothing else in the list we need to free memory. */
  28452. if (g_TrackedDeviceCount_CoreAudio == 0) {
  28453. ma_free(g_ppTrackedDevices_CoreAudio, &pDevice->pContext->allocationCallbacks);
  28454. g_ppTrackedDevices_CoreAudio = NULL;
  28455. g_TrackedDeviceCap_CoreAudio = 0;
  28456. }
  28457. break;
  28458. }
  28459. }
  28460. }
  28461. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  28462. return MA_SUCCESS;
  28463. }
  28464. #endif
  28465. #if defined(MA_APPLE_MOBILE)
  28466. @interface ma_ios_notification_handler:NSObject {
  28467. ma_device* m_pDevice;
  28468. }
  28469. @end
  28470. @implementation ma_ios_notification_handler
  28471. -(id)init:(ma_device*)pDevice
  28472. {
  28473. self = [super init];
  28474. m_pDevice = pDevice;
  28475. /* For route changes. */
  28476. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_route_change:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
  28477. /* For interruptions. */
  28478. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_interruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  28479. return self;
  28480. }
  28481. -(void)dealloc
  28482. {
  28483. [self remove_handler];
  28484. #if defined(__has_feature)
  28485. #if !__has_feature(objc_arc)
  28486. [super dealloc];
  28487. #endif
  28488. #endif
  28489. }
  28490. -(void)remove_handler
  28491. {
  28492. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
  28493. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
  28494. }
  28495. -(void)handle_interruption:(NSNotification*)pNotification
  28496. {
  28497. NSInteger type = [[[pNotification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  28498. switch (type)
  28499. {
  28500. case AVAudioSessionInterruptionTypeBegan:
  28501. {
  28502. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeBegan\n");
  28503. /*
  28504. Core Audio will have stopped the internal device automatically, but we need explicitly
  28505. stop it at a higher level to ensure miniaudio-specific state is updated for consistency.
  28506. */
  28507. ma_device_stop(m_pDevice);
  28508. /*
  28509. Fire the notification after the device has been stopped to ensure it's in the correct
  28510. state when the notification handler is invoked.
  28511. */
  28512. ma_device__on_notification_interruption_began(m_pDevice);
  28513. } break;
  28514. case AVAudioSessionInterruptionTypeEnded:
  28515. {
  28516. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeEnded\n");
  28517. ma_device__on_notification_interruption_ended(m_pDevice);
  28518. } break;
  28519. }
  28520. }
  28521. -(void)handle_route_change:(NSNotification*)pNotification
  28522. {
  28523. AVAudioSession* pSession = [AVAudioSession sharedInstance];
  28524. NSInteger reason = [[[pNotification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  28525. switch (reason)
  28526. {
  28527. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
  28528. {
  28529. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOldDeviceUnavailable\n");
  28530. } break;
  28531. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  28532. {
  28533. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNewDeviceAvailable\n");
  28534. } break;
  28535. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
  28536. {
  28537. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory\n");
  28538. } break;
  28539. case AVAudioSessionRouteChangeReasonWakeFromSleep:
  28540. {
  28541. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonWakeFromSleep\n");
  28542. } break;
  28543. case AVAudioSessionRouteChangeReasonOverride:
  28544. {
  28545. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOverride\n");
  28546. } break;
  28547. case AVAudioSessionRouteChangeReasonCategoryChange:
  28548. {
  28549. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonCategoryChange\n");
  28550. } break;
  28551. case AVAudioSessionRouteChangeReasonUnknown:
  28552. default:
  28553. {
  28554. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonUnknown\n");
  28555. } break;
  28556. }
  28557. 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);
  28558. /* Let the application know about the route change. */
  28559. ma_device__on_notification_rerouted(m_pDevice);
  28560. }
  28561. @end
  28562. #endif
  28563. static ma_result ma_device_uninit__coreaudio(ma_device* pDevice)
  28564. {
  28565. MA_ASSERT(pDevice != NULL);
  28566. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_uninitialized);
  28567. #if defined(MA_APPLE_DESKTOP)
  28568. /*
  28569. 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
  28570. just gracefully ignore it.
  28571. */
  28572. ma_device__untrack__coreaudio(pDevice);
  28573. #endif
  28574. #if defined(MA_APPLE_MOBILE)
  28575. if (pDevice->coreaudio.pNotificationHandler != NULL) {
  28576. ma_ios_notification_handler* pNotificationHandler = (MA_BRIDGE_TRANSFER ma_ios_notification_handler*)pDevice->coreaudio.pNotificationHandler;
  28577. [pNotificationHandler remove_handler];
  28578. }
  28579. #endif
  28580. if (pDevice->coreaudio.audioUnitCapture != NULL) {
  28581. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28582. }
  28583. if (pDevice->coreaudio.audioUnitPlayback != NULL) {
  28584. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28585. }
  28586. if (pDevice->coreaudio.pAudioBufferList) {
  28587. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28588. }
  28589. return MA_SUCCESS;
  28590. }
  28591. typedef struct
  28592. {
  28593. ma_bool32 allowNominalSampleRateChange;
  28594. /* Input. */
  28595. ma_format formatIn;
  28596. ma_uint32 channelsIn;
  28597. ma_uint32 sampleRateIn;
  28598. ma_channel channelMapIn[MA_MAX_CHANNELS];
  28599. ma_uint32 periodSizeInFramesIn;
  28600. ma_uint32 periodSizeInMillisecondsIn;
  28601. ma_uint32 periodsIn;
  28602. ma_share_mode shareMode;
  28603. ma_performance_profile performanceProfile;
  28604. ma_bool32 registerStopEvent;
  28605. /* Output. */
  28606. #if defined(MA_APPLE_DESKTOP)
  28607. AudioObjectID deviceObjectID;
  28608. #endif
  28609. AudioComponent component;
  28610. AudioUnit audioUnit;
  28611. AudioBufferList* pAudioBufferList; /* Only used for input devices. */
  28612. ma_format formatOut;
  28613. ma_uint32 channelsOut;
  28614. ma_uint32 sampleRateOut;
  28615. ma_channel channelMapOut[MA_MAX_CHANNELS];
  28616. ma_uint32 periodSizeInFramesOut;
  28617. ma_uint32 periodsOut;
  28618. char deviceName[256];
  28619. } ma_device_init_internal_data__coreaudio;
  28620. 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. */
  28621. {
  28622. ma_result result;
  28623. OSStatus status;
  28624. UInt32 enableIOFlag;
  28625. AudioStreamBasicDescription bestFormat;
  28626. UInt32 actualPeriodSizeInFrames;
  28627. AURenderCallbackStruct callbackInfo;
  28628. #if defined(MA_APPLE_DESKTOP)
  28629. AudioObjectID deviceObjectID;
  28630. #endif
  28631. /* This API should only be used for a single device type: playback or capture. No full-duplex mode. */
  28632. if (deviceType == ma_device_type_duplex) {
  28633. return MA_INVALID_ARGS;
  28634. }
  28635. MA_ASSERT(pContext != NULL);
  28636. MA_ASSERT(deviceType == ma_device_type_playback || deviceType == ma_device_type_capture);
  28637. #if defined(MA_APPLE_DESKTOP)
  28638. pData->deviceObjectID = 0;
  28639. #endif
  28640. pData->component = NULL;
  28641. pData->audioUnit = NULL;
  28642. pData->pAudioBufferList = NULL;
  28643. #if defined(MA_APPLE_DESKTOP)
  28644. result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID);
  28645. if (result != MA_SUCCESS) {
  28646. return result;
  28647. }
  28648. pData->deviceObjectID = deviceObjectID;
  28649. #endif
  28650. /* Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. */
  28651. pData->periodsOut = pData->periodsIn;
  28652. if (pData->periodsOut == 0) {
  28653. pData->periodsOut = MA_DEFAULT_PERIODS;
  28654. }
  28655. if (pData->periodsOut > 16) {
  28656. pData->periodsOut = 16;
  28657. }
  28658. /* Audio unit. */
  28659. status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)((AudioComponent)pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit);
  28660. if (status != noErr) {
  28661. return ma_result_from_OSStatus(status);
  28662. }
  28663. /* 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. */
  28664. enableIOFlag = 1;
  28665. if (deviceType == ma_device_type_capture) {
  28666. enableIOFlag = 0;
  28667. }
  28668. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &enableIOFlag, sizeof(enableIOFlag));
  28669. if (status != noErr) {
  28670. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28671. return ma_result_from_OSStatus(status);
  28672. }
  28673. enableIOFlag = (enableIOFlag == 0) ? 1 : 0;
  28674. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &enableIOFlag, sizeof(enableIOFlag));
  28675. if (status != noErr) {
  28676. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28677. return ma_result_from_OSStatus(status);
  28678. }
  28679. /* Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. */
  28680. #if defined(MA_APPLE_DESKTOP)
  28681. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceObjectID, sizeof(deviceObjectID));
  28682. if (status != noErr) {
  28683. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28684. return ma_result_from_OSStatus(result);
  28685. }
  28686. #else
  28687. /*
  28688. 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
  28689. 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.
  28690. */
  28691. if (pDeviceID != NULL) {
  28692. if (deviceType == ma_device_type_capture) {
  28693. ma_bool32 found = MA_FALSE;
  28694. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  28695. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  28696. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  28697. [[AVAudioSession sharedInstance] setPreferredInput:pPortDesc error:nil];
  28698. found = MA_TRUE;
  28699. break;
  28700. }
  28701. }
  28702. if (found == MA_FALSE) {
  28703. return MA_DOES_NOT_EXIST;
  28704. }
  28705. }
  28706. }
  28707. #endif
  28708. /*
  28709. Format. This is the hardest part of initialization because there's a few variables to take into account.
  28710. 1) The format must be supported by the device.
  28711. 2) The format must be supported miniaudio.
  28712. 3) There's a priority that miniaudio prefers.
  28713. 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
  28714. most important property is the sample rate. miniaudio can do format conversion for any sample rate and channel count, but cannot do the same
  28715. for the sample data format. If the sample data format is not supported by miniaudio it must be ignored completely.
  28716. On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to.
  28717. */
  28718. {
  28719. AudioStreamBasicDescription origFormat;
  28720. UInt32 origFormatSize = sizeof(origFormat);
  28721. AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
  28722. AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
  28723. if (deviceType == ma_device_type_playback) {
  28724. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &origFormat, &origFormatSize);
  28725. } else {
  28726. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &origFormat, &origFormatSize);
  28727. }
  28728. if (status != noErr) {
  28729. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28730. return ma_result_from_OSStatus(status);
  28731. }
  28732. #if defined(MA_APPLE_DESKTOP)
  28733. result = ma_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, &origFormat, &bestFormat);
  28734. if (result != MA_SUCCESS) {
  28735. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28736. return result;
  28737. }
  28738. /*
  28739. Technical Note TN2091: Device input using the HAL Output Audio Unit
  28740. https://developer.apple.com/library/archive/technotes/tn2091/_index.html
  28741. This documentation says the following:
  28742. The internal AudioConverter can handle any *simple* conversion. Typically, this means that a client can specify ANY
  28743. variant of the PCM formats. Consequently, the device's sample rate should match the desired sample rate. If sample rate
  28744. conversion is needed, it can be accomplished by buffering the input and converting the data on a separate thread with
  28745. another AudioConverter.
  28746. The important part here is the mention that it can handle *simple* conversions, which does *not* include sample rate. We
  28747. therefore want to ensure the sample rate stays consistent. This document is specifically for input, but I'm going to play it
  28748. safe and apply the same rule to output as well.
  28749. I have tried going against the documentation by setting the sample rate anyway, but this just results in AudioUnitRender()
  28750. returning a result code of -10863. I have also tried changing the format directly on the input scope on the input bus, but
  28751. this just results in `ca_require: IsStreamFormatWritable(inScope, inElement) NotWritable` when trying to set the format.
  28752. Something that does seem to work, however, has been setting the nominal sample rate on the deivce object. The problem with
  28753. this, however, is that it actually changes the sample rate at the operating system level and not just the application. This
  28754. 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
  28755. configuration option. When the `coreaudio.allowNominalSampleRateChange` config option is set to true, changing the sample
  28756. rate will be allowed. Otherwise it'll be fixed to the current sample rate. To check the system-defined sample rate, run
  28757. the Audio MIDI Setup program that comes installed on macOS and observe how the sample rate changes as the sample rate is
  28758. changed by miniaudio.
  28759. */
  28760. if (pData->allowNominalSampleRateChange) {
  28761. AudioValueRange sampleRateRange;
  28762. AudioObjectPropertyAddress propAddress;
  28763. sampleRateRange.mMinimum = bestFormat.mSampleRate;
  28764. sampleRateRange.mMaximum = bestFormat.mSampleRate;
  28765. propAddress.mSelector = kAudioDevicePropertyNominalSampleRate;
  28766. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  28767. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  28768. status = ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(sampleRateRange), &sampleRateRange);
  28769. if (status != noErr) {
  28770. bestFormat.mSampleRate = origFormat.mSampleRate;
  28771. }
  28772. } else {
  28773. bestFormat.mSampleRate = origFormat.mSampleRate;
  28774. }
  28775. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
  28776. if (status != noErr) {
  28777. /* We failed to set the format, so fall back to the current format of the audio unit. */
  28778. bestFormat = origFormat;
  28779. }
  28780. #else
  28781. bestFormat = origFormat;
  28782. /*
  28783. Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try
  28784. 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
  28785. 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
  28786. can tell, it looks like the sample rate is shared between playback and capture for everything.
  28787. */
  28788. @autoreleasepool {
  28789. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  28790. MA_ASSERT(pAudioSession != NULL);
  28791. [pAudioSession setPreferredSampleRate:(double)pData->sampleRateIn error:nil];
  28792. bestFormat.mSampleRate = pAudioSession.sampleRate;
  28793. /*
  28794. I've had a report that the channel count returned by AudioUnitGetProperty above is inconsistent with
  28795. AVAudioSession outputNumberOfChannels. I'm going to try using the AVAudioSession values instead.
  28796. */
  28797. if (deviceType == ma_device_type_playback) {
  28798. bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.outputNumberOfChannels;
  28799. }
  28800. if (deviceType == ma_device_type_capture) {
  28801. bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.inputNumberOfChannels;
  28802. }
  28803. }
  28804. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
  28805. if (status != noErr) {
  28806. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28807. return ma_result_from_OSStatus(status);
  28808. }
  28809. #endif
  28810. result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pData->formatOut);
  28811. if (result != MA_SUCCESS) {
  28812. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28813. return result;
  28814. }
  28815. if (pData->formatOut == ma_format_unknown) {
  28816. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28817. return MA_FORMAT_NOT_SUPPORTED;
  28818. }
  28819. pData->channelsOut = bestFormat.mChannelsPerFrame;
  28820. pData->sampleRateOut = bestFormat.mSampleRate;
  28821. }
  28822. /* Clamp the channel count for safety. */
  28823. if (pData->channelsOut > MA_MAX_CHANNELS) {
  28824. pData->channelsOut = MA_MAX_CHANNELS;
  28825. }
  28826. /*
  28827. Internal channel map. This is weird in my testing. If I use the AudioObject to get the
  28828. channel map, the channel descriptions are set to "Unknown" for some reason. To work around
  28829. this it looks like retrieving it from the AudioUnit will work. However, and this is where
  28830. it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore
  28831. I'm going to fall back to a default assumption in these cases.
  28832. */
  28833. #if defined(MA_APPLE_DESKTOP)
  28834. result = ma_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut, pData->channelsOut);
  28835. if (result != MA_SUCCESS) {
  28836. #if 0
  28837. /* Try falling back to the channel map from the AudioObject. */
  28838. result = ma_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut, pData->channelsOut);
  28839. if (result != MA_SUCCESS) {
  28840. return result;
  28841. }
  28842. #else
  28843. /* Fall back to default assumptions. */
  28844. ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  28845. #endif
  28846. }
  28847. #else
  28848. /* TODO: Figure out how to get the channel map using AVAudioSession. */
  28849. ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  28850. #endif
  28851. /* Buffer size. Not allowing this to be configurable on iOS. */
  28852. if (pData->periodSizeInFramesIn == 0) {
  28853. if (pData->periodSizeInMillisecondsIn == 0) {
  28854. if (pData->performanceProfile == ma_performance_profile_low_latency) {
  28855. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, pData->sampleRateOut);
  28856. } else {
  28857. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, pData->sampleRateOut);
  28858. }
  28859. } else {
  28860. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, pData->sampleRateOut);
  28861. }
  28862. } else {
  28863. actualPeriodSizeInFrames = pData->periodSizeInFramesIn;
  28864. }
  28865. #if defined(MA_APPLE_DESKTOP)
  28866. result = ma_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualPeriodSizeInFrames);
  28867. if (result != MA_SUCCESS) {
  28868. return result;
  28869. }
  28870. #else
  28871. /*
  28872. On iOS, the size of the IO buffer needs to be specified in seconds and is a floating point
  28873. number. I don't trust any potential truncation errors due to converting from float to integer
  28874. so I'm going to explicitly set the actual period size to the next power of 2.
  28875. */
  28876. @autoreleasepool {
  28877. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  28878. MA_ASSERT(pAudioSession != NULL);
  28879. [pAudioSession setPreferredIOBufferDuration:((float)actualPeriodSizeInFrames / pAudioSession.sampleRate) error:nil];
  28880. actualPeriodSizeInFrames = ma_next_power_of_2((ma_uint32)(pAudioSession.IOBufferDuration * pAudioSession.sampleRate));
  28881. }
  28882. #endif
  28883. /*
  28884. During testing I discovered that the buffer size can be too big. You'll get an error like this:
  28885. kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512
  28886. Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that
  28887. of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice.
  28888. */
  28889. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualPeriodSizeInFrames, sizeof(actualPeriodSizeInFrames));
  28890. if (status != noErr) {
  28891. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28892. return ma_result_from_OSStatus(status);
  28893. }
  28894. pData->periodSizeInFramesOut = (ma_uint32)actualPeriodSizeInFrames;
  28895. /* We need a buffer list if this is an input device. We render into this in the input callback. */
  28896. if (deviceType == ma_device_type_capture) {
  28897. ma_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
  28898. AudioBufferList* pBufferList;
  28899. pBufferList = ma_allocate_AudioBufferList__coreaudio(pData->periodSizeInFramesOut, pData->formatOut, pData->channelsOut, (isInterleaved) ? ma_stream_layout_interleaved : ma_stream_layout_deinterleaved, &pContext->allocationCallbacks);
  28900. if (pBufferList == NULL) {
  28901. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28902. return MA_OUT_OF_MEMORY;
  28903. }
  28904. pData->pAudioBufferList = pBufferList;
  28905. }
  28906. /* Callbacks. */
  28907. callbackInfo.inputProcRefCon = pDevice_DoNotReference;
  28908. if (deviceType == ma_device_type_playback) {
  28909. callbackInfo.inputProc = ma_on_output__coreaudio;
  28910. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &callbackInfo, sizeof(callbackInfo));
  28911. if (status != noErr) {
  28912. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28913. return ma_result_from_OSStatus(status);
  28914. }
  28915. } else {
  28916. callbackInfo.inputProc = ma_on_input__coreaudio;
  28917. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callbackInfo, sizeof(callbackInfo));
  28918. if (status != noErr) {
  28919. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28920. return ma_result_from_OSStatus(status);
  28921. }
  28922. }
  28923. /* We need to listen for stop events. */
  28924. if (pData->registerStopEvent) {
  28925. status = ((ma_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference);
  28926. if (status != noErr) {
  28927. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28928. return ma_result_from_OSStatus(status);
  28929. }
  28930. }
  28931. /* Initialize the audio unit. */
  28932. status = ((ma_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit);
  28933. if (status != noErr) {
  28934. ma_free(pData->pAudioBufferList, &pContext->allocationCallbacks);
  28935. pData->pAudioBufferList = NULL;
  28936. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28937. return ma_result_from_OSStatus(status);
  28938. }
  28939. /* Grab the name. */
  28940. #if defined(MA_APPLE_DESKTOP)
  28941. ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName);
  28942. #else
  28943. if (deviceType == ma_device_type_playback) {
  28944. ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
  28945. } else {
  28946. ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_CAPTURE_DEVICE_NAME);
  28947. }
  28948. #endif
  28949. return result;
  28950. }
  28951. #if defined(MA_APPLE_DESKTOP)
  28952. static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit)
  28953. {
  28954. ma_device_init_internal_data__coreaudio data;
  28955. ma_result result;
  28956. /* This should only be called for playback or capture, not duplex. */
  28957. if (deviceType == ma_device_type_duplex) {
  28958. return MA_INVALID_ARGS;
  28959. }
  28960. data.allowNominalSampleRateChange = MA_FALSE; /* Don't change the nominal sample rate when switching devices. */
  28961. if (deviceType == ma_device_type_capture) {
  28962. data.formatIn = pDevice->capture.format;
  28963. data.channelsIn = pDevice->capture.channels;
  28964. data.sampleRateIn = pDevice->sampleRate;
  28965. MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
  28966. data.shareMode = pDevice->capture.shareMode;
  28967. data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile;
  28968. data.registerStopEvent = MA_TRUE;
  28969. if (disposePreviousAudioUnit) {
  28970. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28971. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28972. }
  28973. if (pDevice->coreaudio.pAudioBufferList) {
  28974. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28975. }
  28976. } else if (deviceType == ma_device_type_playback) {
  28977. data.formatIn = pDevice->playback.format;
  28978. data.channelsIn = pDevice->playback.channels;
  28979. data.sampleRateIn = pDevice->sampleRate;
  28980. MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
  28981. data.shareMode = pDevice->playback.shareMode;
  28982. data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile;
  28983. data.registerStopEvent = (pDevice->type != ma_device_type_duplex);
  28984. if (disposePreviousAudioUnit) {
  28985. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28986. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28987. }
  28988. }
  28989. data.periodSizeInFramesIn = pDevice->coreaudio.originalPeriodSizeInFrames;
  28990. data.periodSizeInMillisecondsIn = pDevice->coreaudio.originalPeriodSizeInMilliseconds;
  28991. data.periodsIn = pDevice->coreaudio.originalPeriods;
  28992. /* Need at least 3 periods for duplex. */
  28993. if (data.periodsIn < 3 && pDevice->type == ma_device_type_duplex) {
  28994. data.periodsIn = 3;
  28995. }
  28996. result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice);
  28997. if (result != MA_SUCCESS) {
  28998. return result;
  28999. }
  29000. if (deviceType == ma_device_type_capture) {
  29001. #if defined(MA_APPLE_DESKTOP)
  29002. pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID;
  29003. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio);
  29004. #endif
  29005. pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit;
  29006. pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList;
  29007. pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut;
  29008. pDevice->capture.internalFormat = data.formatOut;
  29009. pDevice->capture.internalChannels = data.channelsOut;
  29010. pDevice->capture.internalSampleRate = data.sampleRateOut;
  29011. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  29012. pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  29013. pDevice->capture.internalPeriods = data.periodsOut;
  29014. } else if (deviceType == ma_device_type_playback) {
  29015. #if defined(MA_APPLE_DESKTOP)
  29016. pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
  29017. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio);
  29018. #endif
  29019. pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
  29020. pDevice->playback.internalFormat = data.formatOut;
  29021. pDevice->playback.internalChannels = data.channelsOut;
  29022. pDevice->playback.internalSampleRate = data.sampleRateOut;
  29023. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  29024. pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  29025. pDevice->playback.internalPeriods = data.periodsOut;
  29026. }
  29027. return MA_SUCCESS;
  29028. }
  29029. #endif /* MA_APPLE_DESKTOP */
  29030. static ma_result ma_device_init__coreaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  29031. {
  29032. ma_result result;
  29033. MA_ASSERT(pDevice != NULL);
  29034. MA_ASSERT(pConfig != NULL);
  29035. if (pConfig->deviceType == ma_device_type_loopback) {
  29036. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  29037. }
  29038. /* No exclusive mode with the Core Audio backend for now. */
  29039. if (((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive) ||
  29040. ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive)) {
  29041. return MA_SHARE_MODE_NOT_SUPPORTED;
  29042. }
  29043. /* Capture needs to be initialized first. */
  29044. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  29045. ma_device_init_internal_data__coreaudio data;
  29046. data.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange;
  29047. data.formatIn = pDescriptorCapture->format;
  29048. data.channelsIn = pDescriptorCapture->channels;
  29049. data.sampleRateIn = pDescriptorCapture->sampleRate;
  29050. MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  29051. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  29052. data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
  29053. data.periodsIn = pDescriptorCapture->periodCount;
  29054. data.shareMode = pDescriptorCapture->shareMode;
  29055. data.performanceProfile = pConfig->performanceProfile;
  29056. data.registerStopEvent = MA_TRUE;
  29057. /* Need at least 3 periods for duplex. */
  29058. if (data.periodsIn < 3 && pConfig->deviceType == ma_device_type_duplex) {
  29059. data.periodsIn = 3;
  29060. }
  29061. result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pDescriptorCapture->pDeviceID, &data, (void*)pDevice);
  29062. if (result != MA_SUCCESS) {
  29063. return result;
  29064. }
  29065. pDevice->coreaudio.isDefaultCaptureDevice = (pConfig->capture.pDeviceID == NULL);
  29066. #if defined(MA_APPLE_DESKTOP)
  29067. pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID;
  29068. #endif
  29069. pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit;
  29070. pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList;
  29071. pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut;
  29072. pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  29073. pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
  29074. pDevice->coreaudio.originalPeriods = pDescriptorCapture->periodCount;
  29075. pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile;
  29076. pDescriptorCapture->format = data.formatOut;
  29077. pDescriptorCapture->channels = data.channelsOut;
  29078. pDescriptorCapture->sampleRate = data.sampleRateOut;
  29079. MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  29080. pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
  29081. pDescriptorCapture->periodCount = data.periodsOut;
  29082. #if defined(MA_APPLE_DESKTOP)
  29083. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio);
  29084. /*
  29085. If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
  29086. switch the device in the background.
  29087. */
  29088. if (pConfig->capture.pDeviceID == NULL) {
  29089. ma_device__track__coreaudio(pDevice);
  29090. }
  29091. #endif
  29092. }
  29093. /* Playback. */
  29094. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  29095. ma_device_init_internal_data__coreaudio data;
  29096. data.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange;
  29097. data.formatIn = pDescriptorPlayback->format;
  29098. data.channelsIn = pDescriptorPlayback->channels;
  29099. data.sampleRateIn = pDescriptorPlayback->sampleRate;
  29100. MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  29101. data.shareMode = pDescriptorPlayback->shareMode;
  29102. data.performanceProfile = pConfig->performanceProfile;
  29103. /* In full-duplex mode we want the playback buffer to be the same size as the capture buffer. */
  29104. if (pConfig->deviceType == ma_device_type_duplex) {
  29105. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  29106. data.periodsIn = pDescriptorCapture->periodCount;
  29107. data.registerStopEvent = MA_FALSE;
  29108. } else {
  29109. data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
  29110. data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
  29111. data.periodsIn = pDescriptorPlayback->periodCount;
  29112. data.registerStopEvent = MA_TRUE;
  29113. }
  29114. result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data, (void*)pDevice);
  29115. if (result != MA_SUCCESS) {
  29116. if (pConfig->deviceType == ma_device_type_duplex) {
  29117. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29118. if (pDevice->coreaudio.pAudioBufferList) {
  29119. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  29120. }
  29121. }
  29122. return result;
  29123. }
  29124. pDevice->coreaudio.isDefaultPlaybackDevice = (pConfig->playback.pDeviceID == NULL);
  29125. #if defined(MA_APPLE_DESKTOP)
  29126. pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
  29127. #endif
  29128. pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
  29129. pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  29130. pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
  29131. pDevice->coreaudio.originalPeriods = pDescriptorPlayback->periodCount;
  29132. pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile;
  29133. pDescriptorPlayback->format = data.formatOut;
  29134. pDescriptorPlayback->channels = data.channelsOut;
  29135. pDescriptorPlayback->sampleRate = data.sampleRateOut;
  29136. MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  29137. pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
  29138. pDescriptorPlayback->periodCount = data.periodsOut;
  29139. #if defined(MA_APPLE_DESKTOP)
  29140. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio);
  29141. /*
  29142. If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
  29143. switch the device in the background.
  29144. */
  29145. if (pDescriptorPlayback->pDeviceID == NULL && (pConfig->deviceType != ma_device_type_duplex || pDescriptorCapture->pDeviceID != NULL)) {
  29146. ma_device__track__coreaudio(pDevice);
  29147. }
  29148. #endif
  29149. }
  29150. /*
  29151. When stopping the device, a callback is called on another thread. We need to wait for this callback
  29152. before returning from ma_device_stop(). This event is used for this.
  29153. */
  29154. ma_event_init(&pDevice->coreaudio.stopEvent);
  29155. /*
  29156. We need to detect when a route has changed so we can update the data conversion pipeline accordingly. This is done
  29157. differently on non-Desktop Apple platforms.
  29158. */
  29159. #if defined(MA_APPLE_MOBILE)
  29160. pDevice->coreaudio.pNotificationHandler = (MA_BRIDGE_RETAINED void*)[[ma_ios_notification_handler alloc] init:pDevice];
  29161. #endif
  29162. return MA_SUCCESS;
  29163. }
  29164. static ma_result ma_device_start__coreaudio(ma_device* pDevice)
  29165. {
  29166. MA_ASSERT(pDevice != NULL);
  29167. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29168. OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29169. if (status != noErr) {
  29170. return ma_result_from_OSStatus(status);
  29171. }
  29172. }
  29173. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29174. OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  29175. if (status != noErr) {
  29176. if (pDevice->type == ma_device_type_duplex) {
  29177. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29178. }
  29179. return ma_result_from_OSStatus(status);
  29180. }
  29181. }
  29182. return MA_SUCCESS;
  29183. }
  29184. static ma_result ma_device_stop__coreaudio(ma_device* pDevice)
  29185. {
  29186. MA_ASSERT(pDevice != NULL);
  29187. /* It's not clear from the documentation whether or not AudioOutputUnitStop() actually drains the device or not. */
  29188. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29189. OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  29190. if (status != noErr) {
  29191. return ma_result_from_OSStatus(status);
  29192. }
  29193. }
  29194. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29195. OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  29196. if (status != noErr) {
  29197. return ma_result_from_OSStatus(status);
  29198. }
  29199. }
  29200. /* We need to wait for the callback to finish before returning. */
  29201. ma_event_wait(&pDevice->coreaudio.stopEvent);
  29202. return MA_SUCCESS;
  29203. }
  29204. static ma_result ma_context_uninit__coreaudio(ma_context* pContext)
  29205. {
  29206. MA_ASSERT(pContext != NULL);
  29207. MA_ASSERT(pContext->backend == ma_backend_coreaudio);
  29208. #if defined(MA_APPLE_MOBILE)
  29209. if (!pContext->coreaudio.noAudioSessionDeactivate) {
  29210. if (![[AVAudioSession sharedInstance] setActive:false error:nil]) {
  29211. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to deactivate audio session.");
  29212. return MA_FAILED_TO_INIT_BACKEND;
  29213. }
  29214. }
  29215. #endif
  29216. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29217. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit);
  29218. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio);
  29219. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation);
  29220. #endif
  29221. #if !defined(MA_APPLE_MOBILE)
  29222. ma_context__uninit_device_tracking__coreaudio(pContext);
  29223. #endif
  29224. (void)pContext;
  29225. return MA_SUCCESS;
  29226. }
  29227. #if defined(MA_APPLE_MOBILE) && defined(__IPHONE_12_0)
  29228. static AVAudioSessionCategory ma_to_AVAudioSessionCategory(ma_ios_session_category category)
  29229. {
  29230. /* The "default" and "none" categories are treated different and should not be used as an input into this function. */
  29231. MA_ASSERT(category != ma_ios_session_category_default);
  29232. MA_ASSERT(category != ma_ios_session_category_none);
  29233. switch (category) {
  29234. case ma_ios_session_category_ambient: return AVAudioSessionCategoryAmbient;
  29235. case ma_ios_session_category_solo_ambient: return AVAudioSessionCategorySoloAmbient;
  29236. case ma_ios_session_category_playback: return AVAudioSessionCategoryPlayback;
  29237. case ma_ios_session_category_record: return AVAudioSessionCategoryRecord;
  29238. case ma_ios_session_category_play_and_record: return AVAudioSessionCategoryPlayAndRecord;
  29239. case ma_ios_session_category_multi_route: return AVAudioSessionCategoryMultiRoute;
  29240. case ma_ios_session_category_none: return AVAudioSessionCategoryAmbient;
  29241. case ma_ios_session_category_default: return AVAudioSessionCategoryAmbient;
  29242. default: return AVAudioSessionCategoryAmbient;
  29243. }
  29244. }
  29245. #endif
  29246. static ma_result ma_context_init__coreaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  29247. {
  29248. #if !defined(MA_APPLE_MOBILE)
  29249. ma_result result;
  29250. #endif
  29251. MA_ASSERT(pConfig != NULL);
  29252. MA_ASSERT(pContext != NULL);
  29253. #if defined(MA_APPLE_MOBILE)
  29254. @autoreleasepool {
  29255. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  29256. AVAudioSessionCategoryOptions options = pConfig->coreaudio.sessionCategoryOptions;
  29257. MA_ASSERT(pAudioSession != NULL);
  29258. if (pConfig->coreaudio.sessionCategory == ma_ios_session_category_default) {
  29259. /*
  29260. I'm going to use trial and error to determine our default session category. First we'll try PlayAndRecord. If that fails
  29261. we'll try Playback and if that fails we'll try record. If all of these fail we'll just not set the category.
  29262. */
  29263. #if !defined(MA_APPLE_TV) && !defined(MA_APPLE_WATCH)
  29264. options |= AVAudioSessionCategoryOptionDefaultToSpeaker;
  29265. #endif
  29266. if ([pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:options error:nil]) {
  29267. /* Using PlayAndRecord */
  29268. } else if ([pAudioSession setCategory: AVAudioSessionCategoryPlayback withOptions:options error:nil]) {
  29269. /* Using Playback */
  29270. } else if ([pAudioSession setCategory: AVAudioSessionCategoryRecord withOptions:options error:nil]) {
  29271. /* Using Record */
  29272. } else {
  29273. /* Leave as default? */
  29274. }
  29275. } else {
  29276. if (pConfig->coreaudio.sessionCategory != ma_ios_session_category_none) {
  29277. #if defined(__IPHONE_12_0)
  29278. if (![pAudioSession setCategory: ma_to_AVAudioSessionCategory(pConfig->coreaudio.sessionCategory) withOptions:options error:nil]) {
  29279. return MA_INVALID_OPERATION; /* Failed to set session category. */
  29280. }
  29281. #else
  29282. /* Ignore the session category on version 11 and older, but post a warning. */
  29283. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Session category only supported in iOS 12 and newer.");
  29284. #endif
  29285. }
  29286. }
  29287. if (!pConfig->coreaudio.noAudioSessionActivate) {
  29288. if (![pAudioSession setActive:true error:nil]) {
  29289. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to activate audio session.");
  29290. return MA_FAILED_TO_INIT_BACKEND;
  29291. }
  29292. }
  29293. }
  29294. #endif
  29295. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29296. pContext->coreaudio.hCoreFoundation = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");
  29297. if (pContext->coreaudio.hCoreFoundation == NULL) {
  29298. return MA_API_NOT_FOUND;
  29299. }
  29300. pContext->coreaudio.CFStringGetCString = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation, "CFStringGetCString");
  29301. pContext->coreaudio.CFRelease = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation, "CFRelease");
  29302. pContext->coreaudio.hCoreAudio = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/CoreAudio.framework/CoreAudio");
  29303. if (pContext->coreaudio.hCoreAudio == NULL) {
  29304. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation);
  29305. return MA_API_NOT_FOUND;
  29306. }
  29307. pContext->coreaudio.AudioObjectGetPropertyData = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData");
  29308. pContext->coreaudio.AudioObjectGetPropertyDataSize = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize");
  29309. pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData");
  29310. pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener");
  29311. pContext->coreaudio.AudioObjectRemovePropertyListener = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio, "AudioObjectRemovePropertyListener");
  29312. /*
  29313. It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still
  29314. defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback.
  29315. 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
  29316. AudioToolbox.
  29317. */
  29318. pContext->coreaudio.hAudioUnit = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/AudioUnit.framework/AudioUnit");
  29319. if (pContext->coreaudio.hAudioUnit == NULL) {
  29320. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio);
  29321. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation);
  29322. return MA_API_NOT_FOUND;
  29323. }
  29324. if (ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) {
  29325. /* Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. */
  29326. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit);
  29327. pContext->coreaudio.hAudioUnit = ma_dlopen(ma_context_get_log(pContext), "/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox");
  29328. if (pContext->coreaudio.hAudioUnit == NULL) {
  29329. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio);
  29330. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation);
  29331. return MA_API_NOT_FOUND;
  29332. }
  29333. }
  29334. pContext->coreaudio.AudioComponentFindNext = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentFindNext");
  29335. pContext->coreaudio.AudioComponentInstanceDispose = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose");
  29336. pContext->coreaudio.AudioComponentInstanceNew = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew");
  29337. pContext->coreaudio.AudioOutputUnitStart = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart");
  29338. pContext->coreaudio.AudioOutputUnitStop = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop");
  29339. pContext->coreaudio.AudioUnitAddPropertyListener = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener");
  29340. pContext->coreaudio.AudioUnitGetPropertyInfo = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo");
  29341. pContext->coreaudio.AudioUnitGetProperty = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty");
  29342. pContext->coreaudio.AudioUnitSetProperty = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty");
  29343. pContext->coreaudio.AudioUnitInitialize = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitInitialize");
  29344. pContext->coreaudio.AudioUnitRender = ma_dlsym(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit, "AudioUnitRender");
  29345. #else
  29346. pContext->coreaudio.CFStringGetCString = (ma_proc)CFStringGetCString;
  29347. pContext->coreaudio.CFRelease = (ma_proc)CFRelease;
  29348. #if defined(MA_APPLE_DESKTOP)
  29349. pContext->coreaudio.AudioObjectGetPropertyData = (ma_proc)AudioObjectGetPropertyData;
  29350. pContext->coreaudio.AudioObjectGetPropertyDataSize = (ma_proc)AudioObjectGetPropertyDataSize;
  29351. pContext->coreaudio.AudioObjectSetPropertyData = (ma_proc)AudioObjectSetPropertyData;
  29352. pContext->coreaudio.AudioObjectAddPropertyListener = (ma_proc)AudioObjectAddPropertyListener;
  29353. pContext->coreaudio.AudioObjectRemovePropertyListener = (ma_proc)AudioObjectRemovePropertyListener;
  29354. #endif
  29355. pContext->coreaudio.AudioComponentFindNext = (ma_proc)AudioComponentFindNext;
  29356. pContext->coreaudio.AudioComponentInstanceDispose = (ma_proc)AudioComponentInstanceDispose;
  29357. pContext->coreaudio.AudioComponentInstanceNew = (ma_proc)AudioComponentInstanceNew;
  29358. pContext->coreaudio.AudioOutputUnitStart = (ma_proc)AudioOutputUnitStart;
  29359. pContext->coreaudio.AudioOutputUnitStop = (ma_proc)AudioOutputUnitStop;
  29360. pContext->coreaudio.AudioUnitAddPropertyListener = (ma_proc)AudioUnitAddPropertyListener;
  29361. pContext->coreaudio.AudioUnitGetPropertyInfo = (ma_proc)AudioUnitGetPropertyInfo;
  29362. pContext->coreaudio.AudioUnitGetProperty = (ma_proc)AudioUnitGetProperty;
  29363. pContext->coreaudio.AudioUnitSetProperty = (ma_proc)AudioUnitSetProperty;
  29364. pContext->coreaudio.AudioUnitInitialize = (ma_proc)AudioUnitInitialize;
  29365. pContext->coreaudio.AudioUnitRender = (ma_proc)AudioUnitRender;
  29366. #endif
  29367. /* Audio component. */
  29368. {
  29369. AudioComponentDescription desc;
  29370. desc.componentType = kAudioUnitType_Output;
  29371. #if defined(MA_APPLE_DESKTOP)
  29372. desc.componentSubType = kAudioUnitSubType_HALOutput;
  29373. #else
  29374. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  29375. #endif
  29376. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  29377. desc.componentFlags = 0;
  29378. desc.componentFlagsMask = 0;
  29379. pContext->coreaudio.component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
  29380. if (pContext->coreaudio.component == NULL) {
  29381. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29382. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit);
  29383. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio);
  29384. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation);
  29385. #endif
  29386. return MA_FAILED_TO_INIT_BACKEND;
  29387. }
  29388. }
  29389. #if !defined(MA_APPLE_MOBILE)
  29390. result = ma_context__init_device_tracking__coreaudio(pContext);
  29391. if (result != MA_SUCCESS) {
  29392. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  29393. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hAudioUnit);
  29394. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreAudio);
  29395. ma_dlclose(ma_context_get_log(pContext), pContext->coreaudio.hCoreFoundation);
  29396. #endif
  29397. return result;
  29398. }
  29399. #endif
  29400. pContext->coreaudio.noAudioSessionDeactivate = pConfig->coreaudio.noAudioSessionDeactivate;
  29401. pCallbacks->onContextInit = ma_context_init__coreaudio;
  29402. pCallbacks->onContextUninit = ma_context_uninit__coreaudio;
  29403. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__coreaudio;
  29404. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__coreaudio;
  29405. pCallbacks->onDeviceInit = ma_device_init__coreaudio;
  29406. pCallbacks->onDeviceUninit = ma_device_uninit__coreaudio;
  29407. pCallbacks->onDeviceStart = ma_device_start__coreaudio;
  29408. pCallbacks->onDeviceStop = ma_device_stop__coreaudio;
  29409. pCallbacks->onDeviceRead = NULL;
  29410. pCallbacks->onDeviceWrite = NULL;
  29411. pCallbacks->onDeviceDataLoop = NULL;
  29412. return MA_SUCCESS;
  29413. }
  29414. #endif /* Core Audio */
  29415. /******************************************************************************
  29416. sndio Backend
  29417. ******************************************************************************/
  29418. #ifdef MA_HAS_SNDIO
  29419. #include <fcntl.h>
  29420. /*
  29421. Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due
  29422. to miniaudio's implementation or if it's some kind of system configuration issue, but basically the default device
  29423. just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's
  29424. demand for it or if I can get it tested and debugged more thoroughly.
  29425. */
  29426. #if 0
  29427. #if defined(__NetBSD__) || defined(__OpenBSD__)
  29428. #include <sys/audioio.h>
  29429. #endif
  29430. #if defined(__FreeBSD__) || defined(__DragonFly__)
  29431. #include <sys/soundcard.h>
  29432. #endif
  29433. #endif
  29434. #define MA_SIO_DEVANY "default"
  29435. #define MA_SIO_PLAY 1
  29436. #define MA_SIO_REC 2
  29437. #define MA_SIO_NENC 8
  29438. #define MA_SIO_NCHAN 8
  29439. #define MA_SIO_NRATE 16
  29440. #define MA_SIO_NCONF 4
  29441. struct ma_sio_hdl; /* <-- Opaque */
  29442. struct ma_sio_par
  29443. {
  29444. unsigned int bits;
  29445. unsigned int bps;
  29446. unsigned int sig;
  29447. unsigned int le;
  29448. unsigned int msb;
  29449. unsigned int rchan;
  29450. unsigned int pchan;
  29451. unsigned int rate;
  29452. unsigned int bufsz;
  29453. unsigned int xrun;
  29454. unsigned int round;
  29455. unsigned int appbufsz;
  29456. int __pad[3];
  29457. unsigned int __magic;
  29458. };
  29459. struct ma_sio_enc
  29460. {
  29461. unsigned int bits;
  29462. unsigned int bps;
  29463. unsigned int sig;
  29464. unsigned int le;
  29465. unsigned int msb;
  29466. };
  29467. struct ma_sio_conf
  29468. {
  29469. unsigned int enc;
  29470. unsigned int rchan;
  29471. unsigned int pchan;
  29472. unsigned int rate;
  29473. };
  29474. struct ma_sio_cap
  29475. {
  29476. struct ma_sio_enc enc[MA_SIO_NENC];
  29477. unsigned int rchan[MA_SIO_NCHAN];
  29478. unsigned int pchan[MA_SIO_NCHAN];
  29479. unsigned int rate[MA_SIO_NRATE];
  29480. int __pad[7];
  29481. unsigned int nconf;
  29482. struct ma_sio_conf confs[MA_SIO_NCONF];
  29483. };
  29484. typedef struct ma_sio_hdl* (* ma_sio_open_proc) (const char*, unsigned int, int);
  29485. typedef void (* ma_sio_close_proc) (struct ma_sio_hdl*);
  29486. typedef int (* ma_sio_setpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*);
  29487. typedef int (* ma_sio_getpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*);
  29488. typedef int (* ma_sio_getcap_proc) (struct ma_sio_hdl*, struct ma_sio_cap*);
  29489. typedef size_t (* ma_sio_write_proc) (struct ma_sio_hdl*, const void*, size_t);
  29490. typedef size_t (* ma_sio_read_proc) (struct ma_sio_hdl*, void*, size_t);
  29491. typedef int (* ma_sio_start_proc) (struct ma_sio_hdl*);
  29492. typedef int (* ma_sio_stop_proc) (struct ma_sio_hdl*);
  29493. typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*);
  29494. static ma_uint32 ma_get_standard_sample_rate_priority_index__sndio(ma_uint32 sampleRate) /* Lower = higher priority */
  29495. {
  29496. ma_uint32 i;
  29497. for (i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) {
  29498. if (g_maStandardSampleRatePriorities[i] == sampleRate) {
  29499. return i;
  29500. }
  29501. }
  29502. return (ma_uint32)-1;
  29503. }
  29504. static ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb)
  29505. {
  29506. /* We only support native-endian right now. */
  29507. if ((ma_is_little_endian() && le == 0) || (ma_is_big_endian() && le == 1)) {
  29508. return ma_format_unknown;
  29509. }
  29510. if (bits == 8 && bps == 1 && sig == 0) {
  29511. return ma_format_u8;
  29512. }
  29513. if (bits == 16 && bps == 2 && sig == 1) {
  29514. return ma_format_s16;
  29515. }
  29516. if (bits == 24 && bps == 3 && sig == 1) {
  29517. return ma_format_s24;
  29518. }
  29519. if (bits == 24 && bps == 4 && sig == 1 && msb == 0) {
  29520. /*return ma_format_s24_32;*/
  29521. }
  29522. if (bits == 32 && bps == 4 && sig == 1) {
  29523. return ma_format_s32;
  29524. }
  29525. return ma_format_unknown;
  29526. }
  29527. static ma_format ma_find_best_format_from_sio_cap__sndio(struct ma_sio_cap* caps)
  29528. {
  29529. ma_format bestFormat;
  29530. unsigned int iConfig;
  29531. MA_ASSERT(caps != NULL);
  29532. bestFormat = ma_format_unknown;
  29533. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  29534. unsigned int iEncoding;
  29535. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29536. unsigned int bits;
  29537. unsigned int bps;
  29538. unsigned int sig;
  29539. unsigned int le;
  29540. unsigned int msb;
  29541. ma_format format;
  29542. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29543. continue;
  29544. }
  29545. bits = caps->enc[iEncoding].bits;
  29546. bps = caps->enc[iEncoding].bps;
  29547. sig = caps->enc[iEncoding].sig;
  29548. le = caps->enc[iEncoding].le;
  29549. msb = caps->enc[iEncoding].msb;
  29550. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29551. if (format == ma_format_unknown) {
  29552. continue; /* Format not supported. */
  29553. }
  29554. if (bestFormat == ma_format_unknown) {
  29555. bestFormat = format;
  29556. } else {
  29557. if (ma_get_format_priority_index(bestFormat) > ma_get_format_priority_index(format)) { /* <-- Lower = better. */
  29558. bestFormat = format;
  29559. }
  29560. }
  29561. }
  29562. }
  29563. return bestFormat;
  29564. }
  29565. static ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat)
  29566. {
  29567. ma_uint32 maxChannels;
  29568. unsigned int iConfig;
  29569. MA_ASSERT(caps != NULL);
  29570. MA_ASSERT(requiredFormat != ma_format_unknown);
  29571. /* Just pick whatever configuration has the most channels. */
  29572. maxChannels = 0;
  29573. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  29574. /* The encoding should be of requiredFormat. */
  29575. unsigned int iEncoding;
  29576. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29577. unsigned int iChannel;
  29578. unsigned int bits;
  29579. unsigned int bps;
  29580. unsigned int sig;
  29581. unsigned int le;
  29582. unsigned int msb;
  29583. ma_format format;
  29584. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29585. continue;
  29586. }
  29587. bits = caps->enc[iEncoding].bits;
  29588. bps = caps->enc[iEncoding].bps;
  29589. sig = caps->enc[iEncoding].sig;
  29590. le = caps->enc[iEncoding].le;
  29591. msb = caps->enc[iEncoding].msb;
  29592. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29593. if (format != requiredFormat) {
  29594. continue;
  29595. }
  29596. /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */
  29597. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  29598. unsigned int chan = 0;
  29599. unsigned int channels;
  29600. if (deviceType == ma_device_type_playback) {
  29601. chan = caps->confs[iConfig].pchan;
  29602. } else {
  29603. chan = caps->confs[iConfig].rchan;
  29604. }
  29605. if ((chan & (1UL << iChannel)) == 0) {
  29606. continue;
  29607. }
  29608. if (deviceType == ma_device_type_playback) {
  29609. channels = caps->pchan[iChannel];
  29610. } else {
  29611. channels = caps->rchan[iChannel];
  29612. }
  29613. if (maxChannels < channels) {
  29614. maxChannels = channels;
  29615. }
  29616. }
  29617. }
  29618. }
  29619. return maxChannels;
  29620. }
  29621. 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)
  29622. {
  29623. ma_uint32 firstSampleRate;
  29624. ma_uint32 bestSampleRate;
  29625. unsigned int iConfig;
  29626. MA_ASSERT(caps != NULL);
  29627. MA_ASSERT(requiredFormat != ma_format_unknown);
  29628. MA_ASSERT(requiredChannels > 0);
  29629. MA_ASSERT(requiredChannels <= MA_MAX_CHANNELS);
  29630. firstSampleRate = 0; /* <-- If the device does not support a standard rate we'll fall back to the first one that's found. */
  29631. bestSampleRate = 0;
  29632. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  29633. /* The encoding should be of requiredFormat. */
  29634. unsigned int iEncoding;
  29635. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29636. unsigned int iChannel;
  29637. unsigned int bits;
  29638. unsigned int bps;
  29639. unsigned int sig;
  29640. unsigned int le;
  29641. unsigned int msb;
  29642. ma_format format;
  29643. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29644. continue;
  29645. }
  29646. bits = caps->enc[iEncoding].bits;
  29647. bps = caps->enc[iEncoding].bps;
  29648. sig = caps->enc[iEncoding].sig;
  29649. le = caps->enc[iEncoding].le;
  29650. msb = caps->enc[iEncoding].msb;
  29651. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29652. if (format != requiredFormat) {
  29653. continue;
  29654. }
  29655. /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */
  29656. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  29657. unsigned int chan = 0;
  29658. unsigned int channels;
  29659. unsigned int iRate;
  29660. if (deviceType == ma_device_type_playback) {
  29661. chan = caps->confs[iConfig].pchan;
  29662. } else {
  29663. chan = caps->confs[iConfig].rchan;
  29664. }
  29665. if ((chan & (1UL << iChannel)) == 0) {
  29666. continue;
  29667. }
  29668. if (deviceType == ma_device_type_playback) {
  29669. channels = caps->pchan[iChannel];
  29670. } else {
  29671. channels = caps->rchan[iChannel];
  29672. }
  29673. if (channels != requiredChannels) {
  29674. continue;
  29675. }
  29676. /* Getting here means we have found a compatible encoding/channel pair. */
  29677. for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) {
  29678. ma_uint32 rate = (ma_uint32)caps->rate[iRate];
  29679. ma_uint32 ratePriority;
  29680. if (firstSampleRate == 0) {
  29681. firstSampleRate = rate;
  29682. }
  29683. /* Disregard this rate if it's not a standard one. */
  29684. ratePriority = ma_get_standard_sample_rate_priority_index__sndio(rate);
  29685. if (ratePriority == (ma_uint32)-1) {
  29686. continue;
  29687. }
  29688. if (ma_get_standard_sample_rate_priority_index__sndio(bestSampleRate) > ratePriority) { /* Lower = better. */
  29689. bestSampleRate = rate;
  29690. }
  29691. }
  29692. }
  29693. }
  29694. }
  29695. /* If a standard sample rate was not found just fall back to the first one that was iterated. */
  29696. if (bestSampleRate == 0) {
  29697. bestSampleRate = firstSampleRate;
  29698. }
  29699. return bestSampleRate;
  29700. }
  29701. static ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  29702. {
  29703. ma_bool32 isTerminating = MA_FALSE;
  29704. struct ma_sio_hdl* handle;
  29705. MA_ASSERT(pContext != NULL);
  29706. MA_ASSERT(callback != NULL);
  29707. /* sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating over default devices for now. */
  29708. /* Playback. */
  29709. if (!isTerminating) {
  29710. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_PLAY, 0);
  29711. if (handle != NULL) {
  29712. /* Supports playback. */
  29713. ma_device_info deviceInfo;
  29714. MA_ZERO_OBJECT(&deviceInfo);
  29715. ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), MA_SIO_DEVANY);
  29716. ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
  29717. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  29718. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  29719. }
  29720. }
  29721. /* Capture. */
  29722. if (!isTerminating) {
  29723. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_REC, 0);
  29724. if (handle != NULL) {
  29725. /* Supports capture. */
  29726. ma_device_info deviceInfo;
  29727. MA_ZERO_OBJECT(&deviceInfo);
  29728. ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), "default");
  29729. ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME);
  29730. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  29731. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  29732. }
  29733. }
  29734. return MA_SUCCESS;
  29735. }
  29736. 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)
  29737. {
  29738. char devid[256];
  29739. struct ma_sio_hdl* handle;
  29740. struct ma_sio_cap caps;
  29741. unsigned int iConfig;
  29742. MA_ASSERT(pContext != NULL);
  29743. /* We need to open the device before we can get information about it. */
  29744. if (pDeviceID == NULL) {
  29745. ma_strcpy_s(devid, sizeof(devid), MA_SIO_DEVANY);
  29746. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (deviceType == ma_device_type_playback) ? MA_DEFAULT_PLAYBACK_DEVICE_NAME : MA_DEFAULT_CAPTURE_DEVICE_NAME);
  29747. } else {
  29748. ma_strcpy_s(devid, sizeof(devid), pDeviceID->sndio);
  29749. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid);
  29750. }
  29751. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == ma_device_type_playback) ? MA_SIO_PLAY : MA_SIO_REC, 0);
  29752. if (handle == NULL) {
  29753. return MA_NO_DEVICE;
  29754. }
  29755. if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) {
  29756. return MA_ERROR;
  29757. }
  29758. pDeviceInfo->nativeDataFormatCount = 0;
  29759. for (iConfig = 0; iConfig < caps.nconf; iConfig += 1) {
  29760. /*
  29761. The main thing we care about is that the encoding is supported by miniaudio. If it is, we want to give
  29762. preference to some formats over others.
  29763. */
  29764. unsigned int iEncoding;
  29765. unsigned int iChannel;
  29766. unsigned int iRate;
  29767. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  29768. unsigned int bits;
  29769. unsigned int bps;
  29770. unsigned int sig;
  29771. unsigned int le;
  29772. unsigned int msb;
  29773. ma_format format;
  29774. if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  29775. continue;
  29776. }
  29777. bits = caps.enc[iEncoding].bits;
  29778. bps = caps.enc[iEncoding].bps;
  29779. sig = caps.enc[iEncoding].sig;
  29780. le = caps.enc[iEncoding].le;
  29781. msb = caps.enc[iEncoding].msb;
  29782. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  29783. if (format == ma_format_unknown) {
  29784. continue; /* Format not supported. */
  29785. }
  29786. /* Channels. */
  29787. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  29788. unsigned int chan = 0;
  29789. unsigned int channels;
  29790. if (deviceType == ma_device_type_playback) {
  29791. chan = caps.confs[iConfig].pchan;
  29792. } else {
  29793. chan = caps.confs[iConfig].rchan;
  29794. }
  29795. if ((chan & (1UL << iChannel)) == 0) {
  29796. continue;
  29797. }
  29798. if (deviceType == ma_device_type_playback) {
  29799. channels = caps.pchan[iChannel];
  29800. } else {
  29801. channels = caps.rchan[iChannel];
  29802. }
  29803. /* Sample Rates. */
  29804. for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) {
  29805. if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) {
  29806. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, caps.rate[iRate], 0);
  29807. }
  29808. }
  29809. }
  29810. }
  29811. }
  29812. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  29813. return MA_SUCCESS;
  29814. }
  29815. static ma_result ma_device_uninit__sndio(ma_device* pDevice)
  29816. {
  29817. MA_ASSERT(pDevice != NULL);
  29818. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29819. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29820. }
  29821. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29822. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
  29823. }
  29824. return MA_SUCCESS;
  29825. }
  29826. static ma_result ma_device_init_handle__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  29827. {
  29828. const char* pDeviceName;
  29829. ma_ptr handle;
  29830. int openFlags = 0;
  29831. struct ma_sio_cap caps;
  29832. struct ma_sio_par par;
  29833. const ma_device_id* pDeviceID;
  29834. ma_format format;
  29835. ma_uint32 channels;
  29836. ma_uint32 sampleRate;
  29837. ma_format internalFormat;
  29838. ma_uint32 internalChannels;
  29839. ma_uint32 internalSampleRate;
  29840. ma_uint32 internalPeriodSizeInFrames;
  29841. ma_uint32 internalPeriods;
  29842. MA_ASSERT(pConfig != NULL);
  29843. MA_ASSERT(deviceType != ma_device_type_duplex);
  29844. MA_ASSERT(pDevice != NULL);
  29845. if (deviceType == ma_device_type_capture) {
  29846. openFlags = MA_SIO_REC;
  29847. } else {
  29848. openFlags = MA_SIO_PLAY;
  29849. }
  29850. pDeviceID = pDescriptor->pDeviceID;
  29851. format = pDescriptor->format;
  29852. channels = pDescriptor->channels;
  29853. sampleRate = pDescriptor->sampleRate;
  29854. pDeviceName = MA_SIO_DEVANY;
  29855. if (pDeviceID != NULL) {
  29856. pDeviceName = pDeviceID->sndio;
  29857. }
  29858. handle = (ma_ptr)((ma_sio_open_proc)pDevice->pContext->sndio.sio_open)(pDeviceName, openFlags, 0);
  29859. if (handle == NULL) {
  29860. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to open device.");
  29861. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  29862. }
  29863. /* We need to retrieve the device caps to determine the most appropriate format to use. */
  29864. if (((ma_sio_getcap_proc)pDevice->pContext->sndio.sio_getcap)((struct ma_sio_hdl*)handle, &caps) == 0) {
  29865. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29866. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve device caps.");
  29867. return MA_ERROR;
  29868. }
  29869. /*
  29870. Note: sndio reports a huge range of available channels. This is inconvenient for us because there's no real
  29871. way, as far as I can tell, to get the _actual_ channel count of the device. I'm therefore restricting this
  29872. to the requested channels, regardless of whether or not the default channel count is requested.
  29873. For hardware devices, I'm suspecting only a single channel count will be reported and we can safely use the
  29874. value returned by ma_find_best_channels_from_sio_cap__sndio().
  29875. */
  29876. if (deviceType == ma_device_type_capture) {
  29877. if (format == ma_format_unknown) {
  29878. format = ma_find_best_format_from_sio_cap__sndio(&caps);
  29879. }
  29880. if (channels == 0) {
  29881. if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
  29882. channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
  29883. } else {
  29884. channels = MA_DEFAULT_CHANNELS;
  29885. }
  29886. }
  29887. } else {
  29888. if (format == ma_format_unknown) {
  29889. format = ma_find_best_format_from_sio_cap__sndio(&caps);
  29890. }
  29891. if (channels == 0) {
  29892. if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
  29893. channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
  29894. } else {
  29895. channels = MA_DEFAULT_CHANNELS;
  29896. }
  29897. }
  29898. }
  29899. if (sampleRate == 0) {
  29900. sampleRate = ma_find_best_sample_rate_from_sio_cap__sndio(&caps, pConfig->deviceType, format, channels);
  29901. }
  29902. ((ma_sio_initpar_proc)pDevice->pContext->sndio.sio_initpar)(&par);
  29903. par.msb = 0;
  29904. par.le = ma_is_little_endian();
  29905. switch (format) {
  29906. case ma_format_u8:
  29907. {
  29908. par.bits = 8;
  29909. par.bps = 1;
  29910. par.sig = 0;
  29911. } break;
  29912. case ma_format_s24:
  29913. {
  29914. par.bits = 24;
  29915. par.bps = 3;
  29916. par.sig = 1;
  29917. } break;
  29918. case ma_format_s32:
  29919. {
  29920. par.bits = 32;
  29921. par.bps = 4;
  29922. par.sig = 1;
  29923. } break;
  29924. case ma_format_s16:
  29925. case ma_format_f32:
  29926. case ma_format_unknown:
  29927. default:
  29928. {
  29929. par.bits = 16;
  29930. par.bps = 2;
  29931. par.sig = 1;
  29932. } break;
  29933. }
  29934. if (deviceType == ma_device_type_capture) {
  29935. par.rchan = channels;
  29936. } else {
  29937. par.pchan = channels;
  29938. }
  29939. par.rate = sampleRate;
  29940. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, par.rate, pConfig->performanceProfile);
  29941. par.round = internalPeriodSizeInFrames;
  29942. par.appbufsz = par.round * pDescriptor->periodCount;
  29943. if (((ma_sio_setpar_proc)pDevice->pContext->sndio.sio_setpar)((struct ma_sio_hdl*)handle, &par) == 0) {
  29944. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29945. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size.");
  29946. return MA_ERROR;
  29947. }
  29948. if (((ma_sio_getpar_proc)pDevice->pContext->sndio.sio_getpar)((struct ma_sio_hdl*)handle, &par) == 0) {
  29949. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29950. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size.");
  29951. return MA_ERROR;
  29952. }
  29953. internalFormat = ma_format_from_sio_enc__sndio(par.bits, par.bps, par.sig, par.le, par.msb);
  29954. internalChannels = (deviceType == ma_device_type_capture) ? par.rchan : par.pchan;
  29955. internalSampleRate = par.rate;
  29956. internalPeriods = par.appbufsz / par.round;
  29957. internalPeriodSizeInFrames = par.round;
  29958. if (deviceType == ma_device_type_capture) {
  29959. pDevice->sndio.handleCapture = handle;
  29960. } else {
  29961. pDevice->sndio.handlePlayback = handle;
  29962. }
  29963. pDescriptor->format = internalFormat;
  29964. pDescriptor->channels = internalChannels;
  29965. pDescriptor->sampleRate = internalSampleRate;
  29966. ma_channel_map_init_standard(ma_standard_channel_map_sndio, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels);
  29967. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  29968. pDescriptor->periodCount = internalPeriods;
  29969. return MA_SUCCESS;
  29970. }
  29971. static ma_result ma_device_init__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  29972. {
  29973. MA_ASSERT(pDevice != NULL);
  29974. MA_ZERO_OBJECT(&pDevice->sndio);
  29975. if (pConfig->deviceType == ma_device_type_loopback) {
  29976. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  29977. }
  29978. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  29979. ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  29980. if (result != MA_SUCCESS) {
  29981. return result;
  29982. }
  29983. }
  29984. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  29985. ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  29986. if (result != MA_SUCCESS) {
  29987. return result;
  29988. }
  29989. }
  29990. return MA_SUCCESS;
  29991. }
  29992. static ma_result ma_device_start__sndio(ma_device* pDevice)
  29993. {
  29994. MA_ASSERT(pDevice != NULL);
  29995. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29996. ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29997. }
  29998. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29999. ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); /* <-- Doesn't actually playback until data is written. */
  30000. }
  30001. return MA_SUCCESS;
  30002. }
  30003. static ma_result ma_device_stop__sndio(ma_device* pDevice)
  30004. {
  30005. MA_ASSERT(pDevice != NULL);
  30006. /*
  30007. From the documentation:
  30008. 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
  30009. 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
  30010. buffer is drained. In no case are samples in the play buffer discarded.
  30011. Therefore, sio_stop() performs all of the necessary draining for us.
  30012. */
  30013. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30014. ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  30015. }
  30016. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30017. ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
  30018. }
  30019. return MA_SUCCESS;
  30020. }
  30021. static ma_result ma_device_write__sndio(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  30022. {
  30023. int result;
  30024. if (pFramesWritten != NULL) {
  30025. *pFramesWritten = 0;
  30026. }
  30027. 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));
  30028. if (result == 0) {
  30029. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device.");
  30030. return MA_IO_ERROR;
  30031. }
  30032. if (pFramesWritten != NULL) {
  30033. *pFramesWritten = frameCount;
  30034. }
  30035. return MA_SUCCESS;
  30036. }
  30037. static ma_result ma_device_read__sndio(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  30038. {
  30039. int result;
  30040. if (pFramesRead != NULL) {
  30041. *pFramesRead = 0;
  30042. }
  30043. 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));
  30044. if (result == 0) {
  30045. 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.");
  30046. return MA_IO_ERROR;
  30047. }
  30048. if (pFramesRead != NULL) {
  30049. *pFramesRead = frameCount;
  30050. }
  30051. return MA_SUCCESS;
  30052. }
  30053. static ma_result ma_context_uninit__sndio(ma_context* pContext)
  30054. {
  30055. MA_ASSERT(pContext != NULL);
  30056. MA_ASSERT(pContext->backend == ma_backend_sndio);
  30057. (void)pContext;
  30058. return MA_SUCCESS;
  30059. }
  30060. static ma_result ma_context_init__sndio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  30061. {
  30062. #ifndef MA_NO_RUNTIME_LINKING
  30063. const char* libsndioNames[] = {
  30064. "libsndio.so"
  30065. };
  30066. size_t i;
  30067. for (i = 0; i < ma_countof(libsndioNames); ++i) {
  30068. pContext->sndio.sndioSO = ma_dlopen(ma_context_get_log(pContext), libsndioNames[i]);
  30069. if (pContext->sndio.sndioSO != NULL) {
  30070. break;
  30071. }
  30072. }
  30073. if (pContext->sndio.sndioSO == NULL) {
  30074. return MA_NO_BACKEND;
  30075. }
  30076. pContext->sndio.sio_open = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_open");
  30077. pContext->sndio.sio_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_close");
  30078. pContext->sndio.sio_setpar = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_setpar");
  30079. pContext->sndio.sio_getpar = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_getpar");
  30080. pContext->sndio.sio_getcap = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_getcap");
  30081. pContext->sndio.sio_write = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_write");
  30082. pContext->sndio.sio_read = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_read");
  30083. pContext->sndio.sio_start = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_start");
  30084. pContext->sndio.sio_stop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_stop");
  30085. pContext->sndio.sio_initpar = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->sndio.sndioSO, "sio_initpar");
  30086. #else
  30087. pContext->sndio.sio_open = sio_open;
  30088. pContext->sndio.sio_close = sio_close;
  30089. pContext->sndio.sio_setpar = sio_setpar;
  30090. pContext->sndio.sio_getpar = sio_getpar;
  30091. pContext->sndio.sio_getcap = sio_getcap;
  30092. pContext->sndio.sio_write = sio_write;
  30093. pContext->sndio.sio_read = sio_read;
  30094. pContext->sndio.sio_start = sio_start;
  30095. pContext->sndio.sio_stop = sio_stop;
  30096. pContext->sndio.sio_initpar = sio_initpar;
  30097. #endif
  30098. pCallbacks->onContextInit = ma_context_init__sndio;
  30099. pCallbacks->onContextUninit = ma_context_uninit__sndio;
  30100. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__sndio;
  30101. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__sndio;
  30102. pCallbacks->onDeviceInit = ma_device_init__sndio;
  30103. pCallbacks->onDeviceUninit = ma_device_uninit__sndio;
  30104. pCallbacks->onDeviceStart = ma_device_start__sndio;
  30105. pCallbacks->onDeviceStop = ma_device_stop__sndio;
  30106. pCallbacks->onDeviceRead = ma_device_read__sndio;
  30107. pCallbacks->onDeviceWrite = ma_device_write__sndio;
  30108. pCallbacks->onDeviceDataLoop = NULL;
  30109. (void)pConfig;
  30110. return MA_SUCCESS;
  30111. }
  30112. #endif /* sndio */
  30113. /******************************************************************************
  30114. audio(4) Backend
  30115. ******************************************************************************/
  30116. #ifdef MA_HAS_AUDIO4
  30117. #include <fcntl.h>
  30118. #include <poll.h>
  30119. #include <errno.h>
  30120. #include <sys/stat.h>
  30121. #include <sys/types.h>
  30122. #include <sys/ioctl.h>
  30123. #include <sys/audioio.h>
  30124. #if defined(__OpenBSD__)
  30125. #include <sys/param.h>
  30126. #if defined(OpenBSD) && OpenBSD >= 201709
  30127. #define MA_AUDIO4_USE_NEW_API
  30128. #endif
  30129. #endif
  30130. static void ma_construct_device_id__audio4(char* id, size_t idSize, const char* base, int deviceIndex)
  30131. {
  30132. size_t baseLen;
  30133. MA_ASSERT(id != NULL);
  30134. MA_ASSERT(idSize > 0);
  30135. MA_ASSERT(deviceIndex >= 0);
  30136. baseLen = strlen(base);
  30137. MA_ASSERT(idSize > baseLen);
  30138. ma_strcpy_s(id, idSize, base);
  30139. ma_itoa_s(deviceIndex, id+baseLen, idSize-baseLen, 10);
  30140. }
  30141. static ma_result ma_extract_device_index_from_id__audio4(const char* id, const char* base, int* pIndexOut)
  30142. {
  30143. size_t idLen;
  30144. size_t baseLen;
  30145. const char* deviceIndexStr;
  30146. MA_ASSERT(id != NULL);
  30147. MA_ASSERT(base != NULL);
  30148. MA_ASSERT(pIndexOut != NULL);
  30149. idLen = strlen(id);
  30150. baseLen = strlen(base);
  30151. if (idLen <= baseLen) {
  30152. return MA_ERROR; /* Doesn't look like the id starts with the base. */
  30153. }
  30154. if (strncmp(id, base, baseLen) != 0) {
  30155. return MA_ERROR; /* ID does not begin with base. */
  30156. }
  30157. deviceIndexStr = id + baseLen;
  30158. if (deviceIndexStr[0] == '\0') {
  30159. return MA_ERROR; /* No index specified in the ID. */
  30160. }
  30161. if (pIndexOut) {
  30162. *pIndexOut = atoi(deviceIndexStr);
  30163. }
  30164. return MA_SUCCESS;
  30165. }
  30166. #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
  30167. static ma_format ma_format_from_encoding__audio4(unsigned int encoding, unsigned int precision)
  30168. {
  30169. if (precision == 8 && (encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR_LE || encoding == AUDIO_ENCODING_ULINEAR_BE)) {
  30170. return ma_format_u8;
  30171. } else {
  30172. if (ma_is_little_endian() && encoding == AUDIO_ENCODING_SLINEAR_LE) {
  30173. if (precision == 16) {
  30174. return ma_format_s16;
  30175. } else if (precision == 24) {
  30176. return ma_format_s24;
  30177. } else if (precision == 32) {
  30178. return ma_format_s32;
  30179. }
  30180. } else if (ma_is_big_endian() && encoding == AUDIO_ENCODING_SLINEAR_BE) {
  30181. if (precision == 16) {
  30182. return ma_format_s16;
  30183. } else if (precision == 24) {
  30184. return ma_format_s24;
  30185. } else if (precision == 32) {
  30186. return ma_format_s32;
  30187. }
  30188. }
  30189. }
  30190. return ma_format_unknown; /* Encoding not supported. */
  30191. }
  30192. static void ma_encoding_from_format__audio4(ma_format format, unsigned int* pEncoding, unsigned int* pPrecision)
  30193. {
  30194. MA_ASSERT(pEncoding != NULL);
  30195. MA_ASSERT(pPrecision != NULL);
  30196. switch (format)
  30197. {
  30198. case ma_format_u8:
  30199. {
  30200. *pEncoding = AUDIO_ENCODING_ULINEAR;
  30201. *pPrecision = 8;
  30202. } break;
  30203. case ma_format_s24:
  30204. {
  30205. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  30206. *pPrecision = 24;
  30207. } break;
  30208. case ma_format_s32:
  30209. {
  30210. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  30211. *pPrecision = 32;
  30212. } break;
  30213. case ma_format_s16:
  30214. case ma_format_f32:
  30215. case ma_format_unknown:
  30216. default:
  30217. {
  30218. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  30219. *pPrecision = 16;
  30220. } break;
  30221. }
  30222. }
  30223. static ma_format ma_format_from_prinfo__audio4(struct audio_prinfo* prinfo)
  30224. {
  30225. return ma_format_from_encoding__audio4(prinfo->encoding, prinfo->precision);
  30226. }
  30227. static ma_format ma_best_format_from_fd__audio4(int fd, ma_format preferredFormat)
  30228. {
  30229. audio_encoding_t encoding;
  30230. ma_uint32 iFormat;
  30231. int counter = 0;
  30232. /* First check to see if the preferred format is supported. */
  30233. if (preferredFormat != ma_format_unknown) {
  30234. counter = 0;
  30235. for (;;) {
  30236. MA_ZERO_OBJECT(&encoding);
  30237. encoding.index = counter;
  30238. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  30239. break;
  30240. }
  30241. if (preferredFormat == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) {
  30242. return preferredFormat; /* Found the preferred format. */
  30243. }
  30244. /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */
  30245. counter += 1;
  30246. }
  30247. }
  30248. /* Getting here means our preferred format is not supported, so fall back to our standard priorities. */
  30249. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) {
  30250. ma_format format = g_maFormatPriorities[iFormat];
  30251. counter = 0;
  30252. for (;;) {
  30253. MA_ZERO_OBJECT(&encoding);
  30254. encoding.index = counter;
  30255. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  30256. break;
  30257. }
  30258. if (format == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) {
  30259. return format; /* Found a workable format. */
  30260. }
  30261. /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */
  30262. counter += 1;
  30263. }
  30264. }
  30265. /* Getting here means not appropriate format was found. */
  30266. return ma_format_unknown;
  30267. }
  30268. #else
  30269. static ma_format ma_format_from_swpar__audio4(struct audio_swpar* par)
  30270. {
  30271. if (par->bits == 8 && par->bps == 1 && par->sig == 0) {
  30272. return ma_format_u8;
  30273. }
  30274. if (par->bits == 16 && par->bps == 2 && par->sig == 1 && par->le == ma_is_little_endian()) {
  30275. return ma_format_s16;
  30276. }
  30277. if (par->bits == 24 && par->bps == 3 && par->sig == 1 && par->le == ma_is_little_endian()) {
  30278. return ma_format_s24;
  30279. }
  30280. if (par->bits == 32 && par->bps == 4 && par->sig == 1 && par->le == ma_is_little_endian()) {
  30281. return ma_format_f32;
  30282. }
  30283. /* Format not supported. */
  30284. return ma_format_unknown;
  30285. }
  30286. #endif
  30287. static ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_device_type deviceType, int fd, ma_device_info* pDeviceInfo)
  30288. {
  30289. audio_device_t fdDevice;
  30290. MA_ASSERT(pContext != NULL);
  30291. MA_ASSERT(fd >= 0);
  30292. MA_ASSERT(pDeviceInfo != NULL);
  30293. (void)pContext;
  30294. (void)deviceType;
  30295. if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) {
  30296. return MA_ERROR; /* Failed to retrieve device info. */
  30297. }
  30298. /* Name. */
  30299. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), fdDevice.name);
  30300. #if !defined(MA_AUDIO4_USE_NEW_API)
  30301. {
  30302. audio_info_t fdInfo;
  30303. int counter = 0;
  30304. ma_uint32 channels;
  30305. ma_uint32 sampleRate;
  30306. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  30307. return MA_ERROR;
  30308. }
  30309. if (deviceType == ma_device_type_playback) {
  30310. channels = fdInfo.play.channels;
  30311. sampleRate = fdInfo.play.sample_rate;
  30312. } else {
  30313. channels = fdInfo.record.channels;
  30314. sampleRate = fdInfo.record.sample_rate;
  30315. }
  30316. /* Supported formats. We get this by looking at the encodings. */
  30317. pDeviceInfo->nativeDataFormatCount = 0;
  30318. for (;;) {
  30319. audio_encoding_t encoding;
  30320. ma_format format;
  30321. MA_ZERO_OBJECT(&encoding);
  30322. encoding.index = counter;
  30323. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  30324. break;
  30325. }
  30326. format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision);
  30327. if (format != ma_format_unknown) {
  30328. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0);
  30329. }
  30330. counter += 1;
  30331. }
  30332. }
  30333. #else
  30334. {
  30335. struct audio_swpar fdPar;
  30336. ma_format format;
  30337. ma_uint32 channels;
  30338. ma_uint32 sampleRate;
  30339. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  30340. return MA_ERROR;
  30341. }
  30342. format = ma_format_from_swpar__audio4(&fdPar);
  30343. if (format == ma_format_unknown) {
  30344. return MA_FORMAT_NOT_SUPPORTED;
  30345. }
  30346. if (deviceType == ma_device_type_playback) {
  30347. channels = fdPar.pchan;
  30348. } else {
  30349. channels = fdPar.rchan;
  30350. }
  30351. sampleRate = fdPar.rate;
  30352. pDeviceInfo->nativeDataFormatCount = 0;
  30353. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0);
  30354. }
  30355. #endif
  30356. return MA_SUCCESS;
  30357. }
  30358. static ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  30359. {
  30360. const int maxDevices = 64;
  30361. char devpath[256];
  30362. int iDevice;
  30363. MA_ASSERT(pContext != NULL);
  30364. MA_ASSERT(callback != NULL);
  30365. /*
  30366. Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN"
  30367. version here since we can open it even when another process has control of the "/dev/audioN" device.
  30368. */
  30369. for (iDevice = 0; iDevice < maxDevices; ++iDevice) {
  30370. struct stat st;
  30371. int fd;
  30372. ma_bool32 isTerminating = MA_FALSE;
  30373. ma_strcpy_s(devpath, sizeof(devpath), "/dev/audioctl");
  30374. ma_itoa_s(iDevice, devpath+strlen(devpath), sizeof(devpath)-strlen(devpath), 10);
  30375. if (stat(devpath, &st) < 0) {
  30376. break;
  30377. }
  30378. /* The device exists, but we need to check if it's usable as playback and/or capture. */
  30379. /* Playback. */
  30380. if (!isTerminating) {
  30381. fd = open(devpath, O_RDONLY, 0);
  30382. if (fd >= 0) {
  30383. /* Supports playback. */
  30384. ma_device_info deviceInfo;
  30385. MA_ZERO_OBJECT(&deviceInfo);
  30386. ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice);
  30387. if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_playback, fd, &deviceInfo) == MA_SUCCESS) {
  30388. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  30389. }
  30390. close(fd);
  30391. }
  30392. }
  30393. /* Capture. */
  30394. if (!isTerminating) {
  30395. fd = open(devpath, O_WRONLY, 0);
  30396. if (fd >= 0) {
  30397. /* Supports capture. */
  30398. ma_device_info deviceInfo;
  30399. MA_ZERO_OBJECT(&deviceInfo);
  30400. ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice);
  30401. if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_capture, fd, &deviceInfo) == MA_SUCCESS) {
  30402. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  30403. }
  30404. close(fd);
  30405. }
  30406. }
  30407. if (isTerminating) {
  30408. break;
  30409. }
  30410. }
  30411. return MA_SUCCESS;
  30412. }
  30413. 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)
  30414. {
  30415. int fd = -1;
  30416. int deviceIndex = -1;
  30417. char ctlid[256];
  30418. ma_result result;
  30419. MA_ASSERT(pContext != NULL);
  30420. /*
  30421. We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number
  30422. from the device ID which will be in "/dev/audioN" format.
  30423. */
  30424. if (pDeviceID == NULL) {
  30425. /* Default device. */
  30426. ma_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl");
  30427. } else {
  30428. /* Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". */
  30429. result = ma_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex);
  30430. if (result != MA_SUCCESS) {
  30431. return result;
  30432. }
  30433. ma_construct_device_id__audio4(ctlid, sizeof(ctlid), "/dev/audioctl", deviceIndex);
  30434. }
  30435. fd = open(ctlid, (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY, 0);
  30436. if (fd == -1) {
  30437. return MA_NO_DEVICE;
  30438. }
  30439. if (deviceIndex == -1) {
  30440. ma_strcpy_s(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio");
  30441. } else {
  30442. ma_construct_device_id__audio4(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio", deviceIndex);
  30443. }
  30444. result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo);
  30445. close(fd);
  30446. return result;
  30447. }
  30448. static ma_result ma_device_uninit__audio4(ma_device* pDevice)
  30449. {
  30450. MA_ASSERT(pDevice != NULL);
  30451. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30452. close(pDevice->audio4.fdCapture);
  30453. }
  30454. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30455. close(pDevice->audio4.fdPlayback);
  30456. }
  30457. return MA_SUCCESS;
  30458. }
  30459. static ma_result ma_device_init_fd__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  30460. {
  30461. const char* pDefaultDeviceNames[] = {
  30462. "/dev/audio",
  30463. "/dev/audio0"
  30464. };
  30465. const char* pDefaultDeviceCtlNames[] = {
  30466. "/dev/audioctl",
  30467. "/dev/audioctl0"
  30468. };
  30469. int fd;
  30470. int fdFlags = 0;
  30471. size_t iDefaultDevice = (size_t)-1;
  30472. ma_format internalFormat;
  30473. ma_uint32 internalChannels;
  30474. ma_uint32 internalSampleRate;
  30475. ma_uint32 internalPeriodSizeInFrames;
  30476. ma_uint32 internalPeriods;
  30477. MA_ASSERT(pConfig != NULL);
  30478. MA_ASSERT(deviceType != ma_device_type_duplex);
  30479. MA_ASSERT(pDevice != NULL);
  30480. /* The first thing to do is open the file. */
  30481. if (deviceType == ma_device_type_capture) {
  30482. fdFlags = O_RDONLY;
  30483. } else {
  30484. fdFlags = O_WRONLY;
  30485. }
  30486. /*fdFlags |= O_NONBLOCK;*/
  30487. /* Find the index of the default device as a start. We'll use this index later. Set it to (size_t)-1 otherwise. */
  30488. if (pDescriptor->pDeviceID == NULL) {
  30489. /* Default device. */
  30490. for (iDefaultDevice = 0; iDefaultDevice < ma_countof(pDefaultDeviceNames); ++iDefaultDevice) {
  30491. fd = open(pDefaultDeviceNames[iDefaultDevice], fdFlags, 0);
  30492. if (fd != -1) {
  30493. break;
  30494. }
  30495. }
  30496. } else {
  30497. /* Specific device. */
  30498. fd = open(pDescriptor->pDeviceID->audio4, fdFlags, 0);
  30499. for (iDefaultDevice = 0; iDefaultDevice < ma_countof(pDefaultDeviceNames); iDefaultDevice += 1) {
  30500. if (ma_strcmp(pDefaultDeviceNames[iDefaultDevice], pDescriptor->pDeviceID->audio4) == 0) {
  30501. break;
  30502. }
  30503. }
  30504. if (iDefaultDevice == ma_countof(pDefaultDeviceNames)) {
  30505. iDefaultDevice = (size_t)-1;
  30506. }
  30507. }
  30508. if (fd == -1) {
  30509. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to open device.");
  30510. return ma_result_from_errno(errno);
  30511. }
  30512. #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
  30513. {
  30514. audio_info_t fdInfo;
  30515. int fdInfoResult = -1;
  30516. /*
  30517. The documentation is a little bit unclear to me as to how it handles formats. It says the
  30518. following:
  30519. Regardless of formats supported by underlying driver, the audio driver accepts the
  30520. following formats.
  30521. By then the next sentence says this:
  30522. `encoding` and `precision` are one of the values obtained by AUDIO_GETENC.
  30523. It sounds like a direct contradiction to me. I'm going to play this safe any only use the
  30524. best sample format returned by AUDIO_GETENC. If the requested format is supported we'll
  30525. use that, but otherwise we'll just use our standard format priorities to pick an
  30526. appropriate one.
  30527. */
  30528. AUDIO_INITINFO(&fdInfo);
  30529. /*
  30530. Get the default format from the audioctl file if we're asking for a default device. If we
  30531. retrieve it from /dev/audio it'll default to mono 8000Hz.
  30532. */
  30533. if (iDefaultDevice != (size_t)-1) {
  30534. /* We're using a default device. Get the info from the /dev/audioctl file instead of /dev/audio. */
  30535. int fdctl = open(pDefaultDeviceCtlNames[iDefaultDevice], fdFlags, 0);
  30536. if (fdctl != -1) {
  30537. fdInfoResult = ioctl(fdctl, AUDIO_GETINFO, &fdInfo);
  30538. close(fdctl);
  30539. }
  30540. }
  30541. if (fdInfoResult == -1) {
  30542. /* We still don't have the default device info so just retrieve it from the main audio device. */
  30543. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  30544. close(fd);
  30545. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.");
  30546. return ma_result_from_errno(errno);
  30547. }
  30548. }
  30549. /* We get the driver to do as much of the data conversion as possible. */
  30550. if (deviceType == ma_device_type_capture) {
  30551. fdInfo.mode = AUMODE_RECORD;
  30552. ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.record.encoding, &fdInfo.record.precision);
  30553. if (pDescriptor->channels != 0) {
  30554. fdInfo.record.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */
  30555. }
  30556. if (pDescriptor->sampleRate != 0) {
  30557. 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`.) */
  30558. }
  30559. } else {
  30560. fdInfo.mode = AUMODE_PLAY;
  30561. ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.play.encoding, &fdInfo.play.precision);
  30562. if (pDescriptor->channels != 0) {
  30563. fdInfo.play.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */
  30564. }
  30565. if (pDescriptor->sampleRate != 0) {
  30566. 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`.) */
  30567. }
  30568. }
  30569. if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
  30570. close(fd);
  30571. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed.");
  30572. return ma_result_from_errno(errno);
  30573. }
  30574. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  30575. close(fd);
  30576. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.");
  30577. return ma_result_from_errno(errno);
  30578. }
  30579. if (deviceType == ma_device_type_capture) {
  30580. internalFormat = ma_format_from_prinfo__audio4(&fdInfo.record);
  30581. internalChannels = fdInfo.record.channels;
  30582. internalSampleRate = fdInfo.record.sample_rate;
  30583. } else {
  30584. internalFormat = ma_format_from_prinfo__audio4(&fdInfo.play);
  30585. internalChannels = fdInfo.play.channels;
  30586. internalSampleRate = fdInfo.play.sample_rate;
  30587. }
  30588. if (internalFormat == ma_format_unknown) {
  30589. close(fd);
  30590. 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.");
  30591. return MA_FORMAT_NOT_SUPPORTED;
  30592. }
  30593. /* Buffer. */
  30594. {
  30595. ma_uint32 internalPeriodSizeInBytes;
  30596. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile);
  30597. internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
  30598. if (internalPeriodSizeInBytes < 16) {
  30599. internalPeriodSizeInBytes = 16;
  30600. }
  30601. internalPeriods = pDescriptor->periodCount;
  30602. if (internalPeriods < 2) {
  30603. internalPeriods = 2;
  30604. }
  30605. /* What miniaudio calls a period, audio4 calls a block. */
  30606. AUDIO_INITINFO(&fdInfo);
  30607. fdInfo.hiwat = internalPeriods;
  30608. fdInfo.lowat = internalPeriods-1;
  30609. fdInfo.blocksize = internalPeriodSizeInBytes;
  30610. if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
  30611. close(fd);
  30612. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed.");
  30613. return ma_result_from_errno(errno);
  30614. }
  30615. internalPeriods = fdInfo.hiwat;
  30616. internalPeriodSizeInFrames = fdInfo.blocksize / ma_get_bytes_per_frame(internalFormat, internalChannels);
  30617. }
  30618. }
  30619. #else
  30620. {
  30621. struct audio_swpar fdPar;
  30622. /* 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. */
  30623. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  30624. close(fd);
  30625. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters.");
  30626. return ma_result_from_errno(errno);
  30627. }
  30628. internalFormat = ma_format_from_swpar__audio4(&fdPar);
  30629. internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
  30630. internalSampleRate = fdPar.rate;
  30631. if (internalFormat == ma_format_unknown) {
  30632. close(fd);
  30633. 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.");
  30634. return MA_FORMAT_NOT_SUPPORTED;
  30635. }
  30636. /* Buffer. */
  30637. {
  30638. ma_uint32 internalPeriodSizeInBytes;
  30639. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile);
  30640. /* What miniaudio calls a period, audio4 calls a block. */
  30641. internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
  30642. if (internalPeriodSizeInBytes < 16) {
  30643. internalPeriodSizeInBytes = 16;
  30644. }
  30645. fdPar.nblks = pDescriptor->periodCount;
  30646. fdPar.round = internalPeriodSizeInBytes;
  30647. if (ioctl(fd, AUDIO_SETPAR, &fdPar) < 0) {
  30648. close(fd);
  30649. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters.");
  30650. return ma_result_from_errno(errno);
  30651. }
  30652. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  30653. close(fd);
  30654. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters.");
  30655. return ma_result_from_errno(errno);
  30656. }
  30657. }
  30658. internalFormat = ma_format_from_swpar__audio4(&fdPar);
  30659. internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
  30660. internalSampleRate = fdPar.rate;
  30661. internalPeriods = fdPar.nblks;
  30662. internalPeriodSizeInFrames = fdPar.round / ma_get_bytes_per_frame(internalFormat, internalChannels);
  30663. }
  30664. #endif
  30665. if (internalFormat == ma_format_unknown) {
  30666. close(fd);
  30667. 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.");
  30668. return MA_FORMAT_NOT_SUPPORTED;
  30669. }
  30670. if (deviceType == ma_device_type_capture) {
  30671. pDevice->audio4.fdCapture = fd;
  30672. } else {
  30673. pDevice->audio4.fdPlayback = fd;
  30674. }
  30675. pDescriptor->format = internalFormat;
  30676. pDescriptor->channels = internalChannels;
  30677. pDescriptor->sampleRate = internalSampleRate;
  30678. ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels);
  30679. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  30680. pDescriptor->periodCount = internalPeriods;
  30681. return MA_SUCCESS;
  30682. }
  30683. static ma_result ma_device_init__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  30684. {
  30685. MA_ASSERT(pDevice != NULL);
  30686. MA_ZERO_OBJECT(&pDevice->audio4);
  30687. if (pConfig->deviceType == ma_device_type_loopback) {
  30688. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  30689. }
  30690. pDevice->audio4.fdCapture = -1;
  30691. pDevice->audio4.fdPlayback = -1;
  30692. /*
  30693. The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD
  30694. introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as
  30695. I'm aware.
  30696. */
  30697. #if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000
  30698. /* NetBSD 8.0+ */
  30699. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  30700. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  30701. return MA_SHARE_MODE_NOT_SUPPORTED;
  30702. }
  30703. #else
  30704. /* All other flavors. */
  30705. #endif
  30706. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  30707. ma_result result = ma_device_init_fd__audio4(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  30708. if (result != MA_SUCCESS) {
  30709. return result;
  30710. }
  30711. }
  30712. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  30713. ma_result result = ma_device_init_fd__audio4(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  30714. if (result != MA_SUCCESS) {
  30715. if (pConfig->deviceType == ma_device_type_duplex) {
  30716. close(pDevice->audio4.fdCapture);
  30717. }
  30718. return result;
  30719. }
  30720. }
  30721. return MA_SUCCESS;
  30722. }
  30723. static ma_result ma_device_start__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. if (pDevice->audio4.fdCapture == -1) {
  30728. return MA_INVALID_ARGS;
  30729. }
  30730. }
  30731. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30732. if (pDevice->audio4.fdPlayback == -1) {
  30733. return MA_INVALID_ARGS;
  30734. }
  30735. }
  30736. return MA_SUCCESS;
  30737. }
  30738. static ma_result ma_device_stop_fd__audio4(ma_device* pDevice, int fd)
  30739. {
  30740. if (fd == -1) {
  30741. return MA_INVALID_ARGS;
  30742. }
  30743. #if !defined(MA_AUDIO4_USE_NEW_API)
  30744. if (ioctl(fd, AUDIO_FLUSH, 0) < 0) {
  30745. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed.");
  30746. return ma_result_from_errno(errno);
  30747. }
  30748. #else
  30749. if (ioctl(fd, AUDIO_STOP, 0) < 0) {
  30750. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed.");
  30751. return ma_result_from_errno(errno);
  30752. }
  30753. #endif
  30754. return MA_SUCCESS;
  30755. }
  30756. static ma_result ma_device_stop__audio4(ma_device* pDevice)
  30757. {
  30758. MA_ASSERT(pDevice != NULL);
  30759. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30760. ma_result result;
  30761. result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdCapture);
  30762. if (result != MA_SUCCESS) {
  30763. return result;
  30764. }
  30765. }
  30766. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30767. ma_result result;
  30768. /* 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. */
  30769. #if !defined(MA_AUDIO4_USE_NEW_API)
  30770. ioctl(pDevice->audio4.fdPlayback, AUDIO_DRAIN, 0);
  30771. #endif
  30772. /* Here is where the device is stopped immediately. */
  30773. result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdPlayback);
  30774. if (result != MA_SUCCESS) {
  30775. return result;
  30776. }
  30777. }
  30778. return MA_SUCCESS;
  30779. }
  30780. static ma_result ma_device_write__audio4(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  30781. {
  30782. int result;
  30783. if (pFramesWritten != NULL) {
  30784. *pFramesWritten = 0;
  30785. }
  30786. result = write(pDevice->audio4.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  30787. if (result < 0) {
  30788. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to write data to the device.");
  30789. return ma_result_from_errno(errno);
  30790. }
  30791. if (pFramesWritten != NULL) {
  30792. *pFramesWritten = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  30793. }
  30794. return MA_SUCCESS;
  30795. }
  30796. static ma_result ma_device_read__audio4(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  30797. {
  30798. int result;
  30799. if (pFramesRead != NULL) {
  30800. *pFramesRead = 0;
  30801. }
  30802. result = read(pDevice->audio4.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  30803. if (result < 0) {
  30804. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device.");
  30805. return ma_result_from_errno(errno);
  30806. }
  30807. if (pFramesRead != NULL) {
  30808. *pFramesRead = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  30809. }
  30810. return MA_SUCCESS;
  30811. }
  30812. static ma_result ma_context_uninit__audio4(ma_context* pContext)
  30813. {
  30814. MA_ASSERT(pContext != NULL);
  30815. MA_ASSERT(pContext->backend == ma_backend_audio4);
  30816. (void)pContext;
  30817. return MA_SUCCESS;
  30818. }
  30819. static ma_result ma_context_init__audio4(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  30820. {
  30821. MA_ASSERT(pContext != NULL);
  30822. (void)pConfig;
  30823. pCallbacks->onContextInit = ma_context_init__audio4;
  30824. pCallbacks->onContextUninit = ma_context_uninit__audio4;
  30825. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__audio4;
  30826. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__audio4;
  30827. pCallbacks->onDeviceInit = ma_device_init__audio4;
  30828. pCallbacks->onDeviceUninit = ma_device_uninit__audio4;
  30829. pCallbacks->onDeviceStart = ma_device_start__audio4;
  30830. pCallbacks->onDeviceStop = ma_device_stop__audio4;
  30831. pCallbacks->onDeviceRead = ma_device_read__audio4;
  30832. pCallbacks->onDeviceWrite = ma_device_write__audio4;
  30833. pCallbacks->onDeviceDataLoop = NULL;
  30834. return MA_SUCCESS;
  30835. }
  30836. #endif /* audio4 */
  30837. /******************************************************************************
  30838. OSS Backend
  30839. ******************************************************************************/
  30840. #ifdef MA_HAS_OSS
  30841. #include <sys/ioctl.h>
  30842. #include <unistd.h>
  30843. #include <fcntl.h>
  30844. #include <sys/soundcard.h>
  30845. #ifndef SNDCTL_DSP_HALT
  30846. #define SNDCTL_DSP_HALT SNDCTL_DSP_RESET
  30847. #endif
  30848. #define MA_OSS_DEFAULT_DEVICE_NAME "/dev/dsp"
  30849. static int ma_open_temp_device__oss()
  30850. {
  30851. /* The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. */
  30852. int fd = open("/dev/mixer", O_RDONLY, 0);
  30853. if (fd >= 0) {
  30854. return fd;
  30855. }
  30856. return -1;
  30857. }
  30858. 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)
  30859. {
  30860. const char* deviceName;
  30861. int flags;
  30862. MA_ASSERT(pContext != NULL);
  30863. MA_ASSERT(pfd != NULL);
  30864. (void)pContext;
  30865. *pfd = -1;
  30866. /* This function should only be called for playback or capture, not duplex. */
  30867. if (deviceType == ma_device_type_duplex) {
  30868. return MA_INVALID_ARGS;
  30869. }
  30870. deviceName = MA_OSS_DEFAULT_DEVICE_NAME;
  30871. if (pDeviceID != NULL) {
  30872. deviceName = pDeviceID->oss;
  30873. }
  30874. flags = (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY;
  30875. if (shareMode == ma_share_mode_exclusive) {
  30876. flags |= O_EXCL;
  30877. }
  30878. *pfd = open(deviceName, flags, 0);
  30879. if (*pfd == -1) {
  30880. return ma_result_from_errno(errno);
  30881. }
  30882. return MA_SUCCESS;
  30883. }
  30884. static ma_result ma_context_enumerate_devices__oss(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  30885. {
  30886. int fd;
  30887. oss_sysinfo si;
  30888. int result;
  30889. MA_ASSERT(pContext != NULL);
  30890. MA_ASSERT(callback != NULL);
  30891. fd = ma_open_temp_device__oss();
  30892. if (fd == -1) {
  30893. 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.");
  30894. return MA_NO_BACKEND;
  30895. }
  30896. result = ioctl(fd, SNDCTL_SYSINFO, &si);
  30897. if (result != -1) {
  30898. int iAudioDevice;
  30899. for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) {
  30900. oss_audioinfo ai;
  30901. ai.dev = iAudioDevice;
  30902. result = ioctl(fd, SNDCTL_AUDIOINFO, &ai);
  30903. if (result != -1) {
  30904. if (ai.devnode[0] != '\0') { /* <-- Can be blank, according to documentation. */
  30905. ma_device_info deviceInfo;
  30906. ma_bool32 isTerminating = MA_FALSE;
  30907. MA_ZERO_OBJECT(&deviceInfo);
  30908. /* ID */
  30909. ma_strncpy_s(deviceInfo.id.oss, sizeof(deviceInfo.id.oss), ai.devnode, (size_t)-1);
  30910. /*
  30911. The human readable device name should be in the "ai.handle" variable, but it can
  30912. sometimes be empty in which case we just fall back to "ai.name" which is less user
  30913. friendly, but usually has a value.
  30914. */
  30915. if (ai.handle[0] != '\0') {
  30916. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.handle, (size_t)-1);
  30917. } else {
  30918. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.name, (size_t)-1);
  30919. }
  30920. /* The device can be both playback and capture. */
  30921. if (!isTerminating && (ai.caps & PCM_CAP_OUTPUT) != 0) {
  30922. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  30923. }
  30924. if (!isTerminating && (ai.caps & PCM_CAP_INPUT) != 0) {
  30925. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  30926. }
  30927. if (isTerminating) {
  30928. break;
  30929. }
  30930. }
  30931. }
  30932. }
  30933. } else {
  30934. close(fd);
  30935. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.");
  30936. return MA_NO_BACKEND;
  30937. }
  30938. close(fd);
  30939. return MA_SUCCESS;
  30940. }
  30941. static void ma_context_add_native_data_format__oss(ma_context* pContext, oss_audioinfo* pAudioInfo, ma_format format, ma_device_info* pDeviceInfo)
  30942. {
  30943. unsigned int minChannels;
  30944. unsigned int maxChannels;
  30945. unsigned int iRate;
  30946. MA_ASSERT(pContext != NULL);
  30947. MA_ASSERT(pAudioInfo != NULL);
  30948. MA_ASSERT(pDeviceInfo != NULL);
  30949. /* If we support all channels we just report 0. */
  30950. minChannels = ma_clamp(pAudioInfo->min_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  30951. maxChannels = ma_clamp(pAudioInfo->max_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  30952. /*
  30953. OSS has this annoying thing where sample rates can be reported in two ways. We prefer explicitness,
  30954. which OSS has in the form of nrates/rates, however there are times where nrates can be 0, in which
  30955. case we'll need to use min_rate and max_rate and report only standard rates.
  30956. */
  30957. if (pAudioInfo->nrates > 0) {
  30958. for (iRate = 0; iRate < pAudioInfo->nrates; iRate += 1) {
  30959. unsigned int rate = pAudioInfo->rates[iRate];
  30960. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  30961. 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. */
  30962. } else {
  30963. unsigned int iChannel;
  30964. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  30965. ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, rate, 0);
  30966. }
  30967. }
  30968. }
  30969. } else {
  30970. for (iRate = 0; iRate < ma_countof(g_maStandardSampleRatePriorities); iRate += 1) {
  30971. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iRate];
  30972. if (standardRate >= (ma_uint32)pAudioInfo->min_rate && standardRate <= (ma_uint32)pAudioInfo->max_rate) {
  30973. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  30974. 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. */
  30975. } else {
  30976. unsigned int iChannel;
  30977. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  30978. ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, standardRate, 0);
  30979. }
  30980. }
  30981. }
  30982. }
  30983. }
  30984. }
  30985. 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)
  30986. {
  30987. ma_bool32 foundDevice;
  30988. int fdTemp;
  30989. oss_sysinfo si;
  30990. int result;
  30991. MA_ASSERT(pContext != NULL);
  30992. /* Handle the default device a little differently. */
  30993. if (pDeviceID == NULL) {
  30994. if (deviceType == ma_device_type_playback) {
  30995. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  30996. } else {
  30997. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  30998. }
  30999. return MA_SUCCESS;
  31000. }
  31001. /* If we get here it means we are _not_ using the default device. */
  31002. foundDevice = MA_FALSE;
  31003. fdTemp = ma_open_temp_device__oss();
  31004. if (fdTemp == -1) {
  31005. 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.");
  31006. return MA_NO_BACKEND;
  31007. }
  31008. result = ioctl(fdTemp, SNDCTL_SYSINFO, &si);
  31009. if (result != -1) {
  31010. int iAudioDevice;
  31011. for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) {
  31012. oss_audioinfo ai;
  31013. ai.dev = iAudioDevice;
  31014. result = ioctl(fdTemp, SNDCTL_AUDIOINFO, &ai);
  31015. if (result != -1) {
  31016. if (ma_strcmp(ai.devnode, pDeviceID->oss) == 0) {
  31017. /* It has the same name, so now just confirm the type. */
  31018. if ((deviceType == ma_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) ||
  31019. (deviceType == ma_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) {
  31020. unsigned int formatMask;
  31021. /* ID */
  31022. ma_strncpy_s(pDeviceInfo->id.oss, sizeof(pDeviceInfo->id.oss), ai.devnode, (size_t)-1);
  31023. /*
  31024. The human readable device name should be in the "ai.handle" variable, but it can
  31025. sometimes be empty in which case we just fall back to "ai.name" which is less user
  31026. friendly, but usually has a value.
  31027. */
  31028. if (ai.handle[0] != '\0') {
  31029. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.handle, (size_t)-1);
  31030. } else {
  31031. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.name, (size_t)-1);
  31032. }
  31033. pDeviceInfo->nativeDataFormatCount = 0;
  31034. if (deviceType == ma_device_type_playback) {
  31035. formatMask = ai.oformats;
  31036. } else {
  31037. formatMask = ai.iformats;
  31038. }
  31039. if (((formatMask & AFMT_S16_LE) != 0 && ma_is_little_endian()) || (AFMT_S16_BE && ma_is_big_endian())) {
  31040. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s16, pDeviceInfo);
  31041. }
  31042. if (((formatMask & AFMT_S32_LE) != 0 && ma_is_little_endian()) || (AFMT_S32_BE && ma_is_big_endian())) {
  31043. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s32, pDeviceInfo);
  31044. }
  31045. if ((formatMask & AFMT_U8) != 0) {
  31046. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_u8, pDeviceInfo);
  31047. }
  31048. foundDevice = MA_TRUE;
  31049. break;
  31050. }
  31051. }
  31052. }
  31053. }
  31054. } else {
  31055. close(fdTemp);
  31056. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.");
  31057. return MA_NO_BACKEND;
  31058. }
  31059. close(fdTemp);
  31060. if (!foundDevice) {
  31061. return MA_NO_DEVICE;
  31062. }
  31063. return MA_SUCCESS;
  31064. }
  31065. static ma_result ma_device_uninit__oss(ma_device* pDevice)
  31066. {
  31067. MA_ASSERT(pDevice != NULL);
  31068. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31069. close(pDevice->oss.fdCapture);
  31070. }
  31071. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31072. close(pDevice->oss.fdPlayback);
  31073. }
  31074. return MA_SUCCESS;
  31075. }
  31076. static int ma_format_to_oss(ma_format format)
  31077. {
  31078. int ossFormat = AFMT_U8;
  31079. switch (format) {
  31080. case ma_format_s16: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break;
  31081. case ma_format_s24: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break;
  31082. case ma_format_s32: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break;
  31083. case ma_format_f32: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break;
  31084. case ma_format_u8:
  31085. default: ossFormat = AFMT_U8; break;
  31086. }
  31087. return ossFormat;
  31088. }
  31089. static ma_format ma_format_from_oss(int ossFormat)
  31090. {
  31091. if (ossFormat == AFMT_U8) {
  31092. return ma_format_u8;
  31093. } else {
  31094. if (ma_is_little_endian()) {
  31095. switch (ossFormat) {
  31096. case AFMT_S16_LE: return ma_format_s16;
  31097. case AFMT_S32_LE: return ma_format_s32;
  31098. default: return ma_format_unknown;
  31099. }
  31100. } else {
  31101. switch (ossFormat) {
  31102. case AFMT_S16_BE: return ma_format_s16;
  31103. case AFMT_S32_BE: return ma_format_s32;
  31104. default: return ma_format_unknown;
  31105. }
  31106. }
  31107. }
  31108. return ma_format_unknown;
  31109. }
  31110. static ma_result ma_device_init_fd__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  31111. {
  31112. ma_result result;
  31113. int ossResult;
  31114. int fd;
  31115. const ma_device_id* pDeviceID = NULL;
  31116. ma_share_mode shareMode;
  31117. int ossFormat;
  31118. int ossChannels;
  31119. int ossSampleRate;
  31120. int ossFragment;
  31121. MA_ASSERT(pDevice != NULL);
  31122. MA_ASSERT(pConfig != NULL);
  31123. MA_ASSERT(deviceType != ma_device_type_duplex);
  31124. pDeviceID = pDescriptor->pDeviceID;
  31125. shareMode = pDescriptor->shareMode;
  31126. 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. */
  31127. ossChannels = (int)(pDescriptor->channels > 0) ? pDescriptor->channels : MA_DEFAULT_CHANNELS;
  31128. ossSampleRate = (int)(pDescriptor->sampleRate > 0) ? pDescriptor->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  31129. result = ma_context_open_device__oss(pDevice->pContext, deviceType, pDeviceID, shareMode, &fd);
  31130. if (result != MA_SUCCESS) {
  31131. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  31132. return result;
  31133. }
  31134. /*
  31135. The OSS documantation is very clear about the order we should be initializing the device's properties:
  31136. 1) Format
  31137. 2) Channels
  31138. 3) Sample rate.
  31139. */
  31140. /* Format. */
  31141. ossResult = ioctl(fd, SNDCTL_DSP_SETFMT, &ossFormat);
  31142. if (ossResult == -1) {
  31143. close(fd);
  31144. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set format.");
  31145. return ma_result_from_errno(errno);
  31146. }
  31147. /* Channels. */
  31148. ossResult = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossChannels);
  31149. if (ossResult == -1) {
  31150. close(fd);
  31151. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count.");
  31152. return ma_result_from_errno(errno);
  31153. }
  31154. /* Sample Rate. */
  31155. ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate);
  31156. if (ossResult == -1) {
  31157. close(fd);
  31158. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.");
  31159. return ma_result_from_errno(errno);
  31160. }
  31161. /*
  31162. Buffer.
  31163. The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if
  31164. it should be done before or after format/channels/rate.
  31165. OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual
  31166. value.
  31167. */
  31168. {
  31169. ma_uint32 periodSizeInFrames;
  31170. ma_uint32 periodSizeInBytes;
  31171. ma_uint32 ossFragmentSizePower;
  31172. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, (ma_uint32)ossSampleRate, pConfig->performanceProfile);
  31173. periodSizeInBytes = ma_round_to_power_of_2(periodSizeInFrames * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels));
  31174. if (periodSizeInBytes < 16) {
  31175. periodSizeInBytes = 16;
  31176. }
  31177. ossFragmentSizePower = 4;
  31178. periodSizeInBytes >>= 4;
  31179. while (periodSizeInBytes >>= 1) {
  31180. ossFragmentSizePower += 1;
  31181. }
  31182. ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower);
  31183. ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment);
  31184. if (ossResult == -1) {
  31185. close(fd);
  31186. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.");
  31187. return ma_result_from_errno(errno);
  31188. }
  31189. }
  31190. /* Internal settings. */
  31191. if (deviceType == ma_device_type_capture) {
  31192. pDevice->oss.fdCapture = fd;
  31193. } else {
  31194. pDevice->oss.fdPlayback = fd;
  31195. }
  31196. pDescriptor->format = ma_format_from_oss(ossFormat);
  31197. pDescriptor->channels = ossChannels;
  31198. pDescriptor->sampleRate = ossSampleRate;
  31199. ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels);
  31200. pDescriptor->periodCount = (ma_uint32)(ossFragment >> 16);
  31201. pDescriptor->periodSizeInFrames = (ma_uint32)(1 << (ossFragment & 0xFFFF)) / ma_get_bytes_per_frame(pDescriptor->format, pDescriptor->channels);
  31202. if (pDescriptor->format == ma_format_unknown) {
  31203. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.");
  31204. return MA_FORMAT_NOT_SUPPORTED;
  31205. }
  31206. return MA_SUCCESS;
  31207. }
  31208. static ma_result ma_device_init__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  31209. {
  31210. MA_ASSERT(pDevice != NULL);
  31211. MA_ASSERT(pConfig != NULL);
  31212. MA_ZERO_OBJECT(&pDevice->oss);
  31213. if (pConfig->deviceType == ma_device_type_loopback) {
  31214. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  31215. }
  31216. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  31217. ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  31218. if (result != MA_SUCCESS) {
  31219. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  31220. return result;
  31221. }
  31222. }
  31223. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  31224. ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  31225. if (result != MA_SUCCESS) {
  31226. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  31227. return result;
  31228. }
  31229. }
  31230. return MA_SUCCESS;
  31231. }
  31232. /*
  31233. Note on Starting and Stopping
  31234. =============================
  31235. In the past I was using SNDCTL_DSP_HALT to stop the device, however this results in issues when
  31236. trying to resume the device again. If we use SNDCTL_DSP_HALT, the next write() or read() will
  31237. fail. Instead what we need to do is just not write or read to and from the device when the
  31238. device is not running.
  31239. As a result, both the start and stop functions for OSS are just empty stubs. The starting and
  31240. stopping logic is handled by ma_device_write__oss() and ma_device_read__oss(). These will check
  31241. the device state, and if the device is stopped they will simply not do any kind of processing.
  31242. The downside to this technique is that I've noticed a fairly lengthy delay in stopping the
  31243. device, up to a second. This is on a virtual machine, and as such might just be due to the
  31244. virtual drivers, but I'm not fully sure. I am not sure how to work around this problem so for
  31245. the moment that's just how it's going to have to be.
  31246. When starting the device, OSS will automatically start it when write() or read() is called.
  31247. */
  31248. static ma_result ma_device_start__oss(ma_device* pDevice)
  31249. {
  31250. MA_ASSERT(pDevice != NULL);
  31251. /* The device is automatically started with reading and writing. */
  31252. (void)pDevice;
  31253. return MA_SUCCESS;
  31254. }
  31255. static ma_result ma_device_stop__oss(ma_device* pDevice)
  31256. {
  31257. MA_ASSERT(pDevice != NULL);
  31258. /* See note above on why this is empty. */
  31259. (void)pDevice;
  31260. return MA_SUCCESS;
  31261. }
  31262. static ma_result ma_device_write__oss(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  31263. {
  31264. int resultOSS;
  31265. ma_uint32 deviceState;
  31266. if (pFramesWritten != NULL) {
  31267. *pFramesWritten = 0;
  31268. }
  31269. /* Don't do any processing if the device is stopped. */
  31270. deviceState = ma_device_get_state(pDevice);
  31271. if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) {
  31272. return MA_SUCCESS;
  31273. }
  31274. resultOSS = write(pDevice->oss.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  31275. if (resultOSS < 0) {
  31276. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device.");
  31277. return ma_result_from_errno(errno);
  31278. }
  31279. if (pFramesWritten != NULL) {
  31280. *pFramesWritten = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  31281. }
  31282. return MA_SUCCESS;
  31283. }
  31284. static ma_result ma_device_read__oss(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  31285. {
  31286. int resultOSS;
  31287. ma_uint32 deviceState;
  31288. if (pFramesRead != NULL) {
  31289. *pFramesRead = 0;
  31290. }
  31291. /* Don't do any processing if the device is stopped. */
  31292. deviceState = ma_device_get_state(pDevice);
  31293. if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) {
  31294. return MA_SUCCESS;
  31295. }
  31296. resultOSS = read(pDevice->oss.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  31297. if (resultOSS < 0) {
  31298. 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.");
  31299. return ma_result_from_errno(errno);
  31300. }
  31301. if (pFramesRead != NULL) {
  31302. *pFramesRead = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  31303. }
  31304. return MA_SUCCESS;
  31305. }
  31306. static ma_result ma_context_uninit__oss(ma_context* pContext)
  31307. {
  31308. MA_ASSERT(pContext != NULL);
  31309. MA_ASSERT(pContext->backend == ma_backend_oss);
  31310. (void)pContext;
  31311. return MA_SUCCESS;
  31312. }
  31313. static ma_result ma_context_init__oss(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  31314. {
  31315. int fd;
  31316. int ossVersion;
  31317. int result;
  31318. MA_ASSERT(pContext != NULL);
  31319. (void)pConfig;
  31320. /* Try opening a temporary device first so we can get version information. This is closed at the end. */
  31321. fd = ma_open_temp_device__oss();
  31322. if (fd == -1) {
  31323. 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. */
  31324. return MA_NO_BACKEND;
  31325. }
  31326. /* Grab the OSS version. */
  31327. ossVersion = 0;
  31328. result = ioctl(fd, OSS_GETVERSION, &ossVersion);
  31329. if (result == -1) {
  31330. close(fd);
  31331. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.");
  31332. return MA_NO_BACKEND;
  31333. }
  31334. /* The file handle to temp device is no longer needed. Close ASAP. */
  31335. close(fd);
  31336. pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16);
  31337. pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8);
  31338. pCallbacks->onContextInit = ma_context_init__oss;
  31339. pCallbacks->onContextUninit = ma_context_uninit__oss;
  31340. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__oss;
  31341. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__oss;
  31342. pCallbacks->onDeviceInit = ma_device_init__oss;
  31343. pCallbacks->onDeviceUninit = ma_device_uninit__oss;
  31344. pCallbacks->onDeviceStart = ma_device_start__oss;
  31345. pCallbacks->onDeviceStop = ma_device_stop__oss;
  31346. pCallbacks->onDeviceRead = ma_device_read__oss;
  31347. pCallbacks->onDeviceWrite = ma_device_write__oss;
  31348. pCallbacks->onDeviceDataLoop = NULL;
  31349. return MA_SUCCESS;
  31350. }
  31351. #endif /* OSS */
  31352. /******************************************************************************
  31353. AAudio Backend
  31354. ******************************************************************************/
  31355. #ifdef MA_HAS_AAUDIO
  31356. /*#include <AAudio/AAudio.h>*/
  31357. typedef int32_t ma_aaudio_result_t;
  31358. typedef int32_t ma_aaudio_direction_t;
  31359. typedef int32_t ma_aaudio_sharing_mode_t;
  31360. typedef int32_t ma_aaudio_format_t;
  31361. typedef int32_t ma_aaudio_stream_state_t;
  31362. typedef int32_t ma_aaudio_performance_mode_t;
  31363. typedef int32_t ma_aaudio_usage_t;
  31364. typedef int32_t ma_aaudio_content_type_t;
  31365. typedef int32_t ma_aaudio_input_preset_t;
  31366. typedef int32_t ma_aaudio_allowed_capture_policy_t;
  31367. typedef int32_t ma_aaudio_data_callback_result_t;
  31368. typedef struct ma_AAudioStreamBuilder_t* ma_AAudioStreamBuilder;
  31369. typedef struct ma_AAudioStream_t* ma_AAudioStream;
  31370. #define MA_AAUDIO_UNSPECIFIED 0
  31371. /* Result codes. miniaudio only cares about the success code. */
  31372. #define MA_AAUDIO_OK 0
  31373. /* Directions. */
  31374. #define MA_AAUDIO_DIRECTION_OUTPUT 0
  31375. #define MA_AAUDIO_DIRECTION_INPUT 1
  31376. /* Sharing modes. */
  31377. #define MA_AAUDIO_SHARING_MODE_EXCLUSIVE 0
  31378. #define MA_AAUDIO_SHARING_MODE_SHARED 1
  31379. /* Formats. */
  31380. #define MA_AAUDIO_FORMAT_PCM_I16 1
  31381. #define MA_AAUDIO_FORMAT_PCM_FLOAT 2
  31382. /* Stream states. */
  31383. #define MA_AAUDIO_STREAM_STATE_UNINITIALIZED 0
  31384. #define MA_AAUDIO_STREAM_STATE_UNKNOWN 1
  31385. #define MA_AAUDIO_STREAM_STATE_OPEN 2
  31386. #define MA_AAUDIO_STREAM_STATE_STARTING 3
  31387. #define MA_AAUDIO_STREAM_STATE_STARTED 4
  31388. #define MA_AAUDIO_STREAM_STATE_PAUSING 5
  31389. #define MA_AAUDIO_STREAM_STATE_PAUSED 6
  31390. #define MA_AAUDIO_STREAM_STATE_FLUSHING 7
  31391. #define MA_AAUDIO_STREAM_STATE_FLUSHED 8
  31392. #define MA_AAUDIO_STREAM_STATE_STOPPING 9
  31393. #define MA_AAUDIO_STREAM_STATE_STOPPED 10
  31394. #define MA_AAUDIO_STREAM_STATE_CLOSING 11
  31395. #define MA_AAUDIO_STREAM_STATE_CLOSED 12
  31396. #define MA_AAUDIO_STREAM_STATE_DISCONNECTED 13
  31397. /* Performance modes. */
  31398. #define MA_AAUDIO_PERFORMANCE_MODE_NONE 10
  31399. #define MA_AAUDIO_PERFORMANCE_MODE_POWER_SAVING 11
  31400. #define MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY 12
  31401. /* Usage types. */
  31402. #define MA_AAUDIO_USAGE_MEDIA 1
  31403. #define MA_AAUDIO_USAGE_VOICE_COMMUNICATION 2
  31404. #define MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING 3
  31405. #define MA_AAUDIO_USAGE_ALARM 4
  31406. #define MA_AAUDIO_USAGE_NOTIFICATION 5
  31407. #define MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE 6
  31408. #define MA_AAUDIO_USAGE_NOTIFICATION_EVENT 10
  31409. #define MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY 11
  31410. #define MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE 12
  31411. #define MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION 13
  31412. #define MA_AAUDIO_USAGE_GAME 14
  31413. #define MA_AAUDIO_USAGE_ASSISTANT 16
  31414. #define MA_AAUDIO_SYSTEM_USAGE_EMERGENCY 1000
  31415. #define MA_AAUDIO_SYSTEM_USAGE_SAFETY 1001
  31416. #define MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS 1002
  31417. #define MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT 1003
  31418. /* Content types. */
  31419. #define MA_AAUDIO_CONTENT_TYPE_SPEECH 1
  31420. #define MA_AAUDIO_CONTENT_TYPE_MUSIC 2
  31421. #define MA_AAUDIO_CONTENT_TYPE_MOVIE 3
  31422. #define MA_AAUDIO_CONTENT_TYPE_SONIFICATION 4
  31423. /* Input presets. */
  31424. #define MA_AAUDIO_INPUT_PRESET_GENERIC 1
  31425. #define MA_AAUDIO_INPUT_PRESET_CAMCORDER 5
  31426. #define MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION 6
  31427. #define MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION 7
  31428. #define MA_AAUDIO_INPUT_PRESET_UNPROCESSED 9
  31429. #define MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE 10
  31430. /* Allowed Capture Policies */
  31431. #define MA_AAUDIO_ALLOW_CAPTURE_BY_ALL 1
  31432. #define MA_AAUDIO_ALLOW_CAPTURE_BY_SYSTEM 2
  31433. #define MA_AAUDIO_ALLOW_CAPTURE_BY_NONE 3
  31434. /* Callback results. */
  31435. #define MA_AAUDIO_CALLBACK_RESULT_CONTINUE 0
  31436. #define MA_AAUDIO_CALLBACK_RESULT_STOP 1
  31437. typedef ma_aaudio_data_callback_result_t (* ma_AAudioStream_dataCallback) (ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t numFrames);
  31438. typedef void (* ma_AAudioStream_errorCallback)(ma_AAudioStream *pStream, void *pUserData, ma_aaudio_result_t error);
  31439. typedef ma_aaudio_result_t (* MA_PFN_AAudio_createStreamBuilder) (ma_AAudioStreamBuilder** ppBuilder);
  31440. typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_delete) (ma_AAudioStreamBuilder* pBuilder);
  31441. typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId);
  31442. typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction);
  31443. typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode);
  31444. typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format);
  31445. typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount);
  31446. typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate);
  31447. typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
  31448. typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
  31449. typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData);
  31450. typedef void (* MA_PFN_AAudioStreamBuilder_setErrorCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_errorCallback callback, void* pUserData);
  31451. typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode);
  31452. typedef void (* MA_PFN_AAudioStreamBuilder_setUsage) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_usage_t contentType);
  31453. typedef void (* MA_PFN_AAudioStreamBuilder_setContentType) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_content_type_t contentType);
  31454. typedef void (* MA_PFN_AAudioStreamBuilder_setInputPreset) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_input_preset_t inputPreset);
  31455. typedef void (* MA_PFN_AAudioStreamBuilder_setAllowedCapturePolicy) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_allowed_capture_policy_t policy);
  31456. typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_openStream) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream);
  31457. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_close) (ma_AAudioStream* pStream);
  31458. typedef ma_aaudio_stream_state_t (* MA_PFN_AAudioStream_getState) (ma_AAudioStream* pStream);
  31459. 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);
  31460. typedef ma_aaudio_format_t (* MA_PFN_AAudioStream_getFormat) (ma_AAudioStream* pStream);
  31461. typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream);
  31462. typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream);
  31463. typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream);
  31464. typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream);
  31465. typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream);
  31466. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStart) (ma_AAudioStream* pStream);
  31467. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStop) (ma_AAudioStream* pStream);
  31468. static ma_result ma_result_from_aaudio(ma_aaudio_result_t resultAA)
  31469. {
  31470. switch (resultAA)
  31471. {
  31472. case MA_AAUDIO_OK: return MA_SUCCESS;
  31473. default: break;
  31474. }
  31475. return MA_ERROR;
  31476. }
  31477. static ma_aaudio_usage_t ma_to_usage__aaudio(ma_aaudio_usage usage)
  31478. {
  31479. switch (usage) {
  31480. case ma_aaudio_usage_media: return MA_AAUDIO_USAGE_MEDIA;
  31481. case ma_aaudio_usage_voice_communication: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION;
  31482. case ma_aaudio_usage_voice_communication_signalling: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
  31483. case ma_aaudio_usage_alarm: return MA_AAUDIO_USAGE_ALARM;
  31484. case ma_aaudio_usage_notification: return MA_AAUDIO_USAGE_NOTIFICATION;
  31485. case ma_aaudio_usage_notification_ringtone: return MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE;
  31486. case ma_aaudio_usage_notification_event: return MA_AAUDIO_USAGE_NOTIFICATION_EVENT;
  31487. case ma_aaudio_usage_assistance_accessibility: return MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
  31488. case ma_aaudio_usage_assistance_navigation_guidance: return MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE;
  31489. case ma_aaudio_usage_assistance_sonification: return MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION;
  31490. case ma_aaudio_usage_game: return MA_AAUDIO_USAGE_GAME;
  31491. case ma_aaudio_usage_assitant: return MA_AAUDIO_USAGE_ASSISTANT;
  31492. case ma_aaudio_usage_emergency: return MA_AAUDIO_SYSTEM_USAGE_EMERGENCY;
  31493. case ma_aaudio_usage_safety: return MA_AAUDIO_SYSTEM_USAGE_SAFETY;
  31494. case ma_aaudio_usage_vehicle_status: return MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS;
  31495. case ma_aaudio_usage_announcement: return MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT;
  31496. default: break;
  31497. }
  31498. return MA_AAUDIO_USAGE_MEDIA;
  31499. }
  31500. static ma_aaudio_content_type_t ma_to_content_type__aaudio(ma_aaudio_content_type contentType)
  31501. {
  31502. switch (contentType) {
  31503. case ma_aaudio_content_type_speech: return MA_AAUDIO_CONTENT_TYPE_SPEECH;
  31504. case ma_aaudio_content_type_music: return MA_AAUDIO_CONTENT_TYPE_MUSIC;
  31505. case ma_aaudio_content_type_movie: return MA_AAUDIO_CONTENT_TYPE_MOVIE;
  31506. case ma_aaudio_content_type_sonification: return MA_AAUDIO_CONTENT_TYPE_SONIFICATION;
  31507. default: break;
  31508. }
  31509. return MA_AAUDIO_CONTENT_TYPE_SPEECH;
  31510. }
  31511. static ma_aaudio_input_preset_t ma_to_input_preset__aaudio(ma_aaudio_input_preset inputPreset)
  31512. {
  31513. switch (inputPreset) {
  31514. case ma_aaudio_input_preset_generic: return MA_AAUDIO_INPUT_PRESET_GENERIC;
  31515. case ma_aaudio_input_preset_camcorder: return MA_AAUDIO_INPUT_PRESET_CAMCORDER;
  31516. case ma_aaudio_input_preset_voice_recognition: return MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION;
  31517. case ma_aaudio_input_preset_voice_communication: return MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION;
  31518. case ma_aaudio_input_preset_unprocessed: return MA_AAUDIO_INPUT_PRESET_UNPROCESSED;
  31519. case ma_aaudio_input_preset_voice_performance: return MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE;
  31520. default: break;
  31521. }
  31522. return MA_AAUDIO_INPUT_PRESET_GENERIC;
  31523. }
  31524. static ma_aaudio_allowed_capture_policy_t ma_to_allowed_capture_policy__aaudio(ma_aaudio_allowed_capture_policy allowedCapturePolicy)
  31525. {
  31526. switch (allowedCapturePolicy) {
  31527. case ma_aaudio_allow_capture_by_all: return MA_AAUDIO_ALLOW_CAPTURE_BY_ALL;
  31528. case ma_aaudio_allow_capture_by_system: return MA_AAUDIO_ALLOW_CAPTURE_BY_SYSTEM;
  31529. case ma_aaudio_allow_capture_by_none: return MA_AAUDIO_ALLOW_CAPTURE_BY_NONE;
  31530. default: break;
  31531. }
  31532. return MA_AAUDIO_ALLOW_CAPTURE_BY_ALL;
  31533. }
  31534. static void ma_stream_error_callback__aaudio(ma_AAudioStream* pStream, void* pUserData, ma_aaudio_result_t error)
  31535. {
  31536. ma_result result;
  31537. ma_job job;
  31538. ma_device* pDevice = (ma_device*)pUserData;
  31539. MA_ASSERT(pDevice != NULL);
  31540. (void)error;
  31541. 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));
  31542. /*
  31543. When we get an error, we'll assume that the stream is in an erroneous state and needs to be restarted. From the documentation,
  31544. we cannot do this from the error callback. Therefore we are going to use an event thread for the AAudio backend to do this
  31545. cleanly and safely.
  31546. */
  31547. job = ma_job_init(MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE);
  31548. job.data.device.aaudio.reroute.pDevice = pDevice;
  31549. if (pStream == pDevice->aaudio.pStreamCapture) {
  31550. job.data.device.aaudio.reroute.deviceType = ma_device_type_capture;
  31551. }
  31552. else {
  31553. job.data.device.aaudio.reroute.deviceType = ma_device_type_playback;
  31554. }
  31555. result = ma_device_job_thread_post(&pDevice->pContext->aaudio.jobThread, &job);
  31556. if (result != MA_SUCCESS) {
  31557. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[AAudio] Device Disconnected. Failed to post job for rerouting.\n");
  31558. return;
  31559. }
  31560. }
  31561. static ma_aaudio_data_callback_result_t ma_stream_data_callback_capture__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
  31562. {
  31563. ma_device* pDevice = (ma_device*)pUserData;
  31564. MA_ASSERT(pDevice != NULL);
  31565. ma_device_handle_backend_data_callback(pDevice, NULL, pAudioData, frameCount);
  31566. (void)pStream;
  31567. return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
  31568. }
  31569. static ma_aaudio_data_callback_result_t ma_stream_data_callback_playback__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
  31570. {
  31571. ma_device* pDevice = (ma_device*)pUserData;
  31572. MA_ASSERT(pDevice != NULL);
  31573. ma_device_handle_backend_data_callback(pDevice, pAudioData, NULL, frameCount);
  31574. (void)pStream;
  31575. return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
  31576. }
  31577. 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)
  31578. {
  31579. ma_AAudioStreamBuilder* pBuilder;
  31580. ma_aaudio_result_t resultAA;
  31581. /* Safety. */
  31582. *ppBuilder = NULL;
  31583. resultAA = ((MA_PFN_AAudio_createStreamBuilder)pContext->aaudio.AAudio_createStreamBuilder)(&pBuilder);
  31584. if (resultAA != MA_AAUDIO_OK) {
  31585. return ma_result_from_aaudio(resultAA);
  31586. }
  31587. if (pDeviceID != NULL) {
  31588. ((MA_PFN_AAudioStreamBuilder_setDeviceId)pContext->aaudio.AAudioStreamBuilder_setDeviceId)(pBuilder, pDeviceID->aaudio);
  31589. }
  31590. ((MA_PFN_AAudioStreamBuilder_setDirection)pContext->aaudio.AAudioStreamBuilder_setDirection)(pBuilder, (deviceType == ma_device_type_playback) ? MA_AAUDIO_DIRECTION_OUTPUT : MA_AAUDIO_DIRECTION_INPUT);
  31591. ((MA_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == ma_share_mode_shared) ? MA_AAUDIO_SHARING_MODE_SHARED : MA_AAUDIO_SHARING_MODE_EXCLUSIVE);
  31592. /* If we have a device descriptor make sure we configure the stream builder to take our requested parameters. */
  31593. if (pDescriptor != NULL) {
  31594. 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. */
  31595. if (pDescriptor->sampleRate != 0) {
  31596. ((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pDescriptor->sampleRate);
  31597. }
  31598. if (deviceType == ma_device_type_capture) {
  31599. if (pDescriptor->channels != 0) {
  31600. ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels);
  31601. }
  31602. if (pDescriptor->format != ma_format_unknown) {
  31603. ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
  31604. }
  31605. } else {
  31606. if (pDescriptor->channels != 0) {
  31607. ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels);
  31608. }
  31609. if (pDescriptor->format != ma_format_unknown) {
  31610. ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
  31611. }
  31612. }
  31613. /*
  31614. There have been reports where setting the frames per data callback results in an error
  31615. later on from Android. To address this, I'm experimenting with simply not setting it on
  31616. anything from Android 11 and earlier. Suggestions welcome on how we might be able to make
  31617. this more targetted.
  31618. */
  31619. if (!pConfig->aaudio.enableCompatibilityWorkarounds || ma_android_sdk_version() > 30) {
  31620. /*
  31621. AAudio is annoying when it comes to it's buffer calculation stuff because it doesn't let you
  31622. retrieve the actual sample rate until after you've opened the stream. But you need to configure
  31623. the buffer capacity before you open the stream... :/
  31624. To solve, we're just going to assume MA_DEFAULT_SAMPLE_RATE (48000) and move on.
  31625. */
  31626. ma_uint32 bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, pDescriptor->sampleRate, pConfig->performanceProfile) * pDescriptor->periodCount;
  31627. ((MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, bufferCapacityInFrames);
  31628. ((MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, bufferCapacityInFrames / pDescriptor->periodCount);
  31629. }
  31630. if (deviceType == ma_device_type_capture) {
  31631. if (pConfig->aaudio.inputPreset != ma_aaudio_input_preset_default && pContext->aaudio.AAudioStreamBuilder_setInputPreset != NULL) {
  31632. ((MA_PFN_AAudioStreamBuilder_setInputPreset)pContext->aaudio.AAudioStreamBuilder_setInputPreset)(pBuilder, ma_to_input_preset__aaudio(pConfig->aaudio.inputPreset));
  31633. }
  31634. ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_capture__aaudio, (void*)pDevice);
  31635. } else {
  31636. if (pConfig->aaudio.usage != ma_aaudio_usage_default && pContext->aaudio.AAudioStreamBuilder_setUsage != NULL) {
  31637. ((MA_PFN_AAudioStreamBuilder_setUsage)pContext->aaudio.AAudioStreamBuilder_setUsage)(pBuilder, ma_to_usage__aaudio(pConfig->aaudio.usage));
  31638. }
  31639. if (pConfig->aaudio.contentType != ma_aaudio_content_type_default && pContext->aaudio.AAudioStreamBuilder_setContentType != NULL) {
  31640. ((MA_PFN_AAudioStreamBuilder_setContentType)pContext->aaudio.AAudioStreamBuilder_setContentType)(pBuilder, ma_to_content_type__aaudio(pConfig->aaudio.contentType));
  31641. }
  31642. if (pConfig->aaudio.allowedCapturePolicy != ma_aaudio_allow_capture_default && pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy != NULL) {
  31643. ((MA_PFN_AAudioStreamBuilder_setAllowedCapturePolicy)pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy)(pBuilder, ma_to_allowed_capture_policy__aaudio(pConfig->aaudio.allowedCapturePolicy));
  31644. }
  31645. ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_playback__aaudio, (void*)pDevice);
  31646. }
  31647. /* 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. */
  31648. ((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);
  31649. /* We need to set an error callback to detect device changes. */
  31650. 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. */
  31651. ((MA_PFN_AAudioStreamBuilder_setErrorCallback)pContext->aaudio.AAudioStreamBuilder_setErrorCallback)(pBuilder, ma_stream_error_callback__aaudio, (void*)pDevice);
  31652. }
  31653. }
  31654. *ppBuilder = pBuilder;
  31655. return MA_SUCCESS;
  31656. }
  31657. static ma_result ma_open_stream_and_close_builder__aaudio(ma_context* pContext, ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream)
  31658. {
  31659. ma_result result;
  31660. result = ma_result_from_aaudio(((MA_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream));
  31661. ((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder);
  31662. return result;
  31663. }
  31664. 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)
  31665. {
  31666. ma_result result;
  31667. ma_AAudioStreamBuilder* pBuilder;
  31668. *ppStream = NULL;
  31669. result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pContext, pDeviceID, deviceType, shareMode, NULL, NULL, NULL, &pBuilder);
  31670. if (result != MA_SUCCESS) {
  31671. return result;
  31672. }
  31673. return ma_open_stream_and_close_builder__aaudio(pContext, pBuilder, ppStream);
  31674. }
  31675. 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)
  31676. {
  31677. ma_result result;
  31678. ma_AAudioStreamBuilder* pBuilder;
  31679. MA_ASSERT(pDevice != NULL);
  31680. MA_ASSERT(pDescriptor != NULL);
  31681. MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should not be called for a full-duplex device type. */
  31682. *ppStream = NULL;
  31683. result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pDevice->pContext, pDescriptor->pDeviceID, deviceType, pDescriptor->shareMode, pDescriptor, pConfig, pDevice, &pBuilder);
  31684. if (result != MA_SUCCESS) {
  31685. return result;
  31686. }
  31687. return ma_open_stream_and_close_builder__aaudio(pDevice->pContext, pBuilder, ppStream);
  31688. }
  31689. static ma_result ma_close_stream__aaudio(ma_context* pContext, ma_AAudioStream* pStream)
  31690. {
  31691. return ma_result_from_aaudio(((MA_PFN_AAudioStream_close)pContext->aaudio.AAudioStream_close)(pStream));
  31692. }
  31693. static ma_bool32 ma_has_default_device__aaudio(ma_context* pContext, ma_device_type deviceType)
  31694. {
  31695. /* The only way to know this is to try creating a stream. */
  31696. ma_AAudioStream* pStream;
  31697. ma_result result = ma_open_stream_basic__aaudio(pContext, NULL, deviceType, ma_share_mode_shared, &pStream);
  31698. if (result != MA_SUCCESS) {
  31699. return MA_FALSE;
  31700. }
  31701. ma_close_stream__aaudio(pContext, pStream);
  31702. return MA_TRUE;
  31703. }
  31704. 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)
  31705. {
  31706. ma_aaudio_stream_state_t actualNewState;
  31707. ma_aaudio_result_t resultAA = ((MA_PFN_AAudioStream_waitForStateChange)pContext->aaudio.AAudioStream_waitForStateChange)(pStream, oldState, &actualNewState, 5000000000); /* 5 second timeout. */
  31708. if (resultAA != MA_AAUDIO_OK) {
  31709. return ma_result_from_aaudio(resultAA);
  31710. }
  31711. if (newState != actualNewState) {
  31712. return MA_ERROR; /* Failed to transition into the expected state. */
  31713. }
  31714. return MA_SUCCESS;
  31715. }
  31716. static ma_result ma_context_enumerate_devices__aaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  31717. {
  31718. ma_bool32 cbResult = MA_TRUE;
  31719. MA_ASSERT(pContext != NULL);
  31720. MA_ASSERT(callback != NULL);
  31721. /* 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. */
  31722. /* Playback. */
  31723. if (cbResult) {
  31724. ma_device_info deviceInfo;
  31725. MA_ZERO_OBJECT(&deviceInfo);
  31726. deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED;
  31727. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  31728. if (ma_has_default_device__aaudio(pContext, ma_device_type_playback)) {
  31729. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  31730. }
  31731. }
  31732. /* Capture. */
  31733. if (cbResult) {
  31734. ma_device_info deviceInfo;
  31735. MA_ZERO_OBJECT(&deviceInfo);
  31736. deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED;
  31737. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  31738. if (ma_has_default_device__aaudio(pContext, ma_device_type_capture)) {
  31739. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  31740. }
  31741. }
  31742. return MA_SUCCESS;
  31743. }
  31744. 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)
  31745. {
  31746. MA_ASSERT(pContext != NULL);
  31747. MA_ASSERT(pStream != NULL);
  31748. MA_ASSERT(pDeviceInfo != NULL);
  31749. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  31750. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream);
  31751. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream);
  31752. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  31753. pDeviceInfo->nativeDataFormatCount += 1;
  31754. }
  31755. static void ma_context_add_native_data_format_from_AAudioStream__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_uint32 flags, ma_device_info* pDeviceInfo)
  31756. {
  31757. /* AAudio supports s16 and f32. */
  31758. ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_f32, flags, pDeviceInfo);
  31759. ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_s16, flags, pDeviceInfo);
  31760. }
  31761. 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)
  31762. {
  31763. ma_AAudioStream* pStream;
  31764. ma_result result;
  31765. MA_ASSERT(pContext != NULL);
  31766. /* ID */
  31767. if (pDeviceID != NULL) {
  31768. pDeviceInfo->id.aaudio = pDeviceID->aaudio;
  31769. } else {
  31770. pDeviceInfo->id.aaudio = MA_AAUDIO_UNSPECIFIED;
  31771. }
  31772. /* Name */
  31773. if (deviceType == ma_device_type_playback) {
  31774. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  31775. } else {
  31776. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  31777. }
  31778. pDeviceInfo->nativeDataFormatCount = 0;
  31779. /* We'll need to open the device to get accurate sample rate and channel count information. */
  31780. result = ma_open_stream_basic__aaudio(pContext, pDeviceID, deviceType, ma_share_mode_shared, &pStream);
  31781. if (result != MA_SUCCESS) {
  31782. return result;
  31783. }
  31784. ma_context_add_native_data_format_from_AAudioStream__aaudio(pContext, pStream, 0, pDeviceInfo);
  31785. ma_close_stream__aaudio(pContext, pStream);
  31786. pStream = NULL;
  31787. return MA_SUCCESS;
  31788. }
  31789. static ma_result ma_device_uninit__aaudio(ma_device* pDevice)
  31790. {
  31791. MA_ASSERT(pDevice != NULL);
  31792. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31793. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31794. pDevice->aaudio.pStreamCapture = NULL;
  31795. }
  31796. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31797. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31798. pDevice->aaudio.pStreamPlayback = NULL;
  31799. }
  31800. return MA_SUCCESS;
  31801. }
  31802. 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)
  31803. {
  31804. ma_result result;
  31805. int32_t bufferCapacityInFrames;
  31806. int32_t framesPerDataCallback;
  31807. ma_AAudioStream* pStream;
  31808. MA_ASSERT(pDevice != NULL);
  31809. MA_ASSERT(pConfig != NULL);
  31810. MA_ASSERT(pDescriptor != NULL);
  31811. *ppStream = NULL; /* Safety. */
  31812. /* First step is to open the stream. From there we'll be able to extract the internal configuration. */
  31813. result = ma_open_stream__aaudio(pDevice, pConfig, deviceType, pDescriptor, &pStream);
  31814. if (result != MA_SUCCESS) {
  31815. return result; /* Failed to open the AAudio stream. */
  31816. }
  31817. /* Now extract the internal configuration. */
  31818. pDescriptor->format = (((MA_PFN_AAudioStream_getFormat)pDevice->pContext->aaudio.AAudioStream_getFormat)(pStream) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32;
  31819. pDescriptor->channels = ((MA_PFN_AAudioStream_getChannelCount)pDevice->pContext->aaudio.AAudioStream_getChannelCount)(pStream);
  31820. pDescriptor->sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pDevice->pContext->aaudio.AAudioStream_getSampleRate)(pStream);
  31821. /* For the channel map we need to be sure we don't overflow any buffers. */
  31822. if (pDescriptor->channels <= MA_MAX_CHANNELS) {
  31823. 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. */
  31824. } else {
  31825. ma_channel_map_init_blank(pDescriptor->channelMap, MA_MAX_CHANNELS); /* Too many channels. Use a blank channel map. */
  31826. }
  31827. bufferCapacityInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pDevice->pContext->aaudio.AAudioStream_getBufferCapacityInFrames)(pStream);
  31828. framesPerDataCallback = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pDevice->pContext->aaudio.AAudioStream_getFramesPerDataCallback)(pStream);
  31829. if (framesPerDataCallback > 0) {
  31830. pDescriptor->periodSizeInFrames = framesPerDataCallback;
  31831. pDescriptor->periodCount = bufferCapacityInFrames / framesPerDataCallback;
  31832. } else {
  31833. pDescriptor->periodSizeInFrames = bufferCapacityInFrames;
  31834. pDescriptor->periodCount = 1;
  31835. }
  31836. *ppStream = pStream;
  31837. return MA_SUCCESS;
  31838. }
  31839. static ma_result ma_device_init__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  31840. {
  31841. ma_result result;
  31842. MA_ASSERT(pDevice != NULL);
  31843. if (pConfig->deviceType == ma_device_type_loopback) {
  31844. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  31845. }
  31846. pDevice->aaudio.usage = pConfig->aaudio.usage;
  31847. pDevice->aaudio.contentType = pConfig->aaudio.contentType;
  31848. pDevice->aaudio.inputPreset = pConfig->aaudio.inputPreset;
  31849. pDevice->aaudio.allowedCapturePolicy = pConfig->aaudio.allowedCapturePolicy;
  31850. pDevice->aaudio.noAutoStartAfterReroute = pConfig->aaudio.noAutoStartAfterReroute;
  31851. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  31852. result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_capture, pDescriptorCapture, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture);
  31853. if (result != MA_SUCCESS) {
  31854. return result;
  31855. }
  31856. }
  31857. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  31858. result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_playback, pDescriptorPlayback, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback);
  31859. if (result != MA_SUCCESS) {
  31860. return result;
  31861. }
  31862. }
  31863. return MA_SUCCESS;
  31864. }
  31865. static ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
  31866. {
  31867. ma_aaudio_result_t resultAA;
  31868. ma_aaudio_stream_state_t currentState;
  31869. MA_ASSERT(pDevice != NULL);
  31870. resultAA = ((MA_PFN_AAudioStream_requestStart)pDevice->pContext->aaudio.AAudioStream_requestStart)(pStream);
  31871. if (resultAA != MA_AAUDIO_OK) {
  31872. return ma_result_from_aaudio(resultAA);
  31873. }
  31874. /* Do we actually need to wait for the device to transition into it's started state? */
  31875. /* 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. */
  31876. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  31877. if (currentState != MA_AAUDIO_STREAM_STATE_STARTED) {
  31878. ma_result result;
  31879. if (currentState != MA_AAUDIO_STREAM_STATE_STARTING) {
  31880. return MA_ERROR; /* Expecting the stream to be a starting or started state. */
  31881. }
  31882. result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STARTED);
  31883. if (result != MA_SUCCESS) {
  31884. return result;
  31885. }
  31886. }
  31887. return MA_SUCCESS;
  31888. }
  31889. static ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
  31890. {
  31891. ma_aaudio_result_t resultAA;
  31892. ma_aaudio_stream_state_t currentState;
  31893. MA_ASSERT(pDevice != NULL);
  31894. /*
  31895. From the AAudio documentation:
  31896. The stream will stop after all of the data currently buffered has been played.
  31897. This maps with miniaudio's requirement that device's be drained which means we don't need to implement any draining logic.
  31898. */
  31899. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  31900. if (currentState == MA_AAUDIO_STREAM_STATE_DISCONNECTED) {
  31901. return MA_SUCCESS; /* The device is disconnected. Don't try stopping it. */
  31902. }
  31903. resultAA = ((MA_PFN_AAudioStream_requestStop)pDevice->pContext->aaudio.AAudioStream_requestStop)(pStream);
  31904. if (resultAA != MA_AAUDIO_OK) {
  31905. return ma_result_from_aaudio(resultAA);
  31906. }
  31907. /* 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. */
  31908. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  31909. if (currentState != MA_AAUDIO_STREAM_STATE_STOPPED) {
  31910. ma_result result;
  31911. if (currentState != MA_AAUDIO_STREAM_STATE_STOPPING) {
  31912. return MA_ERROR; /* Expecting the stream to be a stopping or stopped state. */
  31913. }
  31914. result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STOPPED);
  31915. if (result != MA_SUCCESS) {
  31916. return result;
  31917. }
  31918. }
  31919. return MA_SUCCESS;
  31920. }
  31921. static ma_result ma_device_start__aaudio(ma_device* pDevice)
  31922. {
  31923. MA_ASSERT(pDevice != NULL);
  31924. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31925. ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31926. if (result != MA_SUCCESS) {
  31927. return result;
  31928. }
  31929. }
  31930. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31931. ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31932. if (result != MA_SUCCESS) {
  31933. if (pDevice->type == ma_device_type_duplex) {
  31934. ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31935. }
  31936. return result;
  31937. }
  31938. }
  31939. return MA_SUCCESS;
  31940. }
  31941. static ma_result ma_device_stop__aaudio(ma_device* pDevice)
  31942. {
  31943. MA_ASSERT(pDevice != NULL);
  31944. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31945. ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31946. if (result != MA_SUCCESS) {
  31947. return result;
  31948. }
  31949. }
  31950. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31951. ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31952. if (result != MA_SUCCESS) {
  31953. return result;
  31954. }
  31955. }
  31956. ma_device__on_notification_stopped(pDevice);
  31957. return MA_SUCCESS;
  31958. }
  31959. static ma_result ma_device_reinit__aaudio(ma_device* pDevice, ma_device_type deviceType)
  31960. {
  31961. ma_result result;
  31962. MA_ASSERT(pDevice != NULL);
  31963. /* The first thing to do is close the streams. */
  31964. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) {
  31965. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  31966. pDevice->aaudio.pStreamCapture = NULL;
  31967. }
  31968. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31969. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  31970. pDevice->aaudio.pStreamPlayback = NULL;
  31971. }
  31972. /* Now we need to reinitialize each streams. The hardest part with this is just filling output the config and descriptors. */
  31973. {
  31974. ma_device_config deviceConfig;
  31975. ma_device_descriptor descriptorPlayback;
  31976. ma_device_descriptor descriptorCapture;
  31977. deviceConfig = ma_device_config_init(deviceType);
  31978. deviceConfig.playback.pDeviceID = NULL; /* Only doing rerouting with default devices. */
  31979. deviceConfig.playback.shareMode = pDevice->playback.shareMode;
  31980. deviceConfig.playback.format = pDevice->playback.format;
  31981. deviceConfig.playback.channels = pDevice->playback.channels;
  31982. deviceConfig.capture.pDeviceID = NULL; /* Only doing rerouting with default devices. */
  31983. deviceConfig.capture.shareMode = pDevice->capture.shareMode;
  31984. deviceConfig.capture.format = pDevice->capture.format;
  31985. deviceConfig.capture.channels = pDevice->capture.channels;
  31986. deviceConfig.sampleRate = pDevice->sampleRate;
  31987. deviceConfig.aaudio.usage = pDevice->aaudio.usage;
  31988. deviceConfig.aaudio.contentType = pDevice->aaudio.contentType;
  31989. deviceConfig.aaudio.inputPreset = pDevice->aaudio.inputPreset;
  31990. deviceConfig.aaudio.allowedCapturePolicy = pDevice->aaudio.allowedCapturePolicy;
  31991. deviceConfig.aaudio.noAutoStartAfterReroute = pDevice->aaudio.noAutoStartAfterReroute;
  31992. deviceConfig.periods = 1;
  31993. /* Try to get an accurate period size. */
  31994. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31995. deviceConfig.periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
  31996. } else {
  31997. deviceConfig.periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
  31998. }
  31999. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  32000. descriptorCapture.pDeviceID = deviceConfig.capture.pDeviceID;
  32001. descriptorCapture.shareMode = deviceConfig.capture.shareMode;
  32002. descriptorCapture.format = deviceConfig.capture.format;
  32003. descriptorCapture.channels = deviceConfig.capture.channels;
  32004. descriptorCapture.sampleRate = deviceConfig.sampleRate;
  32005. descriptorCapture.periodSizeInFrames = deviceConfig.periodSizeInFrames;
  32006. descriptorCapture.periodCount = deviceConfig.periods;
  32007. }
  32008. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  32009. descriptorPlayback.pDeviceID = deviceConfig.playback.pDeviceID;
  32010. descriptorPlayback.shareMode = deviceConfig.playback.shareMode;
  32011. descriptorPlayback.format = deviceConfig.playback.format;
  32012. descriptorPlayback.channels = deviceConfig.playback.channels;
  32013. descriptorPlayback.sampleRate = deviceConfig.sampleRate;
  32014. descriptorPlayback.periodSizeInFrames = deviceConfig.periodSizeInFrames;
  32015. descriptorPlayback.periodCount = deviceConfig.periods;
  32016. }
  32017. result = ma_device_init__aaudio(pDevice, &deviceConfig, &descriptorPlayback, &descriptorCapture);
  32018. if (result != MA_SUCCESS) {
  32019. return result;
  32020. }
  32021. result = ma_device_post_init(pDevice, deviceType, &descriptorPlayback, &descriptorCapture);
  32022. if (result != MA_SUCCESS) {
  32023. ma_device_uninit__aaudio(pDevice);
  32024. return result;
  32025. }
  32026. /* We'll only ever do this in response to a reroute. */
  32027. ma_device__on_notification_rerouted(pDevice);
  32028. /* If the device is started, start the streams. Maybe make this configurable? */
  32029. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  32030. if (pDevice->aaudio.noAutoStartAfterReroute == MA_FALSE) {
  32031. ma_device_start__aaudio(pDevice);
  32032. } else {
  32033. ma_device_stop(pDevice); /* Do a full device stop so we set internal state correctly. */
  32034. }
  32035. }
  32036. return MA_SUCCESS;
  32037. }
  32038. }
  32039. static ma_result ma_device_get_info__aaudio(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo)
  32040. {
  32041. ma_AAudioStream* pStream = NULL;
  32042. MA_ASSERT(pDevice != NULL);
  32043. MA_ASSERT(type != ma_device_type_duplex);
  32044. MA_ASSERT(pDeviceInfo != NULL);
  32045. if (type == ma_device_type_playback) {
  32046. pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamCapture;
  32047. pDeviceInfo->id.aaudio = pDevice->capture.id.aaudio;
  32048. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */
  32049. }
  32050. if (type == ma_device_type_capture) {
  32051. pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback;
  32052. pDeviceInfo->id.aaudio = pDevice->playback.id.aaudio;
  32053. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */
  32054. }
  32055. /* Safety. Should never happen. */
  32056. if (pStream == NULL) {
  32057. return MA_INVALID_OPERATION;
  32058. }
  32059. pDeviceInfo->nativeDataFormatCount = 0;
  32060. ma_context_add_native_data_format_from_AAudioStream__aaudio(pDevice->pContext, pStream, 0, pDeviceInfo);
  32061. return MA_SUCCESS;
  32062. }
  32063. static ma_result ma_context_uninit__aaudio(ma_context* pContext)
  32064. {
  32065. MA_ASSERT(pContext != NULL);
  32066. MA_ASSERT(pContext->backend == ma_backend_aaudio);
  32067. ma_device_job_thread_uninit(&pContext->aaudio.jobThread, &pContext->allocationCallbacks);
  32068. ma_dlclose(ma_context_get_log(pContext), pContext->aaudio.hAAudio);
  32069. pContext->aaudio.hAAudio = NULL;
  32070. return MA_SUCCESS;
  32071. }
  32072. static ma_result ma_context_init__aaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  32073. {
  32074. size_t i;
  32075. const char* libNames[] = {
  32076. "libaaudio.so"
  32077. };
  32078. for (i = 0; i < ma_countof(libNames); ++i) {
  32079. pContext->aaudio.hAAudio = ma_dlopen(ma_context_get_log(pContext), libNames[i]);
  32080. if (pContext->aaudio.hAAudio != NULL) {
  32081. break;
  32082. }
  32083. }
  32084. if (pContext->aaudio.hAAudio == NULL) {
  32085. return MA_FAILED_TO_INIT_BACKEND;
  32086. }
  32087. pContext->aaudio.AAudio_createStreamBuilder = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudio_createStreamBuilder");
  32088. pContext->aaudio.AAudioStreamBuilder_delete = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_delete");
  32089. pContext->aaudio.AAudioStreamBuilder_setDeviceId = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDeviceId");
  32090. pContext->aaudio.AAudioStreamBuilder_setDirection = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDirection");
  32091. pContext->aaudio.AAudioStreamBuilder_setSharingMode = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSharingMode");
  32092. pContext->aaudio.AAudioStreamBuilder_setFormat = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFormat");
  32093. pContext->aaudio.AAudioStreamBuilder_setChannelCount = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setChannelCount");
  32094. pContext->aaudio.AAudioStreamBuilder_setSampleRate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSampleRate");
  32095. pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setBufferCapacityInFrames");
  32096. pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFramesPerDataCallback");
  32097. pContext->aaudio.AAudioStreamBuilder_setDataCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDataCallback");
  32098. pContext->aaudio.AAudioStreamBuilder_setErrorCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setErrorCallback");
  32099. pContext->aaudio.AAudioStreamBuilder_setPerformanceMode = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setPerformanceMode");
  32100. pContext->aaudio.AAudioStreamBuilder_setUsage = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setUsage");
  32101. pContext->aaudio.AAudioStreamBuilder_setContentType = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setContentType");
  32102. pContext->aaudio.AAudioStreamBuilder_setInputPreset = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setInputPreset");
  32103. pContext->aaudio.AAudioStreamBuilder_setAllowedCapturePolicy = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_setAllowedCapturePolicy");
  32104. pContext->aaudio.AAudioStreamBuilder_openStream = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStreamBuilder_openStream");
  32105. pContext->aaudio.AAudioStream_close = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_close");
  32106. pContext->aaudio.AAudioStream_getState = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getState");
  32107. pContext->aaudio.AAudioStream_waitForStateChange = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_waitForStateChange");
  32108. pContext->aaudio.AAudioStream_getFormat = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getFormat");
  32109. pContext->aaudio.AAudioStream_getChannelCount = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getChannelCount");
  32110. pContext->aaudio.AAudioStream_getSampleRate = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getSampleRate");
  32111. pContext->aaudio.AAudioStream_getBufferCapacityInFrames = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getBufferCapacityInFrames");
  32112. pContext->aaudio.AAudioStream_getFramesPerDataCallback = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getFramesPerDataCallback");
  32113. pContext->aaudio.AAudioStream_getFramesPerBurst = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_getFramesPerBurst");
  32114. pContext->aaudio.AAudioStream_requestStart = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_requestStart");
  32115. pContext->aaudio.AAudioStream_requestStop = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->aaudio.hAAudio, "AAudioStream_requestStop");
  32116. pCallbacks->onContextInit = ma_context_init__aaudio;
  32117. pCallbacks->onContextUninit = ma_context_uninit__aaudio;
  32118. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__aaudio;
  32119. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__aaudio;
  32120. pCallbacks->onDeviceInit = ma_device_init__aaudio;
  32121. pCallbacks->onDeviceUninit = ma_device_uninit__aaudio;
  32122. pCallbacks->onDeviceStart = ma_device_start__aaudio;
  32123. pCallbacks->onDeviceStop = ma_device_stop__aaudio;
  32124. pCallbacks->onDeviceRead = NULL; /* Not used because AAudio is asynchronous. */
  32125. pCallbacks->onDeviceWrite = NULL; /* Not used because AAudio is asynchronous. */
  32126. pCallbacks->onDeviceDataLoop = NULL; /* Not used because AAudio is asynchronous. */
  32127. pCallbacks->onDeviceGetInfo = ma_device_get_info__aaudio;
  32128. /* We need a job thread so we can deal with rerouting. */
  32129. {
  32130. ma_result result;
  32131. ma_device_job_thread_config jobThreadConfig;
  32132. jobThreadConfig = ma_device_job_thread_config_init();
  32133. result = ma_device_job_thread_init(&jobThreadConfig, &pContext->allocationCallbacks, &pContext->aaudio.jobThread);
  32134. if (result != MA_SUCCESS) {
  32135. ma_dlclose(ma_context_get_log(pContext), pContext->aaudio.hAAudio);
  32136. pContext->aaudio.hAAudio = NULL;
  32137. return result;
  32138. }
  32139. }
  32140. (void)pConfig;
  32141. return MA_SUCCESS;
  32142. }
  32143. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob)
  32144. {
  32145. ma_device* pDevice;
  32146. MA_ASSERT(pJob != NULL);
  32147. pDevice = (ma_device*)pJob->data.device.aaudio.reroute.pDevice;
  32148. MA_ASSERT(pDevice != NULL);
  32149. /* Here is where we need to reroute the device. To do this we need to uninitialize the stream and reinitialize it. */
  32150. return ma_device_reinit__aaudio(pDevice, (ma_device_type)pJob->data.device.aaudio.reroute.deviceType);
  32151. }
  32152. #else
  32153. /* Getting here means there is no AAudio backend so we need a no-op job implementation. */
  32154. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob)
  32155. {
  32156. return ma_job_process__noop(pJob);
  32157. }
  32158. #endif /* AAudio */
  32159. /******************************************************************************
  32160. OpenSL|ES Backend
  32161. ******************************************************************************/
  32162. #ifdef MA_HAS_OPENSL
  32163. #include <SLES/OpenSLES.h>
  32164. #ifdef MA_ANDROID
  32165. #include <SLES/OpenSLES_Android.h>
  32166. #endif
  32167. typedef SLresult (SLAPIENTRY * ma_slCreateEngine_proc)(SLObjectItf* pEngine, SLuint32 numOptions, SLEngineOption* pEngineOptions, SLuint32 numInterfaces, SLInterfaceID* pInterfaceIds, SLboolean* pInterfaceRequired);
  32168. /* OpenSL|ES has one-per-application objects :( */
  32169. static SLObjectItf g_maEngineObjectSL = NULL;
  32170. static SLEngineItf g_maEngineSL = NULL;
  32171. static ma_uint32 g_maOpenSLInitCounter = 0;
  32172. static ma_spinlock g_maOpenSLSpinlock = 0; /* For init/uninit. */
  32173. #define MA_OPENSL_OBJ(p) (*((SLObjectItf)(p)))
  32174. #define MA_OPENSL_OUTPUTMIX(p) (*((SLOutputMixItf)(p)))
  32175. #define MA_OPENSL_PLAY(p) (*((SLPlayItf)(p)))
  32176. #define MA_OPENSL_RECORD(p) (*((SLRecordItf)(p)))
  32177. #ifdef MA_ANDROID
  32178. #define MA_OPENSL_BUFFERQUEUE(p) (*((SLAndroidSimpleBufferQueueItf)(p)))
  32179. #else
  32180. #define MA_OPENSL_BUFFERQUEUE(p) (*((SLBufferQueueItf)(p)))
  32181. #endif
  32182. static ma_result ma_result_from_OpenSL(SLuint32 result)
  32183. {
  32184. switch (result)
  32185. {
  32186. case SL_RESULT_SUCCESS: return MA_SUCCESS;
  32187. case SL_RESULT_PRECONDITIONS_VIOLATED: return MA_ERROR;
  32188. case SL_RESULT_PARAMETER_INVALID: return MA_INVALID_ARGS;
  32189. case SL_RESULT_MEMORY_FAILURE: return MA_OUT_OF_MEMORY;
  32190. case SL_RESULT_RESOURCE_ERROR: return MA_INVALID_DATA;
  32191. case SL_RESULT_RESOURCE_LOST: return MA_ERROR;
  32192. case SL_RESULT_IO_ERROR: return MA_IO_ERROR;
  32193. case SL_RESULT_BUFFER_INSUFFICIENT: return MA_NO_SPACE;
  32194. case SL_RESULT_CONTENT_CORRUPTED: return MA_INVALID_DATA;
  32195. case SL_RESULT_CONTENT_UNSUPPORTED: return MA_FORMAT_NOT_SUPPORTED;
  32196. case SL_RESULT_CONTENT_NOT_FOUND: return MA_ERROR;
  32197. case SL_RESULT_PERMISSION_DENIED: return MA_ACCESS_DENIED;
  32198. case SL_RESULT_FEATURE_UNSUPPORTED: return MA_NOT_IMPLEMENTED;
  32199. case SL_RESULT_INTERNAL_ERROR: return MA_ERROR;
  32200. case SL_RESULT_UNKNOWN_ERROR: return MA_ERROR;
  32201. case SL_RESULT_OPERATION_ABORTED: return MA_ERROR;
  32202. case SL_RESULT_CONTROL_LOST: return MA_ERROR;
  32203. default: return MA_ERROR;
  32204. }
  32205. }
  32206. /* Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
  32207. static ma_uint8 ma_channel_id_to_ma__opensl(SLuint32 id)
  32208. {
  32209. switch (id)
  32210. {
  32211. case SL_SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  32212. case SL_SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  32213. case SL_SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  32214. case SL_SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
  32215. case SL_SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
  32216. case SL_SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  32217. case SL_SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  32218. case SL_SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  32219. case SL_SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
  32220. case SL_SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  32221. case SL_SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  32222. case SL_SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  32223. case SL_SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  32224. case SL_SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  32225. case SL_SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  32226. case SL_SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  32227. case SL_SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  32228. case SL_SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  32229. default: return 0;
  32230. }
  32231. }
  32232. /* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. */
  32233. static SLuint32 ma_channel_id_to_opensl(ma_uint8 id)
  32234. {
  32235. switch (id)
  32236. {
  32237. case MA_CHANNEL_MONO: return SL_SPEAKER_FRONT_CENTER;
  32238. case MA_CHANNEL_FRONT_LEFT: return SL_SPEAKER_FRONT_LEFT;
  32239. case MA_CHANNEL_FRONT_RIGHT: return SL_SPEAKER_FRONT_RIGHT;
  32240. case MA_CHANNEL_FRONT_CENTER: return SL_SPEAKER_FRONT_CENTER;
  32241. case MA_CHANNEL_LFE: return SL_SPEAKER_LOW_FREQUENCY;
  32242. case MA_CHANNEL_BACK_LEFT: return SL_SPEAKER_BACK_LEFT;
  32243. case MA_CHANNEL_BACK_RIGHT: return SL_SPEAKER_BACK_RIGHT;
  32244. case MA_CHANNEL_FRONT_LEFT_CENTER: return SL_SPEAKER_FRONT_LEFT_OF_CENTER;
  32245. case MA_CHANNEL_FRONT_RIGHT_CENTER: return SL_SPEAKER_FRONT_RIGHT_OF_CENTER;
  32246. case MA_CHANNEL_BACK_CENTER: return SL_SPEAKER_BACK_CENTER;
  32247. case MA_CHANNEL_SIDE_LEFT: return SL_SPEAKER_SIDE_LEFT;
  32248. case MA_CHANNEL_SIDE_RIGHT: return SL_SPEAKER_SIDE_RIGHT;
  32249. case MA_CHANNEL_TOP_CENTER: return SL_SPEAKER_TOP_CENTER;
  32250. case MA_CHANNEL_TOP_FRONT_LEFT: return SL_SPEAKER_TOP_FRONT_LEFT;
  32251. case MA_CHANNEL_TOP_FRONT_CENTER: return SL_SPEAKER_TOP_FRONT_CENTER;
  32252. case MA_CHANNEL_TOP_FRONT_RIGHT: return SL_SPEAKER_TOP_FRONT_RIGHT;
  32253. case MA_CHANNEL_TOP_BACK_LEFT: return SL_SPEAKER_TOP_BACK_LEFT;
  32254. case MA_CHANNEL_TOP_BACK_CENTER: return SL_SPEAKER_TOP_BACK_CENTER;
  32255. case MA_CHANNEL_TOP_BACK_RIGHT: return SL_SPEAKER_TOP_BACK_RIGHT;
  32256. default: return 0;
  32257. }
  32258. }
  32259. /* Converts a channel mapping to an OpenSL-style channel mask. */
  32260. static SLuint32 ma_channel_map_to_channel_mask__opensl(const ma_channel* pChannelMap, ma_uint32 channels)
  32261. {
  32262. SLuint32 channelMask = 0;
  32263. ma_uint32 iChannel;
  32264. for (iChannel = 0; iChannel < channels; ++iChannel) {
  32265. channelMask |= ma_channel_id_to_opensl(pChannelMap[iChannel]);
  32266. }
  32267. return channelMask;
  32268. }
  32269. /* Converts an OpenSL-style channel mask to a miniaudio channel map. */
  32270. static void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 channels, ma_channel* pChannelMap)
  32271. {
  32272. if (channels == 1 && channelMask == 0) {
  32273. pChannelMap[0] = MA_CHANNEL_MONO;
  32274. } else if (channels == 2 && channelMask == 0) {
  32275. pChannelMap[0] = MA_CHANNEL_FRONT_LEFT;
  32276. pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  32277. } else {
  32278. if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) {
  32279. pChannelMap[0] = MA_CHANNEL_MONO;
  32280. } else {
  32281. /* Just iterate over each bit. */
  32282. ma_uint32 iChannel = 0;
  32283. ma_uint32 iBit;
  32284. for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
  32285. SLuint32 bitValue = (channelMask & (1UL << iBit));
  32286. if (bitValue != 0) {
  32287. /* The bit is set. */
  32288. pChannelMap[iChannel] = ma_channel_id_to_ma__opensl(bitValue);
  32289. iChannel += 1;
  32290. }
  32291. }
  32292. }
  32293. }
  32294. }
  32295. static SLuint32 ma_round_to_standard_sample_rate__opensl(SLuint32 samplesPerSec)
  32296. {
  32297. if (samplesPerSec <= SL_SAMPLINGRATE_8) {
  32298. return SL_SAMPLINGRATE_8;
  32299. }
  32300. if (samplesPerSec <= SL_SAMPLINGRATE_11_025) {
  32301. return SL_SAMPLINGRATE_11_025;
  32302. }
  32303. if (samplesPerSec <= SL_SAMPLINGRATE_12) {
  32304. return SL_SAMPLINGRATE_12;
  32305. }
  32306. if (samplesPerSec <= SL_SAMPLINGRATE_16) {
  32307. return SL_SAMPLINGRATE_16;
  32308. }
  32309. if (samplesPerSec <= SL_SAMPLINGRATE_22_05) {
  32310. return SL_SAMPLINGRATE_22_05;
  32311. }
  32312. if (samplesPerSec <= SL_SAMPLINGRATE_24) {
  32313. return SL_SAMPLINGRATE_24;
  32314. }
  32315. if (samplesPerSec <= SL_SAMPLINGRATE_32) {
  32316. return SL_SAMPLINGRATE_32;
  32317. }
  32318. if (samplesPerSec <= SL_SAMPLINGRATE_44_1) {
  32319. return SL_SAMPLINGRATE_44_1;
  32320. }
  32321. if (samplesPerSec <= SL_SAMPLINGRATE_48) {
  32322. return SL_SAMPLINGRATE_48;
  32323. }
  32324. /* Android doesn't support more than 48000. */
  32325. #ifndef MA_ANDROID
  32326. if (samplesPerSec <= SL_SAMPLINGRATE_64) {
  32327. return SL_SAMPLINGRATE_64;
  32328. }
  32329. if (samplesPerSec <= SL_SAMPLINGRATE_88_2) {
  32330. return SL_SAMPLINGRATE_88_2;
  32331. }
  32332. if (samplesPerSec <= SL_SAMPLINGRATE_96) {
  32333. return SL_SAMPLINGRATE_96;
  32334. }
  32335. if (samplesPerSec <= SL_SAMPLINGRATE_192) {
  32336. return SL_SAMPLINGRATE_192;
  32337. }
  32338. #endif
  32339. return SL_SAMPLINGRATE_16;
  32340. }
  32341. static SLint32 ma_to_stream_type__opensl(ma_opensl_stream_type streamType)
  32342. {
  32343. switch (streamType) {
  32344. case ma_opensl_stream_type_voice: return SL_ANDROID_STREAM_VOICE;
  32345. case ma_opensl_stream_type_system: return SL_ANDROID_STREAM_SYSTEM;
  32346. case ma_opensl_stream_type_ring: return SL_ANDROID_STREAM_RING;
  32347. case ma_opensl_stream_type_media: return SL_ANDROID_STREAM_MEDIA;
  32348. case ma_opensl_stream_type_alarm: return SL_ANDROID_STREAM_ALARM;
  32349. case ma_opensl_stream_type_notification: return SL_ANDROID_STREAM_NOTIFICATION;
  32350. default: break;
  32351. }
  32352. return SL_ANDROID_STREAM_VOICE;
  32353. }
  32354. static SLint32 ma_to_recording_preset__opensl(ma_opensl_recording_preset recordingPreset)
  32355. {
  32356. switch (recordingPreset) {
  32357. case ma_opensl_recording_preset_generic: return SL_ANDROID_RECORDING_PRESET_GENERIC;
  32358. case ma_opensl_recording_preset_camcorder: return SL_ANDROID_RECORDING_PRESET_CAMCORDER;
  32359. case ma_opensl_recording_preset_voice_recognition: return SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION;
  32360. case ma_opensl_recording_preset_voice_communication: return SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION;
  32361. case ma_opensl_recording_preset_voice_unprocessed: return SL_ANDROID_RECORDING_PRESET_UNPROCESSED;
  32362. default: break;
  32363. }
  32364. return SL_ANDROID_RECORDING_PRESET_NONE;
  32365. }
  32366. static ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  32367. {
  32368. ma_bool32 cbResult;
  32369. MA_ASSERT(pContext != NULL);
  32370. MA_ASSERT(callback != NULL);
  32371. 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. */
  32372. if (g_maOpenSLInitCounter == 0) {
  32373. return MA_INVALID_OPERATION;
  32374. }
  32375. /*
  32376. TODO: Test Me.
  32377. This is currently untested, so for now we are just returning default devices.
  32378. */
  32379. #if 0 && !defined(MA_ANDROID)
  32380. ma_bool32 isTerminated = MA_FALSE;
  32381. SLuint32 pDeviceIDs[128];
  32382. SLint32 deviceCount = sizeof(pDeviceIDs) / sizeof(pDeviceIDs[0]);
  32383. SLAudioIODeviceCapabilitiesItf deviceCaps;
  32384. SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps);
  32385. if (resultSL != SL_RESULT_SUCCESS) {
  32386. /* The interface may not be supported so just report a default device. */
  32387. goto return_default_device;
  32388. }
  32389. /* Playback */
  32390. if (!isTerminated) {
  32391. resultSL = (*deviceCaps)->GetAvailableAudioOutputs(deviceCaps, &deviceCount, pDeviceIDs);
  32392. if (resultSL != SL_RESULT_SUCCESS) {
  32393. return ma_result_from_OpenSL(resultSL);
  32394. }
  32395. for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) {
  32396. ma_device_info deviceInfo;
  32397. MA_ZERO_OBJECT(&deviceInfo);
  32398. deviceInfo.id.opensl = pDeviceIDs[iDevice];
  32399. SLAudioOutputDescriptor desc;
  32400. resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc);
  32401. if (resultSL == SL_RESULT_SUCCESS) {
  32402. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.pDeviceName, (size_t)-1);
  32403. ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  32404. if (cbResult == MA_FALSE) {
  32405. isTerminated = MA_TRUE;
  32406. break;
  32407. }
  32408. }
  32409. }
  32410. }
  32411. /* Capture */
  32412. if (!isTerminated) {
  32413. resultSL = (*deviceCaps)->GetAvailableAudioInputs(deviceCaps, &deviceCount, pDeviceIDs);
  32414. if (resultSL != SL_RESULT_SUCCESS) {
  32415. return ma_result_from_OpenSL(resultSL);
  32416. }
  32417. for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) {
  32418. ma_device_info deviceInfo;
  32419. MA_ZERO_OBJECT(&deviceInfo);
  32420. deviceInfo.id.opensl = pDeviceIDs[iDevice];
  32421. SLAudioInputDescriptor desc;
  32422. resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc);
  32423. if (resultSL == SL_RESULT_SUCCESS) {
  32424. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.deviceName, (size_t)-1);
  32425. ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  32426. if (cbResult == MA_FALSE) {
  32427. isTerminated = MA_TRUE;
  32428. break;
  32429. }
  32430. }
  32431. }
  32432. }
  32433. return MA_SUCCESS;
  32434. #else
  32435. goto return_default_device;
  32436. #endif
  32437. return_default_device:;
  32438. cbResult = MA_TRUE;
  32439. /* Playback. */
  32440. if (cbResult) {
  32441. ma_device_info deviceInfo;
  32442. MA_ZERO_OBJECT(&deviceInfo);
  32443. deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT;
  32444. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32445. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  32446. }
  32447. /* Capture. */
  32448. if (cbResult) {
  32449. ma_device_info deviceInfo;
  32450. MA_ZERO_OBJECT(&deviceInfo);
  32451. deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT;
  32452. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32453. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  32454. }
  32455. return MA_SUCCESS;
  32456. }
  32457. 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)
  32458. {
  32459. MA_ASSERT(pContext != NULL);
  32460. MA_ASSERT(pDeviceInfo != NULL);
  32461. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  32462. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  32463. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  32464. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  32465. pDeviceInfo->nativeDataFormatCount += 1;
  32466. }
  32467. static void ma_context_add_data_format__opensl(ma_context* pContext, ma_format format, ma_device_info* pDeviceInfo)
  32468. {
  32469. ma_uint32 minChannels = 1;
  32470. ma_uint32 maxChannels = 2;
  32471. ma_uint32 minSampleRate = (ma_uint32)ma_standard_sample_rate_8000;
  32472. ma_uint32 maxSampleRate = (ma_uint32)ma_standard_sample_rate_48000;
  32473. ma_uint32 iChannel;
  32474. ma_uint32 iSampleRate;
  32475. MA_ASSERT(pContext != NULL);
  32476. MA_ASSERT(pDeviceInfo != NULL);
  32477. /*
  32478. Each sample format can support mono and stereo, and we'll support a small subset of standard
  32479. rates (up to 48000). A better solution would be to somehow find a native sample rate.
  32480. */
  32481. for (iChannel = minChannels; iChannel < maxChannels; iChannel += 1) {
  32482. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) {
  32483. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate];
  32484. if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) {
  32485. ma_context_add_data_format_ex__opensl(pContext, format, iChannel, standardSampleRate, pDeviceInfo);
  32486. }
  32487. }
  32488. }
  32489. }
  32490. 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)
  32491. {
  32492. MA_ASSERT(pContext != NULL);
  32493. 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. */
  32494. if (g_maOpenSLInitCounter == 0) {
  32495. return MA_INVALID_OPERATION;
  32496. }
  32497. /*
  32498. TODO: Test Me.
  32499. This is currently untested, so for now we are just returning default devices.
  32500. */
  32501. #if 0 && !defined(MA_ANDROID)
  32502. SLAudioIODeviceCapabilitiesItf deviceCaps;
  32503. SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps);
  32504. if (resultSL != SL_RESULT_SUCCESS) {
  32505. /* The interface may not be supported so just report a default device. */
  32506. goto return_default_device;
  32507. }
  32508. if (deviceType == ma_device_type_playback) {
  32509. SLAudioOutputDescriptor desc;
  32510. resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, pDeviceID->opensl, &desc);
  32511. if (resultSL != SL_RESULT_SUCCESS) {
  32512. return ma_result_from_OpenSL(resultSL);
  32513. }
  32514. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.pDeviceName, (size_t)-1);
  32515. } else {
  32516. SLAudioInputDescriptor desc;
  32517. resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, pDeviceID->opensl, &desc);
  32518. if (resultSL != SL_RESULT_SUCCESS) {
  32519. return ma_result_from_OpenSL(resultSL);
  32520. }
  32521. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.deviceName, (size_t)-1);
  32522. }
  32523. goto return_detailed_info;
  32524. #else
  32525. goto return_default_device;
  32526. #endif
  32527. return_default_device:
  32528. if (pDeviceID != NULL) {
  32529. if ((deviceType == ma_device_type_playback && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOOUTPUT) ||
  32530. (deviceType == ma_device_type_capture && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOINPUT)) {
  32531. return MA_NO_DEVICE; /* Don't know the device. */
  32532. }
  32533. }
  32534. /* ID and Name / Description */
  32535. if (deviceType == ma_device_type_playback) {
  32536. pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT;
  32537. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32538. } else {
  32539. pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT;
  32540. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32541. }
  32542. pDeviceInfo->isDefault = MA_TRUE;
  32543. goto return_detailed_info;
  32544. return_detailed_info:
  32545. /*
  32546. For now we're just outputting a set of values that are supported by the API but not necessarily supported
  32547. by the device natively. Later on we should work on this so that it more closely reflects the device's
  32548. actual native format.
  32549. */
  32550. pDeviceInfo->nativeDataFormatCount = 0;
  32551. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32552. ma_context_add_data_format__opensl(pContext, ma_format_f32, pDeviceInfo);
  32553. #endif
  32554. ma_context_add_data_format__opensl(pContext, ma_format_s16, pDeviceInfo);
  32555. ma_context_add_data_format__opensl(pContext, ma_format_u8, pDeviceInfo);
  32556. return MA_SUCCESS;
  32557. }
  32558. #ifdef MA_ANDROID
  32559. /*void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext)*/
  32560. static void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
  32561. {
  32562. ma_device* pDevice = (ma_device*)pUserData;
  32563. size_t periodSizeInBytes;
  32564. ma_uint8* pBuffer;
  32565. SLresult resultSL;
  32566. MA_ASSERT(pDevice != NULL);
  32567. (void)pBufferQueue;
  32568. /*
  32569. For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like
  32570. OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this,
  32571. but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :(
  32572. */
  32573. /* Don't do anything if the device is not started. */
  32574. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  32575. return;
  32576. }
  32577. /* Don't do anything if the device is being drained. */
  32578. if (pDevice->opensl.isDrainingCapture) {
  32579. return;
  32580. }
  32581. periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  32582. pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes);
  32583. ma_device_handle_backend_data_callback(pDevice, NULL, pBuffer, pDevice->capture.internalPeriodSizeInFrames);
  32584. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes);
  32585. if (resultSL != SL_RESULT_SUCCESS) {
  32586. return;
  32587. }
  32588. pDevice->opensl.currentBufferIndexCapture = (pDevice->opensl.currentBufferIndexCapture + 1) % pDevice->capture.internalPeriods;
  32589. }
  32590. static void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
  32591. {
  32592. ma_device* pDevice = (ma_device*)pUserData;
  32593. size_t periodSizeInBytes;
  32594. ma_uint8* pBuffer;
  32595. SLresult resultSL;
  32596. MA_ASSERT(pDevice != NULL);
  32597. (void)pBufferQueue;
  32598. /* Don't do anything if the device is not started. */
  32599. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  32600. return;
  32601. }
  32602. /* Don't do anything if the device is being drained. */
  32603. if (pDevice->opensl.isDrainingPlayback) {
  32604. return;
  32605. }
  32606. periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  32607. pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes);
  32608. ma_device_handle_backend_data_callback(pDevice, pBuffer, NULL, pDevice->playback.internalPeriodSizeInFrames);
  32609. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes);
  32610. if (resultSL != SL_RESULT_SUCCESS) {
  32611. return;
  32612. }
  32613. pDevice->opensl.currentBufferIndexPlayback = (pDevice->opensl.currentBufferIndexPlayback + 1) % pDevice->playback.internalPeriods;
  32614. }
  32615. #endif
  32616. static ma_result ma_device_uninit__opensl(ma_device* pDevice)
  32617. {
  32618. MA_ASSERT(pDevice != NULL);
  32619. 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. */
  32620. if (g_maOpenSLInitCounter == 0) {
  32621. return MA_INVALID_OPERATION;
  32622. }
  32623. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32624. if (pDevice->opensl.pAudioRecorderObj) {
  32625. MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioRecorderObj);
  32626. }
  32627. ma_free(pDevice->opensl.pBufferCapture, &pDevice->pContext->allocationCallbacks);
  32628. }
  32629. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32630. if (pDevice->opensl.pAudioPlayerObj) {
  32631. MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioPlayerObj);
  32632. }
  32633. if (pDevice->opensl.pOutputMixObj) {
  32634. MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Destroy((SLObjectItf)pDevice->opensl.pOutputMixObj);
  32635. }
  32636. ma_free(pDevice->opensl.pBufferPlayback, &pDevice->pContext->allocationCallbacks);
  32637. }
  32638. return MA_SUCCESS;
  32639. }
  32640. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32641. typedef SLAndroidDataFormat_PCM_EX ma_SLDataFormat_PCM;
  32642. #else
  32643. typedef SLDataFormat_PCM ma_SLDataFormat_PCM;
  32644. #endif
  32645. 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)
  32646. {
  32647. /* We need to convert our format/channels/rate so that they aren't set to default. */
  32648. if (format == ma_format_unknown) {
  32649. format = MA_DEFAULT_FORMAT;
  32650. }
  32651. if (channels == 0) {
  32652. channels = MA_DEFAULT_CHANNELS;
  32653. }
  32654. if (sampleRate == 0) {
  32655. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  32656. }
  32657. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32658. if (format == ma_format_f32) {
  32659. pDataFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  32660. pDataFormat->representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
  32661. } else {
  32662. pDataFormat->formatType = SL_DATAFORMAT_PCM;
  32663. }
  32664. #else
  32665. pDataFormat->formatType = SL_DATAFORMAT_PCM;
  32666. #endif
  32667. pDataFormat->numChannels = channels;
  32668. ((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 */
  32669. pDataFormat->bitsPerSample = ma_get_bytes_per_sample(format) * 8;
  32670. pDataFormat->channelMask = ma_channel_map_to_channel_mask__opensl(channelMap, channels);
  32671. pDataFormat->endianness = (ma_is_little_endian()) ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN;
  32672. /*
  32673. Android has a few restrictions on the format as documented here: https://developer.android.com/ndk/guides/audio/opensl-for-android.html
  32674. - Only mono and stereo is supported.
  32675. - Only u8 and s16 formats are supported.
  32676. - Maximum sample rate of 48000.
  32677. */
  32678. #ifdef MA_ANDROID
  32679. if (pDataFormat->numChannels > 2) {
  32680. pDataFormat->numChannels = 2;
  32681. }
  32682. #if __ANDROID_API__ >= 21
  32683. if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) {
  32684. /* It's floating point. */
  32685. MA_ASSERT(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT);
  32686. if (pDataFormat->bitsPerSample > 32) {
  32687. pDataFormat->bitsPerSample = 32;
  32688. }
  32689. } else {
  32690. if (pDataFormat->bitsPerSample > 16) {
  32691. pDataFormat->bitsPerSample = 16;
  32692. }
  32693. }
  32694. #else
  32695. if (pDataFormat->bitsPerSample > 16) {
  32696. pDataFormat->bitsPerSample = 16;
  32697. }
  32698. #endif
  32699. if (((SLDataFormat_PCM*)pDataFormat)->samplesPerSec > SL_SAMPLINGRATE_48) {
  32700. ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec = SL_SAMPLINGRATE_48;
  32701. }
  32702. #endif
  32703. pDataFormat->containerSize = pDataFormat->bitsPerSample; /* Always tightly packed for now. */
  32704. return MA_SUCCESS;
  32705. }
  32706. 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)
  32707. {
  32708. ma_bool32 isFloatingPoint = MA_FALSE;
  32709. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  32710. if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) {
  32711. MA_ASSERT(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT);
  32712. isFloatingPoint = MA_TRUE;
  32713. }
  32714. #endif
  32715. if (isFloatingPoint) {
  32716. if (pDataFormat->bitsPerSample == 32) {
  32717. *pFormat = ma_format_f32;
  32718. }
  32719. } else {
  32720. if (pDataFormat->bitsPerSample == 8) {
  32721. *pFormat = ma_format_u8;
  32722. } else if (pDataFormat->bitsPerSample == 16) {
  32723. *pFormat = ma_format_s16;
  32724. } else if (pDataFormat->bitsPerSample == 24) {
  32725. *pFormat = ma_format_s24;
  32726. } else if (pDataFormat->bitsPerSample == 32) {
  32727. *pFormat = ma_format_s32;
  32728. }
  32729. }
  32730. *pChannels = pDataFormat->numChannels;
  32731. *pSampleRate = ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec / 1000;
  32732. ma_channel_mask_to_channel_map__opensl(pDataFormat->channelMask, ma_min(pDataFormat->numChannels, channelMapCap), pChannelMap);
  32733. return MA_SUCCESS;
  32734. }
  32735. static ma_result ma_device_init__opensl(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  32736. {
  32737. #ifdef MA_ANDROID
  32738. SLDataLocator_AndroidSimpleBufferQueue queue;
  32739. SLresult resultSL;
  32740. size_t bufferSizeInBytes;
  32741. SLInterfaceID itfIDs[2];
  32742. const SLboolean itfIDsRequired[] = {
  32743. SL_BOOLEAN_TRUE, /* SL_IID_ANDROIDSIMPLEBUFFERQUEUE */
  32744. SL_BOOLEAN_FALSE /* SL_IID_ANDROIDCONFIGURATION */
  32745. };
  32746. #endif
  32747. 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. */
  32748. if (g_maOpenSLInitCounter == 0) {
  32749. return MA_INVALID_OPERATION;
  32750. }
  32751. if (pConfig->deviceType == ma_device_type_loopback) {
  32752. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  32753. }
  32754. /*
  32755. For now, only supporting Android implementations of OpenSL|ES since that's the only one I've
  32756. been able to test with and I currently depend on Android-specific extensions (simple buffer
  32757. queues).
  32758. */
  32759. #ifdef MA_ANDROID
  32760. itfIDs[0] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  32761. itfIDs[1] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION;
  32762. /* No exclusive mode with OpenSL|ES. */
  32763. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  32764. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  32765. return MA_SHARE_MODE_NOT_SUPPORTED;
  32766. }
  32767. /* Now we can start initializing the device properly. */
  32768. MA_ASSERT(pDevice != NULL);
  32769. MA_ZERO_OBJECT(&pDevice->opensl);
  32770. queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  32771. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  32772. ma_SLDataFormat_PCM pcm;
  32773. SLDataLocator_IODevice locatorDevice;
  32774. SLDataSource source;
  32775. SLDataSink sink;
  32776. SLAndroidConfigurationItf pRecorderConfig;
  32777. ma_SLDataFormat_PCM_init__opensl(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &pcm);
  32778. locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE;
  32779. locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT;
  32780. locatorDevice.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT; /* Must always use the default device with Android. */
  32781. locatorDevice.device = NULL;
  32782. source.pLocator = &locatorDevice;
  32783. source.pFormat = NULL;
  32784. queue.numBuffers = pDescriptorCapture->periodCount;
  32785. sink.pLocator = &queue;
  32786. sink.pFormat = (SLDataFormat_PCM*)&pcm;
  32787. resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32788. if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) {
  32789. /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
  32790. pcm.formatType = SL_DATAFORMAT_PCM;
  32791. pcm.numChannels = 1;
  32792. ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16; /* The name of the sample rate variable is different between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM. */
  32793. pcm.bitsPerSample = 16;
  32794. pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
  32795. pcm.channelMask = 0;
  32796. resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32797. }
  32798. if (resultSL != SL_RESULT_SUCCESS) {
  32799. ma_device_uninit__opensl(pDevice);
  32800. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder.");
  32801. return ma_result_from_OpenSL(resultSL);
  32802. }
  32803. /* Set the recording preset before realizing the player. */
  32804. if (pConfig->opensl.recordingPreset != ma_opensl_recording_preset_default) {
  32805. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pRecorderConfig);
  32806. if (resultSL == SL_RESULT_SUCCESS) {
  32807. SLint32 recordingPreset = ma_to_recording_preset__opensl(pConfig->opensl.recordingPreset);
  32808. resultSL = (*pRecorderConfig)->SetConfiguration(pRecorderConfig, SL_ANDROID_KEY_RECORDING_PRESET, &recordingPreset, sizeof(SLint32));
  32809. if (resultSL != SL_RESULT_SUCCESS) {
  32810. /* Failed to set the configuration. Just keep going. */
  32811. }
  32812. }
  32813. }
  32814. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE);
  32815. if (resultSL != SL_RESULT_SUCCESS) {
  32816. ma_device_uninit__opensl(pDevice);
  32817. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder.");
  32818. return ma_result_from_OpenSL(resultSL);
  32819. }
  32820. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_RECORD, &pDevice->opensl.pAudioRecorder);
  32821. if (resultSL != SL_RESULT_SUCCESS) {
  32822. ma_device_uninit__opensl(pDevice);
  32823. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface.");
  32824. return ma_result_from_OpenSL(resultSL);
  32825. }
  32826. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueueCapture);
  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 retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.");
  32830. return ma_result_from_OpenSL(resultSL);
  32831. }
  32832. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, ma_buffer_queue_callback_capture__opensl_android, pDevice);
  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 register buffer queue callback.");
  32836. return ma_result_from_OpenSL(resultSL);
  32837. }
  32838. /* The internal format is determined by the "pcm" object. */
  32839. ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorCapture->format, &pDescriptorCapture->channels, &pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap));
  32840. /* Buffer. */
  32841. pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  32842. pDevice->opensl.currentBufferIndexCapture = 0;
  32843. bufferSizeInBytes = pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * pDescriptorCapture->periodCount;
  32844. pDevice->opensl.pBufferCapture = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks);
  32845. if (pDevice->opensl.pBufferCapture == NULL) {
  32846. ma_device_uninit__opensl(pDevice);
  32847. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.");
  32848. return MA_OUT_OF_MEMORY;
  32849. }
  32850. MA_ZERO_MEMORY(pDevice->opensl.pBufferCapture, bufferSizeInBytes);
  32851. }
  32852. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  32853. ma_SLDataFormat_PCM pcm;
  32854. SLDataSource source;
  32855. SLDataLocator_OutputMix outmixLocator;
  32856. SLDataSink sink;
  32857. SLAndroidConfigurationItf pPlayerConfig;
  32858. ma_SLDataFormat_PCM_init__opensl(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &pcm);
  32859. resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL);
  32860. if (resultSL != SL_RESULT_SUCCESS) {
  32861. ma_device_uninit__opensl(pDevice);
  32862. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.");
  32863. return ma_result_from_OpenSL(resultSL);
  32864. }
  32865. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE);
  32866. if (resultSL != SL_RESULT_SUCCESS) {
  32867. ma_device_uninit__opensl(pDevice);
  32868. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object.");
  32869. return ma_result_from_OpenSL(resultSL);
  32870. }
  32871. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix);
  32872. if (resultSL != SL_RESULT_SUCCESS) {
  32873. ma_device_uninit__opensl(pDevice);
  32874. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface.");
  32875. return ma_result_from_OpenSL(resultSL);
  32876. }
  32877. /* Set the output device. */
  32878. if (pDescriptorPlayback->pDeviceID != NULL) {
  32879. SLuint32 deviceID_OpenSL = pDescriptorPlayback->pDeviceID->opensl;
  32880. MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL);
  32881. }
  32882. queue.numBuffers = pDescriptorPlayback->periodCount;
  32883. source.pLocator = &queue;
  32884. source.pFormat = (SLDataFormat_PCM*)&pcm;
  32885. outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  32886. outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj;
  32887. sink.pLocator = &outmixLocator;
  32888. sink.pFormat = NULL;
  32889. resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32890. if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) {
  32891. /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
  32892. pcm.formatType = SL_DATAFORMAT_PCM;
  32893. pcm.numChannels = 2;
  32894. ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16;
  32895. pcm.bitsPerSample = 16;
  32896. pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
  32897. pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  32898. resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  32899. }
  32900. if (resultSL != SL_RESULT_SUCCESS) {
  32901. ma_device_uninit__opensl(pDevice);
  32902. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player.");
  32903. return ma_result_from_OpenSL(resultSL);
  32904. }
  32905. /* Set the stream type before realizing the player. */
  32906. if (pConfig->opensl.streamType != ma_opensl_stream_type_default) {
  32907. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pPlayerConfig);
  32908. if (resultSL == SL_RESULT_SUCCESS) {
  32909. SLint32 streamType = ma_to_stream_type__opensl(pConfig->opensl.streamType);
  32910. resultSL = (*pPlayerConfig)->SetConfiguration(pPlayerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32));
  32911. if (resultSL != SL_RESULT_SUCCESS) {
  32912. /* Failed to set the configuration. Just keep going. */
  32913. }
  32914. }
  32915. }
  32916. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE);
  32917. if (resultSL != SL_RESULT_SUCCESS) {
  32918. ma_device_uninit__opensl(pDevice);
  32919. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player.");
  32920. return ma_result_from_OpenSL(resultSL);
  32921. }
  32922. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_PLAY, &pDevice->opensl.pAudioPlayer);
  32923. if (resultSL != SL_RESULT_SUCCESS) {
  32924. ma_device_uninit__opensl(pDevice);
  32925. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface.");
  32926. return ma_result_from_OpenSL(resultSL);
  32927. }
  32928. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueuePlayback);
  32929. if (resultSL != SL_RESULT_SUCCESS) {
  32930. ma_device_uninit__opensl(pDevice);
  32931. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.");
  32932. return ma_result_from_OpenSL(resultSL);
  32933. }
  32934. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, ma_buffer_queue_callback_playback__opensl_android, pDevice);
  32935. if (resultSL != SL_RESULT_SUCCESS) {
  32936. ma_device_uninit__opensl(pDevice);
  32937. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.");
  32938. return ma_result_from_OpenSL(resultSL);
  32939. }
  32940. /* The internal format is determined by the "pcm" object. */
  32941. ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorPlayback->format, &pDescriptorPlayback->channels, &pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap));
  32942. /* Buffer. */
  32943. pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  32944. pDevice->opensl.currentBufferIndexPlayback = 0;
  32945. bufferSizeInBytes = pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) * pDescriptorPlayback->periodCount;
  32946. pDevice->opensl.pBufferPlayback = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks);
  32947. if (pDevice->opensl.pBufferPlayback == NULL) {
  32948. ma_device_uninit__opensl(pDevice);
  32949. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.");
  32950. return MA_OUT_OF_MEMORY;
  32951. }
  32952. MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, bufferSizeInBytes);
  32953. }
  32954. return MA_SUCCESS;
  32955. #else
  32956. return MA_NO_BACKEND; /* Non-Android implementations are not supported. */
  32957. #endif
  32958. }
  32959. static ma_result ma_device_start__opensl(ma_device* pDevice)
  32960. {
  32961. SLresult resultSL;
  32962. size_t periodSizeInBytes;
  32963. ma_uint32 iPeriod;
  32964. MA_ASSERT(pDevice != NULL);
  32965. 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. */
  32966. if (g_maOpenSLInitCounter == 0) {
  32967. return MA_INVALID_OPERATION;
  32968. }
  32969. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32970. resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING);
  32971. if (resultSL != SL_RESULT_SUCCESS) {
  32972. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.");
  32973. return ma_result_from_OpenSL(resultSL);
  32974. }
  32975. periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  32976. for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
  32977. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pDevice->opensl.pBufferCapture + (periodSizeInBytes * iPeriod), periodSizeInBytes);
  32978. if (resultSL != SL_RESULT_SUCCESS) {
  32979. MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
  32980. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device.");
  32981. return ma_result_from_OpenSL(resultSL);
  32982. }
  32983. }
  32984. }
  32985. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32986. resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING);
  32987. if (resultSL != SL_RESULT_SUCCESS) {
  32988. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.");
  32989. return ma_result_from_OpenSL(resultSL);
  32990. }
  32991. /* In playback mode (no duplex) we need to load some initial buffers. In duplex mode we need to enqueue silent buffers. */
  32992. if (pDevice->type == ma_device_type_duplex) {
  32993. MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  32994. } else {
  32995. ma_device__read_frames_from_client(pDevice, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods, pDevice->opensl.pBufferPlayback);
  32996. }
  32997. periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  32998. for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) {
  32999. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pDevice->opensl.pBufferPlayback + (periodSizeInBytes * iPeriod), periodSizeInBytes);
  33000. if (resultSL != SL_RESULT_SUCCESS) {
  33001. MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
  33002. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device.");
  33003. return ma_result_from_OpenSL(resultSL);
  33004. }
  33005. }
  33006. }
  33007. return MA_SUCCESS;
  33008. }
  33009. static ma_result ma_device_drain__opensl(ma_device* pDevice, ma_device_type deviceType)
  33010. {
  33011. SLAndroidSimpleBufferQueueItf pBufferQueue;
  33012. MA_ASSERT(deviceType == ma_device_type_capture || deviceType == ma_device_type_playback);
  33013. if (pDevice->type == ma_device_type_capture) {
  33014. pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture;
  33015. pDevice->opensl.isDrainingCapture = MA_TRUE;
  33016. } else {
  33017. pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback;
  33018. pDevice->opensl.isDrainingPlayback = MA_TRUE;
  33019. }
  33020. for (;;) {
  33021. SLAndroidSimpleBufferQueueState state;
  33022. MA_OPENSL_BUFFERQUEUE(pBufferQueue)->GetState(pBufferQueue, &state);
  33023. if (state.count == 0) {
  33024. break;
  33025. }
  33026. ma_sleep(10);
  33027. }
  33028. if (pDevice->type == ma_device_type_capture) {
  33029. pDevice->opensl.isDrainingCapture = MA_FALSE;
  33030. } else {
  33031. pDevice->opensl.isDrainingPlayback = MA_FALSE;
  33032. }
  33033. return MA_SUCCESS;
  33034. }
  33035. static ma_result ma_device_stop__opensl(ma_device* pDevice)
  33036. {
  33037. SLresult resultSL;
  33038. MA_ASSERT(pDevice != NULL);
  33039. 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. */
  33040. if (g_maOpenSLInitCounter == 0) {
  33041. return MA_INVALID_OPERATION;
  33042. }
  33043. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  33044. ma_device_drain__opensl(pDevice, ma_device_type_capture);
  33045. resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
  33046. if (resultSL != SL_RESULT_SUCCESS) {
  33047. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device.");
  33048. return ma_result_from_OpenSL(resultSL);
  33049. }
  33050. MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture);
  33051. }
  33052. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33053. ma_device_drain__opensl(pDevice, ma_device_type_playback);
  33054. resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
  33055. if (resultSL != SL_RESULT_SUCCESS) {
  33056. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device.");
  33057. return ma_result_from_OpenSL(resultSL);
  33058. }
  33059. MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback);
  33060. }
  33061. /* 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. */
  33062. ma_device__on_notification_stopped(pDevice);
  33063. return MA_SUCCESS;
  33064. }
  33065. static ma_result ma_context_uninit__opensl(ma_context* pContext)
  33066. {
  33067. MA_ASSERT(pContext != NULL);
  33068. MA_ASSERT(pContext->backend == ma_backend_opensl);
  33069. (void)pContext;
  33070. /* Uninit global data. */
  33071. ma_spinlock_lock(&g_maOpenSLSpinlock);
  33072. {
  33073. 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(). */
  33074. g_maOpenSLInitCounter -= 1;
  33075. if (g_maOpenSLInitCounter == 0) {
  33076. (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL);
  33077. }
  33078. }
  33079. ma_spinlock_unlock(&g_maOpenSLSpinlock);
  33080. return MA_SUCCESS;
  33081. }
  33082. static ma_result ma_dlsym_SLInterfaceID__opensl(ma_context* pContext, const char* pName, ma_handle* pHandle)
  33083. {
  33084. /* 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. */
  33085. ma_handle* p = (ma_handle*)ma_dlsym(ma_context_get_log(pContext), pContext->opensl.libOpenSLES, pName);
  33086. if (p == NULL) {
  33087. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol %s", pName);
  33088. return MA_NO_BACKEND;
  33089. }
  33090. *pHandle = *p;
  33091. return MA_SUCCESS;
  33092. }
  33093. static ma_result ma_context_init_engine_nolock__opensl(ma_context* pContext)
  33094. {
  33095. g_maOpenSLInitCounter += 1;
  33096. if (g_maOpenSLInitCounter == 1) {
  33097. SLresult resultSL;
  33098. resultSL = ((ma_slCreateEngine_proc)pContext->opensl.slCreateEngine)(&g_maEngineObjectSL, 0, NULL, 0, NULL, NULL);
  33099. if (resultSL != SL_RESULT_SUCCESS) {
  33100. g_maOpenSLInitCounter -= 1;
  33101. return ma_result_from_OpenSL(resultSL);
  33102. }
  33103. (*g_maEngineObjectSL)->Realize(g_maEngineObjectSL, SL_BOOLEAN_FALSE);
  33104. resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_ENGINE, &g_maEngineSL);
  33105. if (resultSL != SL_RESULT_SUCCESS) {
  33106. (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL);
  33107. g_maOpenSLInitCounter -= 1;
  33108. return ma_result_from_OpenSL(resultSL);
  33109. }
  33110. }
  33111. return MA_SUCCESS;
  33112. }
  33113. static ma_result ma_context_init__opensl(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  33114. {
  33115. ma_result result;
  33116. #if !defined(MA_NO_RUNTIME_LINKING)
  33117. size_t i;
  33118. const char* libOpenSLESNames[] = {
  33119. "libOpenSLES.so"
  33120. };
  33121. #endif
  33122. MA_ASSERT(pContext != NULL);
  33123. (void)pConfig;
  33124. #if !defined(MA_NO_RUNTIME_LINKING)
  33125. /*
  33126. Dynamically link against libOpenSLES.so. I have now had multiple reports that SL_IID_ANDROIDSIMPLEBUFFERQUEUE cannot be found. One
  33127. report was happening at compile time and another at runtime. To try working around this, I'm going to link to libOpenSLES at runtime
  33128. and extract the symbols rather than reference them directly. This should, hopefully, fix these issues as the compiler won't see any
  33129. references to the symbols and will hopefully skip the checks.
  33130. */
  33131. for (i = 0; i < ma_countof(libOpenSLESNames); i += 1) {
  33132. pContext->opensl.libOpenSLES = ma_dlopen(ma_context_get_log(pContext), libOpenSLESNames[i]);
  33133. if (pContext->opensl.libOpenSLES != NULL) {
  33134. break;
  33135. }
  33136. }
  33137. if (pContext->opensl.libOpenSLES == NULL) {
  33138. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Could not find libOpenSLES.so");
  33139. return MA_NO_BACKEND;
  33140. }
  33141. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ENGINE", &pContext->opensl.SL_IID_ENGINE);
  33142. if (result != MA_SUCCESS) {
  33143. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33144. return result;
  33145. }
  33146. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_AUDIOIODEVICECAPABILITIES", &pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES);
  33147. if (result != MA_SUCCESS) {
  33148. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33149. return result;
  33150. }
  33151. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDSIMPLEBUFFERQUEUE", &pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE);
  33152. if (result != MA_SUCCESS) {
  33153. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33154. return result;
  33155. }
  33156. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_RECORD", &pContext->opensl.SL_IID_RECORD);
  33157. if (result != MA_SUCCESS) {
  33158. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33159. return result;
  33160. }
  33161. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_PLAY", &pContext->opensl.SL_IID_PLAY);
  33162. if (result != MA_SUCCESS) {
  33163. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33164. return result;
  33165. }
  33166. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_OUTPUTMIX", &pContext->opensl.SL_IID_OUTPUTMIX);
  33167. if (result != MA_SUCCESS) {
  33168. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33169. return result;
  33170. }
  33171. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDCONFIGURATION", &pContext->opensl.SL_IID_ANDROIDCONFIGURATION);
  33172. if (result != MA_SUCCESS) {
  33173. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33174. return result;
  33175. }
  33176. pContext->opensl.slCreateEngine = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->opensl.libOpenSLES, "slCreateEngine");
  33177. if (pContext->opensl.slCreateEngine == NULL) {
  33178. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33179. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol slCreateEngine.");
  33180. return MA_NO_BACKEND;
  33181. }
  33182. #else
  33183. pContext->opensl.SL_IID_ENGINE = (ma_handle)SL_IID_ENGINE;
  33184. pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES = (ma_handle)SL_IID_AUDIOIODEVICECAPABILITIES;
  33185. pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE = (ma_handle)SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  33186. pContext->opensl.SL_IID_RECORD = (ma_handle)SL_IID_RECORD;
  33187. pContext->opensl.SL_IID_PLAY = (ma_handle)SL_IID_PLAY;
  33188. pContext->opensl.SL_IID_OUTPUTMIX = (ma_handle)SL_IID_OUTPUTMIX;
  33189. pContext->opensl.SL_IID_ANDROIDCONFIGURATION = (ma_handle)SL_IID_ANDROIDCONFIGURATION;
  33190. pContext->opensl.slCreateEngine = (ma_proc)slCreateEngine;
  33191. #endif
  33192. /* Initialize global data first if applicable. */
  33193. ma_spinlock_lock(&g_maOpenSLSpinlock);
  33194. {
  33195. result = ma_context_init_engine_nolock__opensl(pContext);
  33196. }
  33197. ma_spinlock_unlock(&g_maOpenSLSpinlock);
  33198. if (result != MA_SUCCESS) {
  33199. ma_dlclose(ma_context_get_log(pContext), pContext->opensl.libOpenSLES);
  33200. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Failed to initialize OpenSL engine.");
  33201. return result;
  33202. }
  33203. pCallbacks->onContextInit = ma_context_init__opensl;
  33204. pCallbacks->onContextUninit = ma_context_uninit__opensl;
  33205. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__opensl;
  33206. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__opensl;
  33207. pCallbacks->onDeviceInit = ma_device_init__opensl;
  33208. pCallbacks->onDeviceUninit = ma_device_uninit__opensl;
  33209. pCallbacks->onDeviceStart = ma_device_start__opensl;
  33210. pCallbacks->onDeviceStop = ma_device_stop__opensl;
  33211. pCallbacks->onDeviceRead = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  33212. pCallbacks->onDeviceWrite = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  33213. pCallbacks->onDeviceDataLoop = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  33214. return MA_SUCCESS;
  33215. }
  33216. #endif /* OpenSL|ES */
  33217. /******************************************************************************
  33218. Web Audio Backend
  33219. ******************************************************************************/
  33220. #ifdef MA_HAS_WEBAUDIO
  33221. #include <emscripten/emscripten.h>
  33222. #if (__EMSCRIPTEN_major__ > 3) || (__EMSCRIPTEN_major__ == 3 && (__EMSCRIPTEN_minor__ > 1 || (__EMSCRIPTEN_minor__ == 1 && __EMSCRIPTEN_tiny__ >= 32)))
  33223. #include <emscripten/webaudio.h>
  33224. #define MA_SUPPORT_AUDIO_WORKLETS
  33225. #endif
  33226. /*
  33227. TODO: Version 0.12: Swap this logic around so that AudioWorklets are used by default. Add MA_NO_AUDIO_WORKLETS.
  33228. */
  33229. #if defined(MA_ENABLE_AUDIO_WORKLETS) && defined(MA_SUPPORT_AUDIO_WORKLETS)
  33230. #define MA_USE_AUDIO_WORKLETS
  33231. #endif
  33232. /* The thread stack size must be a multiple of 16. */
  33233. #ifndef MA_AUDIO_WORKLETS_THREAD_STACK_SIZE
  33234. #define MA_AUDIO_WORKLETS_THREAD_STACK_SIZE 16384
  33235. #endif
  33236. #if defined(MA_USE_AUDIO_WORKLETS)
  33237. #define MA_WEBAUDIO_LATENCY_HINT_BALANCED "balanced"
  33238. #define MA_WEBAUDIO_LATENCY_HINT_INTERACTIVE "interactive"
  33239. #define MA_WEBAUDIO_LATENCY_HINT_PLAYBACK "playback"
  33240. #endif
  33241. static ma_bool32 ma_is_capture_supported__webaudio()
  33242. {
  33243. return EM_ASM_INT({
  33244. return (navigator.mediaDevices !== undefined && navigator.mediaDevices.getUserMedia !== undefined);
  33245. }, 0) != 0; /* Must pass in a dummy argument for C99 compatibility. */
  33246. }
  33247. #ifdef __cplusplus
  33248. extern "C" {
  33249. #endif
  33250. void* EMSCRIPTEN_KEEPALIVE ma_malloc_emscripten(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  33251. {
  33252. return ma_malloc(sz, pAllocationCallbacks);
  33253. }
  33254. void EMSCRIPTEN_KEEPALIVE ma_free_emscripten(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  33255. {
  33256. ma_free(p, pAllocationCallbacks);
  33257. }
  33258. void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
  33259. {
  33260. ma_device_handle_backend_data_callback(pDevice, NULL, pFrames, (ma_uint32)frameCount);
  33261. }
  33262. void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_playback__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
  33263. {
  33264. ma_device_handle_backend_data_callback(pDevice, pFrames, NULL, (ma_uint32)frameCount);
  33265. }
  33266. #ifdef __cplusplus
  33267. }
  33268. #endif
  33269. static ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  33270. {
  33271. ma_bool32 cbResult = MA_TRUE;
  33272. MA_ASSERT(pContext != NULL);
  33273. MA_ASSERT(callback != NULL);
  33274. /* Only supporting default devices for now. */
  33275. /* Playback. */
  33276. if (cbResult) {
  33277. ma_device_info deviceInfo;
  33278. MA_ZERO_OBJECT(&deviceInfo);
  33279. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  33280. deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */
  33281. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  33282. }
  33283. /* Capture. */
  33284. if (cbResult) {
  33285. if (ma_is_capture_supported__webaudio()) {
  33286. ma_device_info deviceInfo;
  33287. MA_ZERO_OBJECT(&deviceInfo);
  33288. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  33289. deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */
  33290. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  33291. }
  33292. }
  33293. return MA_SUCCESS;
  33294. }
  33295. 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)
  33296. {
  33297. MA_ASSERT(pContext != NULL);
  33298. if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
  33299. return MA_NO_DEVICE;
  33300. }
  33301. MA_ZERO_MEMORY(pDeviceInfo->id.webaudio, sizeof(pDeviceInfo->id.webaudio));
  33302. /* Only supporting default devices for now. */
  33303. (void)pDeviceID;
  33304. if (deviceType == ma_device_type_playback) {
  33305. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  33306. } else {
  33307. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  33308. }
  33309. /* Only supporting default devices. */
  33310. pDeviceInfo->isDefault = MA_TRUE;
  33311. /* Web Audio can support any number of channels and sample rates. It only supports f32 formats, however. */
  33312. pDeviceInfo->nativeDataFormats[0].flags = 0;
  33313. pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
  33314. pDeviceInfo->nativeDataFormats[0].channels = 0; /* All channels are supported. */
  33315. pDeviceInfo->nativeDataFormats[0].sampleRate = EM_ASM_INT({
  33316. try {
  33317. var temp = new (window.AudioContext || window.webkitAudioContext)();
  33318. var sampleRate = temp.sampleRate;
  33319. temp.close();
  33320. return sampleRate;
  33321. } catch(e) {
  33322. return 0;
  33323. }
  33324. }, 0); /* Must pass in a dummy argument for C99 compatibility. */
  33325. if (pDeviceInfo->nativeDataFormats[0].sampleRate == 0) {
  33326. return MA_NO_DEVICE;
  33327. }
  33328. pDeviceInfo->nativeDataFormatCount = 1;
  33329. return MA_SUCCESS;
  33330. }
  33331. static ma_result ma_device_uninit__webaudio(ma_device* pDevice)
  33332. {
  33333. MA_ASSERT(pDevice != NULL);
  33334. #if defined(MA_USE_AUDIO_WORKLETS)
  33335. {
  33336. EM_ASM({
  33337. var device = miniaudio.get_device_by_index($0);
  33338. if (device.streamNode !== undefined) {
  33339. device.streamNode.disconnect();
  33340. device.streamNode = undefined;
  33341. }
  33342. }, pDevice->webaudio.deviceIndex);
  33343. emscripten_destroy_web_audio_node(pDevice->webaudio.audioWorklet);
  33344. emscripten_destroy_audio_context(pDevice->webaudio.audioContext);
  33345. ma_free(pDevice->webaudio.pStackBuffer, &pDevice->pContext->allocationCallbacks);
  33346. }
  33347. #else
  33348. {
  33349. EM_ASM({
  33350. var device = miniaudio.get_device_by_index($0);
  33351. /* Make sure all nodes are disconnected and marked for collection. */
  33352. if (device.scriptNode !== undefined) {
  33353. 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... */
  33354. device.scriptNode.disconnect();
  33355. device.scriptNode = undefined;
  33356. }
  33357. if (device.streamNode !== undefined) {
  33358. device.streamNode.disconnect();
  33359. device.streamNode = undefined;
  33360. }
  33361. /*
  33362. Stop the device. I think there is a chance the callback could get fired after calling this, hence why we want
  33363. to clear the callback before closing.
  33364. */
  33365. device.webaudio.close();
  33366. device.webaudio = undefined;
  33367. }, pDevice->webaudio.deviceIndex);
  33368. }
  33369. #endif
  33370. /* Clean up the device on the JS side. */
  33371. EM_ASM({
  33372. miniaudio.untrack_device_by_index($0);
  33373. }, pDevice->webaudio.deviceIndex);
  33374. ma_free(pDevice->webaudio.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  33375. return MA_SUCCESS;
  33376. }
  33377. #if !defined(MA_USE_AUDIO_WORKLETS)
  33378. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__webaudio(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  33379. {
  33380. /*
  33381. There have been reports of the default buffer size being too small on some browsers. If we're using
  33382. the default buffer size, we'll make sure the period size is bigger than our standard defaults.
  33383. */
  33384. ma_uint32 periodSizeInFrames;
  33385. if (pDescriptor->periodSizeInFrames == 0) {
  33386. if (pDescriptor->periodSizeInMilliseconds == 0) {
  33387. if (performanceProfile == ma_performance_profile_low_latency) {
  33388. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(33, nativeSampleRate); /* 1 frame @ 30 FPS */
  33389. } else {
  33390. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(333, nativeSampleRate);
  33391. }
  33392. } else {
  33393. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  33394. }
  33395. } else {
  33396. periodSizeInFrames = pDescriptor->periodSizeInFrames;
  33397. }
  33398. /* The size of the buffer must be a power of 2 and between 256 and 16384. */
  33399. if (periodSizeInFrames < 256) {
  33400. periodSizeInFrames = 256;
  33401. } else if (periodSizeInFrames > 16384) {
  33402. periodSizeInFrames = 16384;
  33403. } else {
  33404. periodSizeInFrames = ma_next_power_of_2(periodSizeInFrames);
  33405. }
  33406. return periodSizeInFrames;
  33407. }
  33408. #endif
  33409. #if defined(MA_USE_AUDIO_WORKLETS)
  33410. typedef struct
  33411. {
  33412. ma_device* pDevice;
  33413. const ma_device_config* pConfig;
  33414. ma_device_descriptor* pDescriptorPlayback;
  33415. ma_device_descriptor* pDescriptorCapture;
  33416. } ma_audio_worklet_thread_initialized_data;
  33417. 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)
  33418. {
  33419. ma_device* pDevice = (ma_device*)pUserData;
  33420. ma_uint32 frameCount;
  33421. (void)paramCount;
  33422. (void)pParams;
  33423. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  33424. return EM_TRUE;
  33425. }
  33426. /*
  33427. The Emscripten documentation says that it'll always be 128 frames being passed in. Hard coding it like that feels
  33428. like a very bad idea to me. Even if it's hard coded in the backend, the API and documentation should always refer
  33429. to variables instead of a hard coded number. In any case, will follow along for the time being.
  33430. Unfortunately the audio data is not interleaved so we'll need to convert it before we give the data to miniaudio
  33431. for further processing.
  33432. */
  33433. frameCount = 128;
  33434. if (inputCount > 0) {
  33435. /* Input data needs to be interleaved before we hand it to the client. */
  33436. for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; iChannel += 1) {
  33437. for (ma_uint32 iFrame = 0; iFrame < frameCount; iFrame += 1) {
  33438. pDevice->webaudio.pIntermediaryBuffer[iFrame*pDevice->capture.internalChannels + iChannel] = pInputs[0].data[frameCount*iChannel + iFrame];
  33439. }
  33440. }
  33441. ma_device_process_pcm_frames_capture__webaudio(pDevice, frameCount, pDevice->webaudio.pIntermediaryBuffer);
  33442. }
  33443. if (outputCount > 0) {
  33444. /* If it's a capture-only device, we'll need to output silence. */
  33445. if (pDevice->type == ma_device_type_capture) {
  33446. MA_ZERO_MEMORY(pOutputs[0].data, frameCount * pDevice->playback.internalChannels * sizeof(float));
  33447. } else {
  33448. ma_device_process_pcm_frames_playback__webaudio(pDevice, frameCount, pDevice->webaudio.pIntermediaryBuffer);
  33449. /* We've read the data from the client. Now we need to deinterleave the buffer and output to the output buffer. */
  33450. for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; iChannel += 1) {
  33451. for (ma_uint32 iFrame = 0; iFrame < frameCount; iFrame += 1) {
  33452. pOutputs[0].data[frameCount*iChannel + iFrame] = pDevice->webaudio.pIntermediaryBuffer[iFrame*pDevice->playback.internalChannels + iChannel];
  33453. }
  33454. }
  33455. }
  33456. }
  33457. return EM_TRUE;
  33458. }
  33459. static void ma_audio_worklet_processor_created__webaudio(EMSCRIPTEN_WEBAUDIO_T audioContext, EM_BOOL success, void* pUserData)
  33460. {
  33461. ma_audio_worklet_thread_initialized_data* pParameters = (ma_audio_worklet_thread_initialized_data*)pUserData;
  33462. EmscriptenAudioWorkletNodeCreateOptions audioWorkletOptions;
  33463. int channels = 0;
  33464. size_t intermediaryBufferSizeInFrames;
  33465. int sampleRate;
  33466. if (success == EM_FALSE) {
  33467. pParameters->pDevice->webaudio.initResult = MA_ERROR;
  33468. ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks);
  33469. return;
  33470. }
  33471. /* The next step is to initialize the audio worklet node. */
  33472. MA_ZERO_OBJECT(&audioWorkletOptions);
  33473. /*
  33474. The way channel counts work with Web Audio is confusing. As far as I can tell, there's no way to know the channel
  33475. count from MediaStreamAudioSourceNode (what we use for capture)? The only way to have control is to configure an
  33476. output channel count on the capture side. This is slightly confusing for capture mode because intuitively you
  33477. wouldn't actually connect an output to an input-only node, but this is what we'll have to do in order to have
  33478. proper control over the channel count. In the capture case, we'll have to output silence to it's output node.
  33479. */
  33480. if (pParameters->pConfig->deviceType == ma_device_type_capture) {
  33481. channels = (int)((pParameters->pDescriptorCapture->channels > 0) ? pParameters->pDescriptorCapture->channels : MA_DEFAULT_CHANNELS);
  33482. audioWorkletOptions.numberOfInputs = 1;
  33483. } else {
  33484. channels = (int)((pParameters->pDescriptorPlayback->channels > 0) ? pParameters->pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS);
  33485. if (pParameters->pConfig->deviceType == ma_device_type_duplex) {
  33486. audioWorkletOptions.numberOfInputs = 1;
  33487. } else {
  33488. audioWorkletOptions.numberOfInputs = 0;
  33489. }
  33490. }
  33491. audioWorkletOptions.numberOfOutputs = 1;
  33492. audioWorkletOptions.outputChannelCounts = &channels;
  33493. /*
  33494. Now that we know the channel count to use we can allocate the intermediary buffer. The
  33495. intermediary buffer is used for interleaving and deinterleaving.
  33496. */
  33497. intermediaryBufferSizeInFrames = 128;
  33498. pParameters->pDevice->webaudio.pIntermediaryBuffer = (float*)ma_malloc(intermediaryBufferSizeInFrames * (ma_uint32)channels * sizeof(float), &pParameters->pDevice->pContext->allocationCallbacks);
  33499. if (pParameters->pDevice->webaudio.pIntermediaryBuffer == NULL) {
  33500. pParameters->pDevice->webaudio.initResult = MA_OUT_OF_MEMORY;
  33501. ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks);
  33502. return;
  33503. }
  33504. pParameters->pDevice->webaudio.audioWorklet = emscripten_create_wasm_audio_worklet_node(audioContext, "miniaudio", &audioWorkletOptions, &ma_audio_worklet_process_callback__webaudio, pParameters->pDevice);
  33505. /* With the audio worklet initialized we can now attach it to the graph. */
  33506. if (pParameters->pConfig->deviceType == ma_device_type_capture || pParameters->pConfig->deviceType == ma_device_type_duplex) {
  33507. ma_result attachmentResult = (ma_result)EM_ASM_INT({
  33508. var getUserMediaResult = 0;
  33509. var audioWorklet = emscriptenGetAudioObject($0);
  33510. var audioContext = emscriptenGetAudioObject($1);
  33511. navigator.mediaDevices.getUserMedia({audio:true, video:false})
  33512. .then(function(stream) {
  33513. audioContext.streamNode = audioContext.createMediaStreamSource(stream);
  33514. audioContext.streamNode.connect(audioWorklet);
  33515. audioWorklet.connect(audioContext.destination);
  33516. getUserMediaResult = 0; /* 0 = MA_SUCCESS */
  33517. })
  33518. .catch(function(error) {
  33519. console.log("navigator.mediaDevices.getUserMedia Failed: " + error);
  33520. getUserMediaResult = -1; /* -1 = MA_ERROR */
  33521. });
  33522. return getUserMediaResult;
  33523. }, pParameters->pDevice->webaudio.audioWorklet, audioContext);
  33524. if (attachmentResult != MA_SUCCESS) {
  33525. ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_ERROR, "Web Audio: Failed to connect capture node.");
  33526. emscripten_destroy_web_audio_node(pParameters->pDevice->webaudio.audioWorklet);
  33527. pParameters->pDevice->webaudio.initResult = attachmentResult;
  33528. ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks);
  33529. return;
  33530. }
  33531. }
  33532. /* If it's playback only we can now attach the worklet node to the graph. This has already been done for the duplex case. */
  33533. if (pParameters->pConfig->deviceType == ma_device_type_playback) {
  33534. ma_result attachmentResult = (ma_result)EM_ASM_INT({
  33535. var audioWorklet = emscriptenGetAudioObject($0);
  33536. var audioContext = emscriptenGetAudioObject($1);
  33537. audioWorklet.connect(audioContext.destination);
  33538. return 0; /* 0 = MA_SUCCESS */
  33539. }, pParameters->pDevice->webaudio.audioWorklet, audioContext);
  33540. if (attachmentResult != MA_SUCCESS) {
  33541. ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_ERROR, "Web Audio: Failed to connect playback node.");
  33542. pParameters->pDevice->webaudio.initResult = attachmentResult;
  33543. ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks);
  33544. return;
  33545. }
  33546. }
  33547. /* We need to update the descriptors so that they reflect the internal data format. Both capture and playback should be the same. */
  33548. sampleRate = EM_ASM_INT({ return emscriptenGetAudioObject($0).sampleRate; }, audioContext);
  33549. if (pParameters->pDescriptorCapture != NULL) {
  33550. pParameters->pDescriptorCapture->format = ma_format_f32;
  33551. pParameters->pDescriptorCapture->channels = (ma_uint32)channels;
  33552. pParameters->pDescriptorCapture->sampleRate = (ma_uint32)sampleRate;
  33553. ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pParameters->pDescriptorCapture->channelMap, ma_countof(pParameters->pDescriptorCapture->channelMap), pParameters->pDescriptorCapture->channels);
  33554. pParameters->pDescriptorCapture->periodSizeInFrames = intermediaryBufferSizeInFrames;
  33555. pParameters->pDescriptorCapture->periodCount = 1;
  33556. }
  33557. if (pParameters->pDescriptorPlayback != NULL) {
  33558. pParameters->pDescriptorPlayback->format = ma_format_f32;
  33559. pParameters->pDescriptorPlayback->channels = (ma_uint32)channels;
  33560. pParameters->pDescriptorPlayback->sampleRate = (ma_uint32)sampleRate;
  33561. ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pParameters->pDescriptorPlayback->channelMap, ma_countof(pParameters->pDescriptorPlayback->channelMap), pParameters->pDescriptorPlayback->channels);
  33562. pParameters->pDescriptorPlayback->periodSizeInFrames = intermediaryBufferSizeInFrames;
  33563. pParameters->pDescriptorPlayback->periodCount = 1;
  33564. }
  33565. /* At this point we're done and we can return. */
  33566. ma_log_postf(ma_device_get_log(pParameters->pDevice), MA_LOG_LEVEL_DEBUG, "AudioWorklets: Created worklet node: %d\n", pParameters->pDevice->webaudio.audioWorklet);
  33567. pParameters->pDevice->webaudio.initResult = MA_SUCCESS;
  33568. ma_free(pParameters, &pParameters->pDevice->pContext->allocationCallbacks);
  33569. }
  33570. static void ma_audio_worklet_thread_initialized__webaudio(EMSCRIPTEN_WEBAUDIO_T audioContext, EM_BOOL success, void* pUserData)
  33571. {
  33572. ma_audio_worklet_thread_initialized_data* pParameters = (ma_audio_worklet_thread_initialized_data*)pUserData;
  33573. WebAudioWorkletProcessorCreateOptions workletProcessorOptions;
  33574. MA_ASSERT(pParameters != NULL);
  33575. if (success == EM_FALSE) {
  33576. pParameters->pDevice->webaudio.initResult = MA_ERROR;
  33577. return;
  33578. }
  33579. MA_ZERO_OBJECT(&workletProcessorOptions);
  33580. 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? */
  33581. emscripten_create_wasm_audio_worklet_processor_async(audioContext, &workletProcessorOptions, ma_audio_worklet_processor_created__webaudio, pParameters);
  33582. }
  33583. #endif
  33584. static ma_result ma_device_init__webaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  33585. {
  33586. if (pConfig->deviceType == ma_device_type_loopback) {
  33587. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  33588. }
  33589. /* No exclusive mode with Web Audio. */
  33590. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  33591. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  33592. return MA_SHARE_MODE_NOT_SUPPORTED;
  33593. }
  33594. /*
  33595. With AudioWorklets we'll have just a single AudioContext. I'm not sure why I'm not doing this for ScriptProcessorNode so
  33596. it might be worthwhile to look into that as well.
  33597. */
  33598. #if defined(MA_USE_AUDIO_WORKLETS)
  33599. {
  33600. EmscriptenWebAudioCreateAttributes audioContextAttributes;
  33601. ma_audio_worklet_thread_initialized_data* pInitParameters;
  33602. void* pStackBuffer;
  33603. if (pConfig->performanceProfile == ma_performance_profile_conservative) {
  33604. audioContextAttributes.latencyHint = MA_WEBAUDIO_LATENCY_HINT_PLAYBACK;
  33605. } else {
  33606. audioContextAttributes.latencyHint = MA_WEBAUDIO_LATENCY_HINT_INTERACTIVE;
  33607. }
  33608. /*
  33609. In my testing, Firefox does not seem to capture audio data properly if the sample rate is set
  33610. to anything other than 48K. This does not seem to be the case for other browsers. For this reason,
  33611. if the device type is anything other than playback, we'll leave the sample rate as-is and let the
  33612. browser pick the appropriate rate for us.
  33613. */
  33614. if (pConfig->deviceType == ma_device_type_playback) {
  33615. audioContextAttributes.sampleRate = pDescriptorPlayback->sampleRate;
  33616. } else {
  33617. audioContextAttributes.sampleRate = 0;
  33618. }
  33619. /* 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. */
  33620. pDevice->webaudio.audioContext = emscripten_create_audio_context(&audioContextAttributes);
  33621. /*
  33622. With the context created we can now create the worklet. We can only have a single worklet per audio
  33623. context which means we'll need to craft this appropriately to handle duplex devices correctly.
  33624. */
  33625. /*
  33626. We now need to create a worker thread. This is a bit weird because we need to allocate our
  33627. own buffer for the thread's stack. The stack needs to be aligned to 16 bytes. I'm going to
  33628. allocate this on the heap to keep it simple.
  33629. */
  33630. pStackBuffer = ma_aligned_malloc(MA_AUDIO_WORKLETS_THREAD_STACK_SIZE, 16, &pDevice->pContext->allocationCallbacks);
  33631. if (pStackBuffer == NULL) {
  33632. emscripten_destroy_audio_context(pDevice->webaudio.audioContext);
  33633. return MA_OUT_OF_MEMORY;
  33634. }
  33635. /* Our thread initialization parameters need to be allocated on the heap so they don't go out of scope. */
  33636. pInitParameters = (ma_audio_worklet_thread_initialized_data*)ma_malloc(sizeof(*pInitParameters), &pDevice->pContext->allocationCallbacks);
  33637. if (pInitParameters == NULL) {
  33638. ma_free(pStackBuffer, &pDevice->pContext->allocationCallbacks);
  33639. emscripten_destroy_audio_context(pDevice->webaudio.audioContext);
  33640. return MA_OUT_OF_MEMORY;
  33641. }
  33642. pInitParameters->pDevice = pDevice;
  33643. pInitParameters->pConfig = pConfig;
  33644. pInitParameters->pDescriptorPlayback = pDescriptorPlayback;
  33645. pInitParameters->pDescriptorCapture = pDescriptorCapture;
  33646. /*
  33647. We need to flag the device as not yet initialized so we can wait on it later. Unfortunately all of
  33648. the Emscripten WebAudio stuff is asynchronous.
  33649. */
  33650. pDevice->webaudio.initResult = MA_BUSY;
  33651. {
  33652. emscripten_start_wasm_audio_worklet_thread_async(pDevice->webaudio.audioContext, pStackBuffer, MA_AUDIO_WORKLETS_THREAD_STACK_SIZE, ma_audio_worklet_thread_initialized__webaudio, pInitParameters);
  33653. }
  33654. while (pDevice->webaudio.initResult == MA_BUSY) { emscripten_sleep(1); } /* We must wait for initialization to complete. We're just spinning here. The emscripten_sleep() call is why we need to build with `-sASYNCIFY`. */
  33655. /* Initialization is now complete. Descriptors were updated when the worklet was initialized. */
  33656. if (pDevice->webaudio.initResult != MA_SUCCESS) {
  33657. ma_free(pStackBuffer, &pDevice->pContext->allocationCallbacks);
  33658. emscripten_destroy_audio_context(pDevice->webaudio.audioContext);
  33659. return pDevice->webaudio.initResult;
  33660. }
  33661. /* We need to add an entry to the miniaudio.devices list on the JS side so we can do some JS/C interop. */
  33662. pDevice->webaudio.deviceIndex = EM_ASM_INT({
  33663. return miniaudio.track_device({
  33664. webaudio: emscriptenGetAudioObject($0),
  33665. state: 1 /* 1 = ma_device_state_stopped */
  33666. });
  33667. }, pDevice->webaudio.audioContext);
  33668. return MA_SUCCESS;
  33669. }
  33670. #else
  33671. {
  33672. /* ScriptProcessorNode. This path requires us to do almost everything in JS, but we'll do as much as we can in C. */
  33673. ma_uint32 deviceIndex;
  33674. ma_uint32 channels;
  33675. ma_uint32 sampleRate;
  33676. ma_uint32 periodSizeInFrames;
  33677. /* The channel count will depend on the device type. If it's a capture, use it's, otherwise use the playback side. */
  33678. if (pConfig->deviceType == ma_device_type_capture) {
  33679. channels = (pDescriptorCapture->channels > 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS;
  33680. } else {
  33681. channels = (pDescriptorPlayback->channels > 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS;
  33682. }
  33683. /*
  33684. When testing in Firefox, I've seen it where capture mode fails if the sample rate is changed to anything other than it's
  33685. native rate. For this reason we're leaving the sample rate untouched for capture devices.
  33686. */
  33687. if (pConfig->deviceType == ma_device_type_playback) {
  33688. sampleRate = pDescriptorPlayback->sampleRate;
  33689. } else {
  33690. sampleRate = 0; /* Let the browser decide when capturing. */
  33691. }
  33692. /* The period size needs to be a power of 2. */
  33693. if (pConfig->deviceType == ma_device_type_capture) {
  33694. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__webaudio(pDescriptorCapture, sampleRate, pConfig->performanceProfile);
  33695. } else {
  33696. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__webaudio(pDescriptorPlayback, sampleRate, pConfig->performanceProfile);
  33697. }
  33698. /* We need an intermediary buffer for doing interleaving and deinterleaving. */
  33699. pDevice->webaudio.pIntermediaryBuffer = (float*)ma_malloc(periodSizeInFrames * channels * sizeof(float), &pDevice->pContext->allocationCallbacks);
  33700. if (pDevice->webaudio.pIntermediaryBuffer == NULL) {
  33701. return MA_OUT_OF_MEMORY;
  33702. }
  33703. deviceIndex = EM_ASM_INT({
  33704. var deviceType = $0;
  33705. var channels = $1;
  33706. var sampleRate = $2;
  33707. var bufferSize = $3;
  33708. var pIntermediaryBuffer = $4;
  33709. var pDevice = $5;
  33710. if (typeof(window.miniaudio) === 'undefined') {
  33711. return -1; /* Context not initialized. */
  33712. }
  33713. var device = {};
  33714. /* First thing we need is an AudioContext. */
  33715. var audioContextOptions = {};
  33716. if (deviceType == window.miniaudio.device_type.playback && sampleRate != 0) {
  33717. audioContextOptions.sampleRate = sampleRate;
  33718. }
  33719. device.webaudio = new (window.AudioContext || window.webkitAudioContext)(audioContextOptions);
  33720. device.webaudio.suspend(); /* The AudioContext must be created in a suspended state. */
  33721. device.state = window.miniaudio.device_state.stopped;
  33722. /*
  33723. We need to create a ScriptProcessorNode. The channel situation is the same as the AudioWorklet path in that we
  33724. need to specify an output and configure the channel count there.
  33725. */
  33726. var channelCountIn = 0;
  33727. var channelCountOut = channels;
  33728. if (deviceType != window.miniaudio.device_type.playback) {
  33729. channelCountIn = channels;
  33730. }
  33731. device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, channelCountIn, channelCountOut);
  33732. /* The node processing callback. */
  33733. device.scriptNode.onaudioprocess = function(e) {
  33734. if (device.intermediaryBufferView == null || device.intermediaryBufferView.length == 0) {
  33735. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, pIntermediaryBuffer, bufferSize * channels);
  33736. }
  33737. /* Do the capture side first. */
  33738. if (deviceType == miniaudio.device_type.capture || deviceType == miniaudio.device_type.duplex) {
  33739. /* The data must be interleaved before being processed miniaudio. */
  33740. for (var iChannel = 0; iChannel < channels; iChannel += 1) {
  33741. var inputBuffer = e.inputBuffer.getChannelData(iChannel);
  33742. var intermediaryBuffer = device.intermediaryBufferView;
  33743. for (var iFrame = 0; iFrame < bufferSize; iFrame += 1) {
  33744. intermediaryBuffer[iFrame*channels + iChannel] = inputBuffer[iFrame];
  33745. }
  33746. }
  33747. _ma_device_process_pcm_frames_capture__webaudio(pDevice, bufferSize, pIntermediaryBuffer);
  33748. }
  33749. if (deviceType == miniaudio.device_type.playback || deviceType == miniaudio.device_type.duplex) {
  33750. _ma_device_process_pcm_frames_playback__webaudio(pDevice, bufferSize, pIntermediaryBuffer);
  33751. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  33752. var outputBuffer = e.outputBuffer.getChannelData(iChannel);
  33753. var intermediaryBuffer = device.intermediaryBufferView;
  33754. for (var iFrame = 0; iFrame < bufferSize; iFrame += 1) {
  33755. outputBuffer[iFrame] = intermediaryBuffer[iFrame*channels + iChannel];
  33756. }
  33757. }
  33758. } else {
  33759. /* It's a capture-only device. Make sure the output is silenced. */
  33760. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  33761. e.outputBuffer.getChannelData(iChannel).fill(0.0);
  33762. }
  33763. }
  33764. };
  33765. /* Now we need to connect our node to the graph. */
  33766. if (deviceType == miniaudio.device_type.capture || deviceType == miniaudio.device_type.duplex) {
  33767. navigator.mediaDevices.getUserMedia({audio:true, video:false})
  33768. .then(function(stream) {
  33769. device.streamNode = device.webaudio.createMediaStreamSource(stream);
  33770. device.streamNode.connect(device.scriptNode);
  33771. device.scriptNode.connect(device.webaudio.destination);
  33772. })
  33773. .catch(function(error) {
  33774. console.log("Failed to get user media: " + error);
  33775. });
  33776. }
  33777. if (deviceType == miniaudio.device_type.playback) {
  33778. device.scriptNode.connect(device.webaudio.destination);
  33779. }
  33780. return miniaudio.track_device(device);
  33781. }, pConfig->deviceType, channels, sampleRate, periodSizeInFrames, pDevice->webaudio.pIntermediaryBuffer, pDevice);
  33782. if (deviceIndex < 0) {
  33783. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  33784. }
  33785. pDevice->webaudio.deviceIndex = deviceIndex;
  33786. /* Grab the sample rate from the audio context directly. */
  33787. sampleRate = (ma_uint32)EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex);
  33788. if (pDescriptorCapture != NULL) {
  33789. pDescriptorCapture->format = ma_format_f32;
  33790. pDescriptorCapture->channels = channels;
  33791. pDescriptorCapture->sampleRate = sampleRate;
  33792. ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  33793. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  33794. pDescriptorCapture->periodCount = 1;
  33795. }
  33796. if (pDescriptorPlayback != NULL) {
  33797. pDescriptorPlayback->format = ma_format_f32;
  33798. pDescriptorPlayback->channels = channels;
  33799. pDescriptorPlayback->sampleRate = sampleRate;
  33800. ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  33801. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  33802. pDescriptorPlayback->periodCount = 1;
  33803. }
  33804. return MA_SUCCESS;
  33805. }
  33806. #endif
  33807. }
  33808. static ma_result ma_device_start__webaudio(ma_device* pDevice)
  33809. {
  33810. MA_ASSERT(pDevice != NULL);
  33811. EM_ASM({
  33812. var device = miniaudio.get_device_by_index($0);
  33813. device.webaudio.resume();
  33814. device.state = miniaudio.device_state.started;
  33815. }, pDevice->webaudio.deviceIndex);
  33816. return MA_SUCCESS;
  33817. }
  33818. static ma_result ma_device_stop__webaudio(ma_device* pDevice)
  33819. {
  33820. MA_ASSERT(pDevice != NULL);
  33821. /*
  33822. From the WebAudio API documentation for AudioContext.suspend():
  33823. Suspends the progression of AudioContext's currentTime, allows any current context processing blocks that are already processed to be played to the
  33824. destination, and then allows the system to release its claim on audio hardware.
  33825. 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
  33826. do any kind of explicit draining.
  33827. */
  33828. EM_ASM({
  33829. var device = miniaudio.get_device_by_index($0);
  33830. device.webaudio.suspend();
  33831. device.state = miniaudio.device_state.stopped;
  33832. }, pDevice->webaudio.deviceIndex);
  33833. ma_device__on_notification_stopped(pDevice);
  33834. return MA_SUCCESS;
  33835. }
  33836. static ma_result ma_context_uninit__webaudio(ma_context* pContext)
  33837. {
  33838. MA_ASSERT(pContext != NULL);
  33839. MA_ASSERT(pContext->backend == ma_backend_webaudio);
  33840. (void)pContext; /* Unused. */
  33841. /* Remove the global miniaudio object from window if there are no more references to it. */
  33842. EM_ASM({
  33843. if (typeof(window.miniaudio) !== 'undefined') {
  33844. window.miniaudio.referenceCount -= 1;
  33845. if (window.miniaudio.referenceCount === 0) {
  33846. delete window.miniaudio;
  33847. }
  33848. }
  33849. });
  33850. return MA_SUCCESS;
  33851. }
  33852. static ma_result ma_context_init__webaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  33853. {
  33854. int resultFromJS;
  33855. MA_ASSERT(pContext != NULL);
  33856. (void)pConfig; /* Unused. */
  33857. /* Here is where our global JavaScript object is initialized. */
  33858. resultFromJS = EM_ASM_INT({
  33859. if (typeof window === 'undefined' || (window.AudioContext || window.webkitAudioContext) === undefined) {
  33860. return 0; /* Web Audio not supported. */
  33861. }
  33862. if (typeof(window.miniaudio) === 'undefined') {
  33863. window.miniaudio = {
  33864. referenceCount: 0
  33865. };
  33866. /* Device types. */
  33867. window.miniaudio.device_type = {};
  33868. window.miniaudio.device_type.playback = $0;
  33869. window.miniaudio.device_type.capture = $1;
  33870. window.miniaudio.device_type.duplex = $2;
  33871. /* Device states. */
  33872. window.miniaudio.device_state = {};
  33873. window.miniaudio.device_state.stopped = $3;
  33874. window.miniaudio.device_state.started = $4;
  33875. /* Device cache for mapping devices to indexes for JavaScript/C interop. */
  33876. miniaudio.devices = [];
  33877. miniaudio.track_device = function(device) {
  33878. /* Try inserting into a free slot first. */
  33879. for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) {
  33880. if (miniaudio.devices[iDevice] == null) {
  33881. miniaudio.devices[iDevice] = device;
  33882. return iDevice;
  33883. }
  33884. }
  33885. /* Getting here means there is no empty slots in the array so we just push to the end. */
  33886. miniaudio.devices.push(device);
  33887. return miniaudio.devices.length - 1;
  33888. };
  33889. miniaudio.untrack_device_by_index = function(deviceIndex) {
  33890. /* We just set the device's slot to null. The slot will get reused in the next call to ma_track_device. */
  33891. miniaudio.devices[deviceIndex] = null;
  33892. /* Trim the array if possible. */
  33893. while (miniaudio.devices.length > 0) {
  33894. if (miniaudio.devices[miniaudio.devices.length-1] == null) {
  33895. miniaudio.devices.pop();
  33896. } else {
  33897. break;
  33898. }
  33899. }
  33900. };
  33901. miniaudio.untrack_device = function(device) {
  33902. for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) {
  33903. if (miniaudio.devices[iDevice] == device) {
  33904. return miniaudio.untrack_device_by_index(iDevice);
  33905. }
  33906. }
  33907. };
  33908. miniaudio.get_device_by_index = function(deviceIndex) {
  33909. return miniaudio.devices[deviceIndex];
  33910. };
  33911. miniaudio.unlock_event_types = (function(){
  33912. return ['touchend', 'click'];
  33913. })();
  33914. miniaudio.unlock = function() {
  33915. for(var i = 0; i < miniaudio.devices.length; ++i) {
  33916. var device = miniaudio.devices[i];
  33917. if (device != null && device.webaudio != null && device.state === 2 /* ma_device_state_started */) {
  33918. device.webaudio.resume();
  33919. }
  33920. }
  33921. miniaudio.unlock_event_types.map(function(event_type) {
  33922. document.removeEventListener(event_type, miniaudio.unlock, true);
  33923. });
  33924. };
  33925. miniaudio.unlock_event_types.map(function(event_type) {
  33926. document.addEventListener(event_type, miniaudio.unlock, true);
  33927. });
  33928. }
  33929. window.miniaudio.referenceCount += 1;
  33930. return 1;
  33931. }, ma_device_type_playback, ma_device_type_capture, ma_device_type_duplex, ma_device_state_stopped, ma_device_state_started);
  33932. if (resultFromJS != 1) {
  33933. return MA_FAILED_TO_INIT_BACKEND;
  33934. }
  33935. pCallbacks->onContextInit = ma_context_init__webaudio;
  33936. pCallbacks->onContextUninit = ma_context_uninit__webaudio;
  33937. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__webaudio;
  33938. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__webaudio;
  33939. pCallbacks->onDeviceInit = ma_device_init__webaudio;
  33940. pCallbacks->onDeviceUninit = ma_device_uninit__webaudio;
  33941. pCallbacks->onDeviceStart = ma_device_start__webaudio;
  33942. pCallbacks->onDeviceStop = ma_device_stop__webaudio;
  33943. pCallbacks->onDeviceRead = NULL; /* Not needed because WebAudio is asynchronous. */
  33944. pCallbacks->onDeviceWrite = NULL; /* Not needed because WebAudio is asynchronous. */
  33945. pCallbacks->onDeviceDataLoop = NULL; /* Not needed because WebAudio is asynchronous. */
  33946. return MA_SUCCESS;
  33947. }
  33948. #endif /* Web Audio */
  33949. static ma_bool32 ma__is_channel_map_valid(const ma_channel* pChannelMap, ma_uint32 channels)
  33950. {
  33951. /* A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. */
  33952. if (pChannelMap != NULL && pChannelMap[0] != MA_CHANNEL_NONE) {
  33953. ma_uint32 iChannel;
  33954. if (channels == 0 || channels > MA_MAX_CHANNELS) {
  33955. return MA_FALSE; /* Channel count out of range. */
  33956. }
  33957. /* A channel cannot be present in the channel map more than once. */
  33958. for (iChannel = 0; iChannel < channels; ++iChannel) {
  33959. ma_uint32 jChannel;
  33960. for (jChannel = iChannel + 1; jChannel < channels; ++jChannel) {
  33961. if (pChannelMap[iChannel] == pChannelMap[jChannel]) {
  33962. return MA_FALSE;
  33963. }
  33964. }
  33965. }
  33966. }
  33967. return MA_TRUE;
  33968. }
  33969. static ma_bool32 ma_context_is_backend_asynchronous(ma_context* pContext)
  33970. {
  33971. MA_ASSERT(pContext != NULL);
  33972. if (pContext->callbacks.onDeviceRead == NULL && pContext->callbacks.onDeviceWrite == NULL) {
  33973. if (pContext->callbacks.onDeviceDataLoop == NULL) {
  33974. return MA_TRUE;
  33975. } else {
  33976. return MA_FALSE;
  33977. }
  33978. } else {
  33979. return MA_FALSE;
  33980. }
  33981. }
  33982. static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType)
  33983. {
  33984. ma_result result;
  33985. MA_ASSERT(pDevice != NULL);
  33986. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  33987. if (pDevice->capture.format == ma_format_unknown) {
  33988. pDevice->capture.format = pDevice->capture.internalFormat;
  33989. }
  33990. if (pDevice->capture.channels == 0) {
  33991. pDevice->capture.channels = pDevice->capture.internalChannels;
  33992. }
  33993. if (pDevice->capture.channelMap[0] == MA_CHANNEL_NONE) {
  33994. MA_ASSERT(pDevice->capture.channels <= MA_MAX_CHANNELS);
  33995. if (pDevice->capture.internalChannels == pDevice->capture.channels) {
  33996. ma_channel_map_copy(pDevice->capture.channelMap, pDevice->capture.internalChannelMap, pDevice->capture.channels);
  33997. } else {
  33998. if (pDevice->capture.channelMixMode == ma_channel_mix_mode_simple) {
  33999. ma_channel_map_init_blank(pDevice->capture.channelMap, pDevice->capture.channels);
  34000. } else {
  34001. ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pDevice->capture.channels);
  34002. }
  34003. }
  34004. }
  34005. }
  34006. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34007. if (pDevice->playback.format == ma_format_unknown) {
  34008. pDevice->playback.format = pDevice->playback.internalFormat;
  34009. }
  34010. if (pDevice->playback.channels == 0) {
  34011. pDevice->playback.channels = pDevice->playback.internalChannels;
  34012. }
  34013. if (pDevice->playback.channelMap[0] == MA_CHANNEL_NONE) {
  34014. MA_ASSERT(pDevice->playback.channels <= MA_MAX_CHANNELS);
  34015. if (pDevice->playback.internalChannels == pDevice->playback.channels) {
  34016. ma_channel_map_copy(pDevice->playback.channelMap, pDevice->playback.internalChannelMap, pDevice->playback.channels);
  34017. } else {
  34018. if (pDevice->playback.channelMixMode == ma_channel_mix_mode_simple) {
  34019. ma_channel_map_init_blank(pDevice->playback.channelMap, pDevice->playback.channels);
  34020. } else {
  34021. ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pDevice->playback.channels);
  34022. }
  34023. }
  34024. }
  34025. }
  34026. if (pDevice->sampleRate == 0) {
  34027. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34028. pDevice->sampleRate = pDevice->capture.internalSampleRate;
  34029. } else {
  34030. pDevice->sampleRate = pDevice->playback.internalSampleRate;
  34031. }
  34032. }
  34033. /* Data converters. */
  34034. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34035. /* Converting from internal device format to client format. */
  34036. ma_data_converter_config converterConfig = ma_data_converter_config_init_default();
  34037. converterConfig.formatIn = pDevice->capture.internalFormat;
  34038. converterConfig.channelsIn = pDevice->capture.internalChannels;
  34039. converterConfig.sampleRateIn = pDevice->capture.internalSampleRate;
  34040. converterConfig.pChannelMapIn = pDevice->capture.internalChannelMap;
  34041. converterConfig.formatOut = pDevice->capture.format;
  34042. converterConfig.channelsOut = pDevice->capture.channels;
  34043. converterConfig.sampleRateOut = pDevice->sampleRate;
  34044. converterConfig.pChannelMapOut = pDevice->capture.channelMap;
  34045. converterConfig.channelMixMode = pDevice->capture.channelMixMode;
  34046. converterConfig.calculateLFEFromSpatialChannels = pDevice->capture.calculateLFEFromSpatialChannels;
  34047. converterConfig.allowDynamicSampleRate = MA_FALSE;
  34048. converterConfig.resampling.algorithm = pDevice->resampling.algorithm;
  34049. converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder;
  34050. converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable;
  34051. converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData;
  34052. /* Make sure the old converter is uninitialized first. */
  34053. if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) {
  34054. ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks);
  34055. }
  34056. result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->capture.converter);
  34057. if (result != MA_SUCCESS) {
  34058. return result;
  34059. }
  34060. }
  34061. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34062. /* Converting from client format to device format. */
  34063. ma_data_converter_config converterConfig = ma_data_converter_config_init_default();
  34064. converterConfig.formatIn = pDevice->playback.format;
  34065. converterConfig.channelsIn = pDevice->playback.channels;
  34066. converterConfig.sampleRateIn = pDevice->sampleRate;
  34067. converterConfig.pChannelMapIn = pDevice->playback.channelMap;
  34068. converterConfig.formatOut = pDevice->playback.internalFormat;
  34069. converterConfig.channelsOut = pDevice->playback.internalChannels;
  34070. converterConfig.sampleRateOut = pDevice->playback.internalSampleRate;
  34071. converterConfig.pChannelMapOut = pDevice->playback.internalChannelMap;
  34072. converterConfig.channelMixMode = pDevice->playback.channelMixMode;
  34073. converterConfig.calculateLFEFromSpatialChannels = pDevice->playback.calculateLFEFromSpatialChannels;
  34074. converterConfig.allowDynamicSampleRate = MA_FALSE;
  34075. converterConfig.resampling.algorithm = pDevice->resampling.algorithm;
  34076. converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder;
  34077. converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable;
  34078. converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData;
  34079. /* Make sure the old converter is uninitialized first. */
  34080. if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) {
  34081. ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks);
  34082. }
  34083. result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->playback.converter);
  34084. if (result != MA_SUCCESS) {
  34085. return result;
  34086. }
  34087. }
  34088. /*
  34089. If the device is doing playback (ma_device_type_playback or ma_device_type_duplex), there's
  34090. a couple of situations where we'll need a heap allocated cache.
  34091. The first is a duplex device for backends that use a callback for data delivery. The reason
  34092. this is needed is that the input stage needs to have a buffer to place the input data while it
  34093. waits for the playback stage, after which the miniaudio data callback will get fired. This is
  34094. not needed for backends that use a blocking API because miniaudio manages temporary buffers on
  34095. the stack to achieve this.
  34096. The other situation is when the data converter does not have the ability to query the number
  34097. of input frames that are required in order to process a given number of output frames. When
  34098. performing data conversion, it's useful if miniaudio know exactly how many frames it needs
  34099. from the client in order to generate a given number of output frames. This way, only exactly
  34100. the number of frames are needed to be read from the client which means no cache is necessary.
  34101. On the other hand, if miniaudio doesn't know how many frames to read, it is forced to read
  34102. in fixed sized chunks and then cache any residual unused input frames, those of which will be
  34103. processed at a later stage.
  34104. */
  34105. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34106. ma_uint64 unused;
  34107. pDevice->playback.inputCacheConsumed = 0;
  34108. pDevice->playback.inputCacheRemaining = 0;
  34109. if (pDevice->type == ma_device_type_duplex || /* Duplex. backend may decide to use ma_device_handle_backend_data_callback() which will require this cache. */
  34110. ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, 1, &unused) != MA_SUCCESS) /* Data conversion required input frame calculation not supported. */
  34111. {
  34112. /* We need a heap allocated cache. We want to size this based on the period size. */
  34113. void* pNewInputCache;
  34114. ma_uint64 newInputCacheCap;
  34115. ma_uint64 newInputCacheSizeInBytes;
  34116. newInputCacheCap = ma_calculate_frame_count_after_resampling(pDevice->playback.internalSampleRate, pDevice->sampleRate, pDevice->playback.internalPeriodSizeInFrames);
  34117. newInputCacheSizeInBytes = newInputCacheCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  34118. if (newInputCacheSizeInBytes > MA_SIZE_MAX) {
  34119. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34120. pDevice->playback.pInputCache = NULL;
  34121. pDevice->playback.inputCacheCap = 0;
  34122. return MA_OUT_OF_MEMORY; /* Allocation too big. Should never hit this, but makes the cast below safer for 32-bit builds. */
  34123. }
  34124. pNewInputCache = ma_realloc(pDevice->playback.pInputCache, (size_t)newInputCacheSizeInBytes, &pDevice->pContext->allocationCallbacks);
  34125. if (pNewInputCache == NULL) {
  34126. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34127. pDevice->playback.pInputCache = NULL;
  34128. pDevice->playback.inputCacheCap = 0;
  34129. return MA_OUT_OF_MEMORY;
  34130. }
  34131. pDevice->playback.pInputCache = pNewInputCache;
  34132. pDevice->playback.inputCacheCap = newInputCacheCap;
  34133. } else {
  34134. /* 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. */
  34135. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34136. pDevice->playback.pInputCache = NULL;
  34137. pDevice->playback.inputCacheCap = 0;
  34138. }
  34139. }
  34140. return MA_SUCCESS;
  34141. }
  34142. 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)
  34143. {
  34144. ma_result result;
  34145. if (pDevice == NULL) {
  34146. return MA_INVALID_ARGS;
  34147. }
  34148. /* Capture. */
  34149. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34150. if (ma_device_descriptor_is_valid(pDescriptorCapture) == MA_FALSE) {
  34151. return MA_INVALID_ARGS;
  34152. }
  34153. pDevice->capture.internalFormat = pDescriptorCapture->format;
  34154. pDevice->capture.internalChannels = pDescriptorCapture->channels;
  34155. pDevice->capture.internalSampleRate = pDescriptorCapture->sampleRate;
  34156. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  34157. pDevice->capture.internalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  34158. pDevice->capture.internalPeriods = pDescriptorCapture->periodCount;
  34159. if (pDevice->capture.internalPeriodSizeInFrames == 0) {
  34160. pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorCapture->periodSizeInMilliseconds, pDescriptorCapture->sampleRate);
  34161. }
  34162. }
  34163. /* Playback. */
  34164. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34165. if (ma_device_descriptor_is_valid(pDescriptorPlayback) == MA_FALSE) {
  34166. return MA_INVALID_ARGS;
  34167. }
  34168. pDevice->playback.internalFormat = pDescriptorPlayback->format;
  34169. pDevice->playback.internalChannels = pDescriptorPlayback->channels;
  34170. pDevice->playback.internalSampleRate = pDescriptorPlayback->sampleRate;
  34171. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  34172. pDevice->playback.internalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  34173. pDevice->playback.internalPeriods = pDescriptorPlayback->periodCount;
  34174. if (pDevice->playback.internalPeriodSizeInFrames == 0) {
  34175. pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorPlayback->periodSizeInMilliseconds, pDescriptorPlayback->sampleRate);
  34176. }
  34177. }
  34178. /*
  34179. 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.
  34180. For loopback devices, we need to retrieve the name of the playback device.
  34181. */
  34182. {
  34183. ma_device_info deviceInfo;
  34184. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  34185. result = ma_device_get_info(pDevice, (deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo);
  34186. if (result == MA_SUCCESS) {
  34187. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1);
  34188. } else {
  34189. /* We failed to retrieve the device info. Fall back to a default name. */
  34190. if (pDescriptorCapture->pDeviceID == NULL) {
  34191. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  34192. } else {
  34193. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1);
  34194. }
  34195. }
  34196. }
  34197. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  34198. result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo);
  34199. if (result == MA_SUCCESS) {
  34200. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1);
  34201. } else {
  34202. /* We failed to retrieve the device info. Fall back to a default name. */
  34203. if (pDescriptorPlayback->pDeviceID == NULL) {
  34204. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  34205. } else {
  34206. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1);
  34207. }
  34208. }
  34209. }
  34210. }
  34211. /* Update data conversion. */
  34212. return ma_device__post_init_setup(pDevice, deviceType); /* TODO: Should probably rename ma_device__post_init_setup() to something better. */
  34213. }
  34214. static ma_thread_result MA_THREADCALL ma_worker_thread(void* pData)
  34215. {
  34216. ma_device* pDevice = (ma_device*)pData;
  34217. #ifdef MA_WIN32
  34218. HRESULT CoInitializeResult;
  34219. #endif
  34220. MA_ASSERT(pDevice != NULL);
  34221. #ifdef MA_WIN32
  34222. CoInitializeResult = ma_CoInitializeEx(pDevice->pContext, NULL, MA_COINIT_VALUE);
  34223. #endif
  34224. /*
  34225. When the device is being initialized it's initial state is set to ma_device_state_uninitialized. Before returning from
  34226. ma_device_init(), the state needs to be set to something valid. In miniaudio the device's default state immediately
  34227. after initialization is stopped, so therefore we need to mark the device as such. miniaudio will wait on the worker
  34228. thread to signal an event to know when the worker thread is ready for action.
  34229. */
  34230. ma_device__set_state(pDevice, ma_device_state_stopped);
  34231. ma_event_signal(&pDevice->stopEvent);
  34232. for (;;) { /* <-- This loop just keeps the thread alive. The main audio loop is inside. */
  34233. ma_result startResult;
  34234. ma_result stopResult; /* <-- This will store the result from onDeviceStop(). If it returns an error, we don't fire the stopped notification callback. */
  34235. /* We wait on an event to know when something has requested that the device be started and the main loop entered. */
  34236. ma_event_wait(&pDevice->wakeupEvent);
  34237. /* Default result code. */
  34238. pDevice->workResult = MA_SUCCESS;
  34239. /* If the reason for the wake up is that we are terminating, just break from the loop. */
  34240. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  34241. break;
  34242. }
  34243. /*
  34244. Getting to this point means the device is wanting to get started. The function that has requested that the device
  34245. be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event
  34246. in both the success and error case. It's important that the state of the device is set _before_ signaling the event.
  34247. */
  34248. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_starting);
  34249. /* If the device has a start callback, start it now. */
  34250. if (pDevice->pContext->callbacks.onDeviceStart != NULL) {
  34251. startResult = pDevice->pContext->callbacks.onDeviceStart(pDevice);
  34252. } else {
  34253. startResult = MA_SUCCESS;
  34254. }
  34255. /*
  34256. If starting was not successful we'll need to loop back to the start and wait for something
  34257. to happen (pDevice->wakeupEvent).
  34258. */
  34259. if (startResult != MA_SUCCESS) {
  34260. pDevice->workResult = startResult;
  34261. ma_event_signal(&pDevice->startEvent); /* <-- Always signal the start event so ma_device_start() can return as it'll be waiting on it. */
  34262. continue;
  34263. }
  34264. /* Make sure the state is set appropriately. */
  34265. 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. */
  34266. ma_event_signal(&pDevice->startEvent);
  34267. ma_device__on_notification_started(pDevice);
  34268. if (pDevice->pContext->callbacks.onDeviceDataLoop != NULL) {
  34269. pDevice->pContext->callbacks.onDeviceDataLoop(pDevice);
  34270. } else {
  34271. /* The backend is not using a custom main loop implementation, so now fall back to the blocking read-write implementation. */
  34272. ma_device_audio_thread__default_read_write(pDevice);
  34273. }
  34274. /* Getting here means we have broken from the main loop which happens the application has requested that device be stopped. */
  34275. if (pDevice->pContext->callbacks.onDeviceStop != NULL) {
  34276. stopResult = pDevice->pContext->callbacks.onDeviceStop(pDevice);
  34277. } else {
  34278. stopResult = MA_SUCCESS; /* No stop callback with the backend. Just assume successful. */
  34279. }
  34280. /*
  34281. After the device has stopped, make sure an event is posted. Don't post a stopped event if
  34282. stopping failed. This can happen on some backends when the underlying stream has been
  34283. stopped due to the device being physically unplugged or disabled via an OS setting.
  34284. */
  34285. if (stopResult == MA_SUCCESS) {
  34286. ma_device__on_notification_stopped(pDevice);
  34287. }
  34288. /* If we stopped because the device has been uninitialized, abort now. */
  34289. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  34290. break;
  34291. }
  34292. /* 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. */
  34293. ma_device__set_state(pDevice, ma_device_state_stopped);
  34294. ma_event_signal(&pDevice->stopEvent);
  34295. }
  34296. #ifdef MA_WIN32
  34297. if (CoInitializeResult == S_OK) {
  34298. ma_CoUninitialize(pDevice->pContext);
  34299. }
  34300. #endif
  34301. return (ma_thread_result)0;
  34302. }
  34303. /* Helper for determining whether or not the given device is initialized. */
  34304. static ma_bool32 ma_device__is_initialized(ma_device* pDevice)
  34305. {
  34306. if (pDevice == NULL) {
  34307. return MA_FALSE;
  34308. }
  34309. return ma_device_get_state(pDevice) != ma_device_state_uninitialized;
  34310. }
  34311. #ifdef MA_WIN32
  34312. static ma_result ma_context_uninit_backend_apis__win32(ma_context* pContext)
  34313. {
  34314. /* For some reason UWP complains when CoUninitialize() is called. I'm just not going to call it on UWP. */
  34315. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  34316. if (pContext->win32.CoInitializeResult == S_OK) {
  34317. ma_CoUninitialize(pContext);
  34318. }
  34319. #if defined(MA_WIN32_DESKTOP)
  34320. ma_dlclose(ma_context_get_log(pContext), pContext->win32.hUser32DLL);
  34321. ma_dlclose(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL);
  34322. #endif
  34323. ma_dlclose(ma_context_get_log(pContext), pContext->win32.hOle32DLL);
  34324. #else
  34325. (void)pContext;
  34326. #endif
  34327. return MA_SUCCESS;
  34328. }
  34329. static ma_result ma_context_init_backend_apis__win32(ma_context* pContext)
  34330. {
  34331. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  34332. #if defined(MA_WIN32_DESKTOP)
  34333. /* User32.dll */
  34334. pContext->win32.hUser32DLL = ma_dlopen(ma_context_get_log(pContext), "user32.dll");
  34335. if (pContext->win32.hUser32DLL == NULL) {
  34336. return MA_FAILED_TO_INIT_BACKEND;
  34337. }
  34338. pContext->win32.GetForegroundWindow = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hUser32DLL, "GetForegroundWindow");
  34339. pContext->win32.GetDesktopWindow = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hUser32DLL, "GetDesktopWindow");
  34340. /* Advapi32.dll */
  34341. pContext->win32.hAdvapi32DLL = ma_dlopen(ma_context_get_log(pContext), "advapi32.dll");
  34342. if (pContext->win32.hAdvapi32DLL == NULL) {
  34343. return MA_FAILED_TO_INIT_BACKEND;
  34344. }
  34345. pContext->win32.RegOpenKeyExA = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL, "RegOpenKeyExA");
  34346. pContext->win32.RegCloseKey = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL, "RegCloseKey");
  34347. pContext->win32.RegQueryValueExA = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hAdvapi32DLL, "RegQueryValueExA");
  34348. #endif
  34349. /* Ole32.dll */
  34350. pContext->win32.hOle32DLL = ma_dlopen(ma_context_get_log(pContext), "ole32.dll");
  34351. if (pContext->win32.hOle32DLL == NULL) {
  34352. return MA_FAILED_TO_INIT_BACKEND;
  34353. }
  34354. pContext->win32.CoInitialize = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoInitialize");
  34355. pContext->win32.CoInitializeEx = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoInitializeEx");
  34356. pContext->win32.CoUninitialize = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoUninitialize");
  34357. pContext->win32.CoCreateInstance = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoCreateInstance");
  34358. pContext->win32.CoTaskMemFree = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "CoTaskMemFree");
  34359. pContext->win32.PropVariantClear = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "PropVariantClear");
  34360. pContext->win32.StringFromGUID2 = (ma_proc)ma_dlsym(ma_context_get_log(pContext), pContext->win32.hOle32DLL, "StringFromGUID2");
  34361. #else
  34362. (void)pContext; /* Unused. */
  34363. #endif
  34364. pContext->win32.CoInitializeResult = ma_CoInitializeEx(pContext, NULL, MA_COINIT_VALUE);
  34365. return MA_SUCCESS;
  34366. }
  34367. #else
  34368. static ma_result ma_context_uninit_backend_apis__nix(ma_context* pContext)
  34369. {
  34370. (void)pContext;
  34371. return MA_SUCCESS;
  34372. }
  34373. static ma_result ma_context_init_backend_apis__nix(ma_context* pContext)
  34374. {
  34375. (void)pContext;
  34376. return MA_SUCCESS;
  34377. }
  34378. #endif
  34379. static ma_result ma_context_init_backend_apis(ma_context* pContext)
  34380. {
  34381. ma_result result;
  34382. #ifdef MA_WIN32
  34383. result = ma_context_init_backend_apis__win32(pContext);
  34384. #else
  34385. result = ma_context_init_backend_apis__nix(pContext);
  34386. #endif
  34387. return result;
  34388. }
  34389. static ma_result ma_context_uninit_backend_apis(ma_context* pContext)
  34390. {
  34391. ma_result result;
  34392. #ifdef MA_WIN32
  34393. result = ma_context_uninit_backend_apis__win32(pContext);
  34394. #else
  34395. result = ma_context_uninit_backend_apis__nix(pContext);
  34396. #endif
  34397. return result;
  34398. }
  34399. /* The default capacity doesn't need to be too big. */
  34400. #ifndef MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY
  34401. #define MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY 32
  34402. #endif
  34403. MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void)
  34404. {
  34405. ma_device_job_thread_config config;
  34406. MA_ZERO_OBJECT(&config);
  34407. config.noThread = MA_FALSE;
  34408. config.jobQueueCapacity = MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY;
  34409. config.jobQueueFlags = 0;
  34410. return config;
  34411. }
  34412. static ma_thread_result MA_THREADCALL ma_device_job_thread_entry(void* pUserData)
  34413. {
  34414. ma_device_job_thread* pJobThread = (ma_device_job_thread*)pUserData;
  34415. MA_ASSERT(pJobThread != NULL);
  34416. for (;;) {
  34417. ma_result result;
  34418. ma_job job;
  34419. result = ma_device_job_thread_next(pJobThread, &job);
  34420. if (result != MA_SUCCESS) {
  34421. break;
  34422. }
  34423. if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
  34424. break;
  34425. }
  34426. ma_job_process(&job);
  34427. }
  34428. return (ma_thread_result)0;
  34429. }
  34430. 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)
  34431. {
  34432. ma_result result;
  34433. ma_job_queue_config jobQueueConfig;
  34434. if (pJobThread == NULL) {
  34435. return MA_INVALID_ARGS;
  34436. }
  34437. MA_ZERO_OBJECT(pJobThread);
  34438. if (pConfig == NULL) {
  34439. return MA_INVALID_ARGS;
  34440. }
  34441. /* Initialize the job queue before the thread to ensure it's in a valid state. */
  34442. jobQueueConfig = ma_job_queue_config_init(pConfig->jobQueueFlags, pConfig->jobQueueCapacity);
  34443. result = ma_job_queue_init(&jobQueueConfig, pAllocationCallbacks, &pJobThread->jobQueue);
  34444. if (result != MA_SUCCESS) {
  34445. return result; /* Failed to initialize job queue. */
  34446. }
  34447. /* The thread needs to be initialized after the job queue to ensure the thread doesn't try to access it prematurely. */
  34448. if (pConfig->noThread == MA_FALSE) {
  34449. result = ma_thread_create(&pJobThread->thread, ma_thread_priority_normal, 0, ma_device_job_thread_entry, pJobThread, pAllocationCallbacks);
  34450. if (result != MA_SUCCESS) {
  34451. ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks);
  34452. return result; /* Failed to create the job thread. */
  34453. }
  34454. pJobThread->_hasThread = MA_TRUE;
  34455. } else {
  34456. pJobThread->_hasThread = MA_FALSE;
  34457. }
  34458. return MA_SUCCESS;
  34459. }
  34460. MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks)
  34461. {
  34462. if (pJobThread == NULL) {
  34463. return;
  34464. }
  34465. /* 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. */
  34466. {
  34467. ma_job job = ma_job_init(MA_JOB_TYPE_QUIT);
  34468. ma_device_job_thread_post(pJobThread, &job);
  34469. }
  34470. /* Wait for the thread to terminate naturally. */
  34471. if (pJobThread->_hasThread) {
  34472. ma_thread_wait(&pJobThread->thread);
  34473. }
  34474. /* At this point the thread should be terminated so we can safely uninitialize the job queue. */
  34475. ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks);
  34476. }
  34477. MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob)
  34478. {
  34479. if (pJobThread == NULL || pJob == NULL) {
  34480. return MA_INVALID_ARGS;
  34481. }
  34482. return ma_job_queue_post(&pJobThread->jobQueue, pJob);
  34483. }
  34484. MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob)
  34485. {
  34486. if (pJob == NULL) {
  34487. return MA_INVALID_ARGS;
  34488. }
  34489. MA_ZERO_OBJECT(pJob);
  34490. if (pJobThread == NULL) {
  34491. return MA_INVALID_ARGS;
  34492. }
  34493. return ma_job_queue_next(&pJobThread->jobQueue, pJob);
  34494. }
  34495. MA_API ma_context_config ma_context_config_init(void)
  34496. {
  34497. ma_context_config config;
  34498. MA_ZERO_OBJECT(&config);
  34499. return config;
  34500. }
  34501. MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext)
  34502. {
  34503. ma_result result;
  34504. ma_context_config defaultConfig;
  34505. ma_backend defaultBackends[ma_backend_null+1];
  34506. ma_uint32 iBackend;
  34507. ma_backend* pBackendsToIterate;
  34508. ma_uint32 backendsToIterateCount;
  34509. if (pContext == NULL) {
  34510. return MA_INVALID_ARGS;
  34511. }
  34512. MA_ZERO_OBJECT(pContext);
  34513. /* Always make sure the config is set first to ensure properties are available as soon as possible. */
  34514. if (pConfig == NULL) {
  34515. defaultConfig = ma_context_config_init();
  34516. pConfig = &defaultConfig;
  34517. }
  34518. /* Allocation callbacks need to come first because they'll be passed around to other areas. */
  34519. result = ma_allocation_callbacks_init_copy(&pContext->allocationCallbacks, &pConfig->allocationCallbacks);
  34520. if (result != MA_SUCCESS) {
  34521. return result;
  34522. }
  34523. /* Get a lot set up first so we can start logging ASAP. */
  34524. if (pConfig->pLog != NULL) {
  34525. pContext->pLog = pConfig->pLog;
  34526. } else {
  34527. result = ma_log_init(&pContext->allocationCallbacks, &pContext->log);
  34528. if (result == MA_SUCCESS) {
  34529. pContext->pLog = &pContext->log;
  34530. } else {
  34531. pContext->pLog = NULL; /* Logging is not available. */
  34532. }
  34533. }
  34534. pContext->threadPriority = pConfig->threadPriority;
  34535. pContext->threadStackSize = pConfig->threadStackSize;
  34536. pContext->pUserData = pConfig->pUserData;
  34537. /* Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. */
  34538. result = ma_context_init_backend_apis(pContext);
  34539. if (result != MA_SUCCESS) {
  34540. return result;
  34541. }
  34542. for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) {
  34543. defaultBackends[iBackend] = (ma_backend)iBackend;
  34544. }
  34545. pBackendsToIterate = (ma_backend*)backends;
  34546. backendsToIterateCount = backendCount;
  34547. if (pBackendsToIterate == NULL) {
  34548. pBackendsToIterate = (ma_backend*)defaultBackends;
  34549. backendsToIterateCount = ma_countof(defaultBackends);
  34550. }
  34551. MA_ASSERT(pBackendsToIterate != NULL);
  34552. for (iBackend = 0; iBackend < backendsToIterateCount; iBackend += 1) {
  34553. ma_backend backend = pBackendsToIterate[iBackend];
  34554. /* Make sure all callbacks are reset so we don't accidentally drag in any from previously failed initialization attempts. */
  34555. MA_ZERO_OBJECT(&pContext->callbacks);
  34556. /* These backends are using the new callback system. */
  34557. switch (backend) {
  34558. #ifdef MA_HAS_WASAPI
  34559. case ma_backend_wasapi:
  34560. {
  34561. pContext->callbacks.onContextInit = ma_context_init__wasapi;
  34562. } break;
  34563. #endif
  34564. #ifdef MA_HAS_DSOUND
  34565. case ma_backend_dsound:
  34566. {
  34567. pContext->callbacks.onContextInit = ma_context_init__dsound;
  34568. } break;
  34569. #endif
  34570. #ifdef MA_HAS_WINMM
  34571. case ma_backend_winmm:
  34572. {
  34573. pContext->callbacks.onContextInit = ma_context_init__winmm;
  34574. } break;
  34575. #endif
  34576. #ifdef MA_HAS_COREAUDIO
  34577. case ma_backend_coreaudio:
  34578. {
  34579. pContext->callbacks.onContextInit = ma_context_init__coreaudio;
  34580. } break;
  34581. #endif
  34582. #ifdef MA_HAS_SNDIO
  34583. case ma_backend_sndio:
  34584. {
  34585. pContext->callbacks.onContextInit = ma_context_init__sndio;
  34586. } break;
  34587. #endif
  34588. #ifdef MA_HAS_AUDIO4
  34589. case ma_backend_audio4:
  34590. {
  34591. pContext->callbacks.onContextInit = ma_context_init__audio4;
  34592. } break;
  34593. #endif
  34594. #ifdef MA_HAS_OSS
  34595. case ma_backend_oss:
  34596. {
  34597. pContext->callbacks.onContextInit = ma_context_init__oss;
  34598. } break;
  34599. #endif
  34600. #ifdef MA_HAS_PULSEAUDIO
  34601. case ma_backend_pulseaudio:
  34602. {
  34603. pContext->callbacks.onContextInit = ma_context_init__pulse;
  34604. } break;
  34605. #endif
  34606. #ifdef MA_HAS_ALSA
  34607. case ma_backend_alsa:
  34608. {
  34609. pContext->callbacks.onContextInit = ma_context_init__alsa;
  34610. } break;
  34611. #endif
  34612. #ifdef MA_HAS_JACK
  34613. case ma_backend_jack:
  34614. {
  34615. pContext->callbacks.onContextInit = ma_context_init__jack;
  34616. } break;
  34617. #endif
  34618. #ifdef MA_HAS_AAUDIO
  34619. case ma_backend_aaudio:
  34620. {
  34621. if (ma_is_backend_enabled(backend)) {
  34622. pContext->callbacks.onContextInit = ma_context_init__aaudio;
  34623. }
  34624. } break;
  34625. #endif
  34626. #ifdef MA_HAS_OPENSL
  34627. case ma_backend_opensl:
  34628. {
  34629. if (ma_is_backend_enabled(backend)) {
  34630. pContext->callbacks.onContextInit = ma_context_init__opensl;
  34631. }
  34632. } break;
  34633. #endif
  34634. #ifdef MA_HAS_WEBAUDIO
  34635. case ma_backend_webaudio:
  34636. {
  34637. pContext->callbacks.onContextInit = ma_context_init__webaudio;
  34638. } break;
  34639. #endif
  34640. #ifdef MA_HAS_CUSTOM
  34641. case ma_backend_custom:
  34642. {
  34643. /* Slightly different logic for custom backends. Custom backends can optionally set all of their callbacks in the config. */
  34644. pContext->callbacks = pConfig->custom;
  34645. } break;
  34646. #endif
  34647. #ifdef MA_HAS_NULL
  34648. case ma_backend_null:
  34649. {
  34650. pContext->callbacks.onContextInit = ma_context_init__null;
  34651. } break;
  34652. #endif
  34653. default: break;
  34654. }
  34655. if (pContext->callbacks.onContextInit != NULL) {
  34656. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Attempting to initialize %s backend...\n", ma_get_backend_name(backend));
  34657. result = pContext->callbacks.onContextInit(pContext, pConfig, &pContext->callbacks);
  34658. } else {
  34659. /* Getting here means the onContextInit callback is not set which means the backend is not enabled. Special case for the custom backend. */
  34660. if (backend != ma_backend_custom) {
  34661. result = MA_BACKEND_NOT_ENABLED;
  34662. } else {
  34663. #if !defined(MA_HAS_CUSTOM)
  34664. result = MA_BACKEND_NOT_ENABLED;
  34665. #else
  34666. result = MA_NO_BACKEND;
  34667. #endif
  34668. }
  34669. }
  34670. /* If this iteration was successful, return. */
  34671. if (result == MA_SUCCESS) {
  34672. result = ma_mutex_init(&pContext->deviceEnumLock);
  34673. if (result != MA_SUCCESS) {
  34674. 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");
  34675. }
  34676. result = ma_mutex_init(&pContext->deviceInfoLock);
  34677. if (result != MA_SUCCESS) {
  34678. 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");
  34679. }
  34680. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "System Architecture:\n");
  34681. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " Endian: %s\n", ma_is_little_endian() ? "LE" : "BE");
  34682. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " SSE2: %s\n", ma_has_sse2() ? "YES" : "NO");
  34683. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " AVX2: %s\n", ma_has_avx2() ? "YES" : "NO");
  34684. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " NEON: %s\n", ma_has_neon() ? "YES" : "NO");
  34685. pContext->backend = backend;
  34686. return result;
  34687. } else {
  34688. if (result == MA_BACKEND_NOT_ENABLED) {
  34689. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "%s backend is disabled.\n", ma_get_backend_name(backend));
  34690. } else {
  34691. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Failed to initialize %s backend.\n", ma_get_backend_name(backend));
  34692. }
  34693. }
  34694. }
  34695. /* If we get here it means an error occurred. */
  34696. MA_ZERO_OBJECT(pContext); /* Safety. */
  34697. return MA_NO_BACKEND;
  34698. }
  34699. MA_API ma_result ma_context_uninit(ma_context* pContext)
  34700. {
  34701. if (pContext == NULL) {
  34702. return MA_INVALID_ARGS;
  34703. }
  34704. if (pContext->callbacks.onContextUninit != NULL) {
  34705. pContext->callbacks.onContextUninit(pContext);
  34706. }
  34707. ma_mutex_uninit(&pContext->deviceEnumLock);
  34708. ma_mutex_uninit(&pContext->deviceInfoLock);
  34709. ma_free(pContext->pDeviceInfos, &pContext->allocationCallbacks);
  34710. ma_context_uninit_backend_apis(pContext);
  34711. if (pContext->pLog == &pContext->log) {
  34712. ma_log_uninit(&pContext->log);
  34713. }
  34714. return MA_SUCCESS;
  34715. }
  34716. MA_API size_t ma_context_sizeof(void)
  34717. {
  34718. return sizeof(ma_context);
  34719. }
  34720. MA_API ma_log* ma_context_get_log(ma_context* pContext)
  34721. {
  34722. if (pContext == NULL) {
  34723. return NULL;
  34724. }
  34725. return pContext->pLog;
  34726. }
  34727. MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  34728. {
  34729. ma_result result;
  34730. if (pContext == NULL || callback == NULL) {
  34731. return MA_INVALID_ARGS;
  34732. }
  34733. if (pContext->callbacks.onContextEnumerateDevices == NULL) {
  34734. return MA_INVALID_OPERATION;
  34735. }
  34736. ma_mutex_lock(&pContext->deviceEnumLock);
  34737. {
  34738. result = pContext->callbacks.onContextEnumerateDevices(pContext, callback, pUserData);
  34739. }
  34740. ma_mutex_unlock(&pContext->deviceEnumLock);
  34741. return result;
  34742. }
  34743. static ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
  34744. {
  34745. /*
  34746. 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
  34747. it's just appended to the end. If it's a playback device it's inserted just before the first capture device.
  34748. */
  34749. /*
  34750. 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
  34751. simple fixed size increment for buffer expansion.
  34752. */
  34753. const ma_uint32 bufferExpansionCount = 2;
  34754. const ma_uint32 totalDeviceInfoCount = pContext->playbackDeviceInfoCount + pContext->captureDeviceInfoCount;
  34755. if (totalDeviceInfoCount >= pContext->deviceInfoCapacity) {
  34756. ma_uint32 newCapacity = pContext->deviceInfoCapacity + bufferExpansionCount;
  34757. ma_device_info* pNewInfos = (ma_device_info*)ma_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity, &pContext->allocationCallbacks);
  34758. if (pNewInfos == NULL) {
  34759. return MA_FALSE; /* Out of memory. */
  34760. }
  34761. pContext->pDeviceInfos = pNewInfos;
  34762. pContext->deviceInfoCapacity = newCapacity;
  34763. }
  34764. if (deviceType == ma_device_type_playback) {
  34765. /* Playback. Insert just before the first capture device. */
  34766. /* The first thing to do is move all of the capture devices down a slot. */
  34767. ma_uint32 iFirstCaptureDevice = pContext->playbackDeviceInfoCount;
  34768. size_t iCaptureDevice;
  34769. for (iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) {
  34770. pContext->pDeviceInfos[iCaptureDevice] = pContext->pDeviceInfos[iCaptureDevice-1];
  34771. }
  34772. /* Now just insert where the first capture device was before moving it down a slot. */
  34773. pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo;
  34774. pContext->playbackDeviceInfoCount += 1;
  34775. } else {
  34776. /* Capture. Insert at the end. */
  34777. pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo;
  34778. pContext->captureDeviceInfoCount += 1;
  34779. }
  34780. (void)pUserData;
  34781. return MA_TRUE;
  34782. }
  34783. 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)
  34784. {
  34785. ma_result result;
  34786. /* Safety. */
  34787. if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL;
  34788. if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0;
  34789. if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL;
  34790. if (pCaptureDeviceCount != NULL) *pCaptureDeviceCount = 0;
  34791. if (pContext == NULL) {
  34792. return MA_INVALID_ARGS;
  34793. }
  34794. if (pContext->callbacks.onContextEnumerateDevices == NULL) {
  34795. return MA_INVALID_OPERATION;
  34796. }
  34797. /* Note that we don't use ma_context_enumerate_devices() here because we want to do locking at a higher level. */
  34798. ma_mutex_lock(&pContext->deviceEnumLock);
  34799. {
  34800. /* Reset everything first. */
  34801. pContext->playbackDeviceInfoCount = 0;
  34802. pContext->captureDeviceInfoCount = 0;
  34803. /* Now enumerate over available devices. */
  34804. result = pContext->callbacks.onContextEnumerateDevices(pContext, ma_context_get_devices__enum_callback, NULL);
  34805. if (result == MA_SUCCESS) {
  34806. /* Playback devices. */
  34807. if (ppPlaybackDeviceInfos != NULL) {
  34808. *ppPlaybackDeviceInfos = pContext->pDeviceInfos;
  34809. }
  34810. if (pPlaybackDeviceCount != NULL) {
  34811. *pPlaybackDeviceCount = pContext->playbackDeviceInfoCount;
  34812. }
  34813. /* Capture devices. */
  34814. if (ppCaptureDeviceInfos != NULL) {
  34815. *ppCaptureDeviceInfos = pContext->pDeviceInfos;
  34816. /* Capture devices come after playback devices. */
  34817. if (pContext->playbackDeviceInfoCount > 0) {
  34818. /* Conditional, because NULL+0 is undefined behavior. */
  34819. *ppCaptureDeviceInfos += pContext->playbackDeviceInfoCount;
  34820. }
  34821. }
  34822. if (pCaptureDeviceCount != NULL) {
  34823. *pCaptureDeviceCount = pContext->captureDeviceInfoCount;
  34824. }
  34825. }
  34826. }
  34827. ma_mutex_unlock(&pContext->deviceEnumLock);
  34828. return result;
  34829. }
  34830. 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)
  34831. {
  34832. ma_result result;
  34833. ma_device_info deviceInfo;
  34834. /* NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. */
  34835. if (pContext == NULL || pDeviceInfo == NULL) {
  34836. return MA_INVALID_ARGS;
  34837. }
  34838. MA_ZERO_OBJECT(&deviceInfo);
  34839. /* Help the backend out by copying over the device ID if we have one. */
  34840. if (pDeviceID != NULL) {
  34841. MA_COPY_MEMORY(&deviceInfo.id, pDeviceID, sizeof(*pDeviceID));
  34842. }
  34843. if (pContext->callbacks.onContextGetDeviceInfo == NULL) {
  34844. return MA_INVALID_OPERATION;
  34845. }
  34846. ma_mutex_lock(&pContext->deviceInfoLock);
  34847. {
  34848. result = pContext->callbacks.onContextGetDeviceInfo(pContext, deviceType, pDeviceID, &deviceInfo);
  34849. }
  34850. ma_mutex_unlock(&pContext->deviceInfoLock);
  34851. *pDeviceInfo = deviceInfo;
  34852. return result;
  34853. }
  34854. MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext)
  34855. {
  34856. if (pContext == NULL) {
  34857. return MA_FALSE;
  34858. }
  34859. return ma_is_loopback_supported(pContext->backend);
  34860. }
  34861. MA_API ma_device_config ma_device_config_init(ma_device_type deviceType)
  34862. {
  34863. ma_device_config config;
  34864. MA_ZERO_OBJECT(&config);
  34865. config.deviceType = deviceType;
  34866. config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate don't matter here. */
  34867. return config;
  34868. }
  34869. MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
  34870. {
  34871. ma_result result;
  34872. ma_device_descriptor descriptorPlayback;
  34873. ma_device_descriptor descriptorCapture;
  34874. /* The context can be null, in which case we self-manage it. */
  34875. if (pContext == NULL) {
  34876. return ma_device_init_ex(NULL, 0, NULL, pConfig, pDevice);
  34877. }
  34878. if (pDevice == NULL) {
  34879. return MA_INVALID_ARGS;
  34880. }
  34881. MA_ZERO_OBJECT(pDevice);
  34882. if (pConfig == NULL) {
  34883. return MA_INVALID_ARGS;
  34884. }
  34885. /* Check that we have our callbacks defined. */
  34886. if (pContext->callbacks.onDeviceInit == NULL) {
  34887. return MA_INVALID_OPERATION;
  34888. }
  34889. /* Basic config validation. */
  34890. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  34891. if (pConfig->capture.channels > MA_MAX_CHANNELS) {
  34892. return MA_INVALID_ARGS;
  34893. }
  34894. if (!ma__is_channel_map_valid(pConfig->capture.pChannelMap, pConfig->capture.channels)) {
  34895. return MA_INVALID_ARGS;
  34896. }
  34897. }
  34898. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  34899. if (pConfig->playback.channels > MA_MAX_CHANNELS) {
  34900. return MA_INVALID_ARGS;
  34901. }
  34902. if (!ma__is_channel_map_valid(pConfig->playback.pChannelMap, pConfig->playback.channels)) {
  34903. return MA_INVALID_ARGS;
  34904. }
  34905. }
  34906. pDevice->pContext = pContext;
  34907. /* Set the user data and log callback ASAP to ensure it is available for the entire initialization process. */
  34908. pDevice->pUserData = pConfig->pUserData;
  34909. pDevice->onData = pConfig->dataCallback;
  34910. pDevice->onNotification = pConfig->notificationCallback;
  34911. pDevice->onStop = pConfig->stopCallback;
  34912. if (pConfig->playback.pDeviceID != NULL) {
  34913. MA_COPY_MEMORY(&pDevice->playback.id, pConfig->playback.pDeviceID, sizeof(pDevice->playback.id));
  34914. pDevice->playback.pID = &pDevice->playback.id;
  34915. } else {
  34916. pDevice->playback.pID = NULL;
  34917. }
  34918. if (pConfig->capture.pDeviceID != NULL) {
  34919. MA_COPY_MEMORY(&pDevice->capture.id, pConfig->capture.pDeviceID, sizeof(pDevice->capture.id));
  34920. pDevice->capture.pID = &pDevice->capture.id;
  34921. } else {
  34922. pDevice->capture.pID = NULL;
  34923. }
  34924. pDevice->noPreSilencedOutputBuffer = pConfig->noPreSilencedOutputBuffer;
  34925. pDevice->noClip = pConfig->noClip;
  34926. pDevice->noDisableDenormals = pConfig->noDisableDenormals;
  34927. pDevice->noFixedSizedCallback = pConfig->noFixedSizedCallback;
  34928. ma_atomic_float_set(&pDevice->masterVolumeFactor, 1);
  34929. pDevice->type = pConfig->deviceType;
  34930. pDevice->sampleRate = pConfig->sampleRate;
  34931. pDevice->resampling.algorithm = pConfig->resampling.algorithm;
  34932. pDevice->resampling.linear.lpfOrder = pConfig->resampling.linear.lpfOrder;
  34933. pDevice->resampling.pBackendVTable = pConfig->resampling.pBackendVTable;
  34934. pDevice->resampling.pBackendUserData = pConfig->resampling.pBackendUserData;
  34935. pDevice->capture.shareMode = pConfig->capture.shareMode;
  34936. pDevice->capture.format = pConfig->capture.format;
  34937. pDevice->capture.channels = pConfig->capture.channels;
  34938. ma_channel_map_copy_or_default(pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels);
  34939. pDevice->capture.channelMixMode = pConfig->capture.channelMixMode;
  34940. pDevice->capture.calculateLFEFromSpatialChannels = pConfig->capture.calculateLFEFromSpatialChannels;
  34941. pDevice->playback.shareMode = pConfig->playback.shareMode;
  34942. pDevice->playback.format = pConfig->playback.format;
  34943. pDevice->playback.channels = pConfig->playback.channels;
  34944. ma_channel_map_copy_or_default(pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels);
  34945. pDevice->playback.channelMixMode = pConfig->playback.channelMixMode;
  34946. pDevice->playback.calculateLFEFromSpatialChannels = pConfig->playback.calculateLFEFromSpatialChannels;
  34947. result = ma_mutex_init(&pDevice->startStopLock);
  34948. if (result != MA_SUCCESS) {
  34949. return result;
  34950. }
  34951. /*
  34952. When the device is started, the worker thread is the one that does the actual startup of the backend device. We
  34953. use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device.
  34954. Each of these semaphores is released internally by the worker thread when the work is completed. The start
  34955. semaphore is also used to wake up the worker thread.
  34956. */
  34957. result = ma_event_init(&pDevice->wakeupEvent);
  34958. if (result != MA_SUCCESS) {
  34959. ma_mutex_uninit(&pDevice->startStopLock);
  34960. return result;
  34961. }
  34962. result = ma_event_init(&pDevice->startEvent);
  34963. if (result != MA_SUCCESS) {
  34964. ma_event_uninit(&pDevice->wakeupEvent);
  34965. ma_mutex_uninit(&pDevice->startStopLock);
  34966. return result;
  34967. }
  34968. result = ma_event_init(&pDevice->stopEvent);
  34969. if (result != MA_SUCCESS) {
  34970. ma_event_uninit(&pDevice->startEvent);
  34971. ma_event_uninit(&pDevice->wakeupEvent);
  34972. ma_mutex_uninit(&pDevice->startStopLock);
  34973. return result;
  34974. }
  34975. MA_ZERO_OBJECT(&descriptorPlayback);
  34976. descriptorPlayback.pDeviceID = pConfig->playback.pDeviceID;
  34977. descriptorPlayback.shareMode = pConfig->playback.shareMode;
  34978. descriptorPlayback.format = pConfig->playback.format;
  34979. descriptorPlayback.channels = pConfig->playback.channels;
  34980. descriptorPlayback.sampleRate = pConfig->sampleRate;
  34981. ma_channel_map_copy_or_default(descriptorPlayback.channelMap, ma_countof(descriptorPlayback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels);
  34982. descriptorPlayback.periodSizeInFrames = pConfig->periodSizeInFrames;
  34983. descriptorPlayback.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
  34984. descriptorPlayback.periodCount = pConfig->periods;
  34985. if (descriptorPlayback.periodCount == 0) {
  34986. descriptorPlayback.periodCount = MA_DEFAULT_PERIODS;
  34987. }
  34988. MA_ZERO_OBJECT(&descriptorCapture);
  34989. descriptorCapture.pDeviceID = pConfig->capture.pDeviceID;
  34990. descriptorCapture.shareMode = pConfig->capture.shareMode;
  34991. descriptorCapture.format = pConfig->capture.format;
  34992. descriptorCapture.channels = pConfig->capture.channels;
  34993. descriptorCapture.sampleRate = pConfig->sampleRate;
  34994. ma_channel_map_copy_or_default(descriptorCapture.channelMap, ma_countof(descriptorCapture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels);
  34995. descriptorCapture.periodSizeInFrames = pConfig->periodSizeInFrames;
  34996. descriptorCapture.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
  34997. descriptorCapture.periodCount = pConfig->periods;
  34998. if (descriptorCapture.periodCount == 0) {
  34999. descriptorCapture.periodCount = MA_DEFAULT_PERIODS;
  35000. }
  35001. result = pContext->callbacks.onDeviceInit(pDevice, pConfig, &descriptorPlayback, &descriptorCapture);
  35002. if (result != MA_SUCCESS) {
  35003. ma_event_uninit(&pDevice->startEvent);
  35004. ma_event_uninit(&pDevice->wakeupEvent);
  35005. ma_mutex_uninit(&pDevice->startStopLock);
  35006. return result;
  35007. }
  35008. #if 0
  35009. /*
  35010. On output the descriptors will contain the *actual* data format of the device. We need this to know how to convert the data between
  35011. the requested format and the internal format.
  35012. */
  35013. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  35014. if (!ma_device_descriptor_is_valid(&descriptorCapture)) {
  35015. ma_device_uninit(pDevice);
  35016. return MA_INVALID_ARGS;
  35017. }
  35018. pDevice->capture.internalFormat = descriptorCapture.format;
  35019. pDevice->capture.internalChannels = descriptorCapture.channels;
  35020. pDevice->capture.internalSampleRate = descriptorCapture.sampleRate;
  35021. ma_channel_map_copy(pDevice->capture.internalChannelMap, descriptorCapture.channelMap, descriptorCapture.channels);
  35022. pDevice->capture.internalPeriodSizeInFrames = descriptorCapture.periodSizeInFrames;
  35023. pDevice->capture.internalPeriods = descriptorCapture.periodCount;
  35024. if (pDevice->capture.internalPeriodSizeInFrames == 0) {
  35025. pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorCapture.periodSizeInMilliseconds, descriptorCapture.sampleRate);
  35026. }
  35027. }
  35028. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  35029. if (!ma_device_descriptor_is_valid(&descriptorPlayback)) {
  35030. ma_device_uninit(pDevice);
  35031. return MA_INVALID_ARGS;
  35032. }
  35033. pDevice->playback.internalFormat = descriptorPlayback.format;
  35034. pDevice->playback.internalChannels = descriptorPlayback.channels;
  35035. pDevice->playback.internalSampleRate = descriptorPlayback.sampleRate;
  35036. ma_channel_map_copy(pDevice->playback.internalChannelMap, descriptorPlayback.channelMap, descriptorPlayback.channels);
  35037. pDevice->playback.internalPeriodSizeInFrames = descriptorPlayback.periodSizeInFrames;
  35038. pDevice->playback.internalPeriods = descriptorPlayback.periodCount;
  35039. if (pDevice->playback.internalPeriodSizeInFrames == 0) {
  35040. pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorPlayback.periodSizeInMilliseconds, descriptorPlayback.sampleRate);
  35041. }
  35042. }
  35043. /*
  35044. 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.
  35045. For loopback devices, we need to retrieve the name of the playback device.
  35046. */
  35047. {
  35048. ma_device_info deviceInfo;
  35049. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  35050. result = ma_device_get_info(pDevice, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo);
  35051. if (result == MA_SUCCESS) {
  35052. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1);
  35053. } else {
  35054. /* We failed to retrieve the device info. Fall back to a default name. */
  35055. if (descriptorCapture.pDeviceID == NULL) {
  35056. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  35057. } else {
  35058. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1);
  35059. }
  35060. }
  35061. }
  35062. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  35063. result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo);
  35064. if (result == MA_SUCCESS) {
  35065. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1);
  35066. } else {
  35067. /* We failed to retrieve the device info. Fall back to a default name. */
  35068. if (descriptorPlayback.pDeviceID == NULL) {
  35069. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  35070. } else {
  35071. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1);
  35072. }
  35073. }
  35074. }
  35075. }
  35076. ma_device__post_init_setup(pDevice, pConfig->deviceType);
  35077. #endif
  35078. result = ma_device_post_init(pDevice, pConfig->deviceType, &descriptorPlayback, &descriptorCapture);
  35079. if (result != MA_SUCCESS) {
  35080. ma_device_uninit(pDevice);
  35081. return result;
  35082. }
  35083. /*
  35084. If we're using fixed sized callbacks we'll need to make use of an intermediary buffer. Needs to
  35085. be done after post_init_setup() because we'll need access to the sample rate.
  35086. */
  35087. if (pConfig->noFixedSizedCallback == MA_FALSE) {
  35088. /* We're using a fixed sized data callback so we'll need an intermediary buffer. */
  35089. ma_uint32 intermediaryBufferCap = pConfig->periodSizeInFrames;
  35090. if (intermediaryBufferCap == 0) {
  35091. intermediaryBufferCap = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pDevice->sampleRate);
  35092. }
  35093. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  35094. ma_uint32 intermediaryBufferSizeInBytes;
  35095. pDevice->capture.intermediaryBufferLen = 0;
  35096. pDevice->capture.intermediaryBufferCap = intermediaryBufferCap;
  35097. if (pDevice->capture.intermediaryBufferCap == 0) {
  35098. pDevice->capture.intermediaryBufferCap = pDevice->capture.internalPeriodSizeInFrames;
  35099. }
  35100. intermediaryBufferSizeInBytes = pDevice->capture.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  35101. pDevice->capture.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks);
  35102. if (pDevice->capture.pIntermediaryBuffer == NULL) {
  35103. ma_device_uninit(pDevice);
  35104. return MA_OUT_OF_MEMORY;
  35105. }
  35106. /* Silence the buffer for safety. */
  35107. ma_silence_pcm_frames(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap, pDevice->capture.format, pDevice->capture.channels);
  35108. pDevice->capture.intermediaryBufferLen = pDevice->capture.intermediaryBufferCap;
  35109. }
  35110. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  35111. ma_uint64 intermediaryBufferSizeInBytes;
  35112. pDevice->playback.intermediaryBufferLen = 0;
  35113. if (pConfig->deviceType == ma_device_type_duplex) {
  35114. pDevice->playback.intermediaryBufferCap = pDevice->capture.intermediaryBufferCap; /* In duplex mode, make sure the intermediary buffer is always the same size as the capture side. */
  35115. } else {
  35116. pDevice->playback.intermediaryBufferCap = intermediaryBufferCap;
  35117. if (pDevice->playback.intermediaryBufferCap == 0) {
  35118. pDevice->playback.intermediaryBufferCap = pDevice->playback.internalPeriodSizeInFrames;
  35119. }
  35120. }
  35121. intermediaryBufferSizeInBytes = pDevice->playback.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  35122. pDevice->playback.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks);
  35123. if (pDevice->playback.pIntermediaryBuffer == NULL) {
  35124. ma_device_uninit(pDevice);
  35125. return MA_OUT_OF_MEMORY;
  35126. }
  35127. /* Silence the buffer for safety. */
  35128. ma_silence_pcm_frames(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap, pDevice->playback.format, pDevice->playback.channels);
  35129. pDevice->playback.intermediaryBufferLen = 0;
  35130. }
  35131. } else {
  35132. /* Not using a fixed sized data callback so no need for an intermediary buffer. */
  35133. }
  35134. /* Some backends don't require the worker thread. */
  35135. if (!ma_context_is_backend_asynchronous(pContext)) {
  35136. /* The worker thread. */
  35137. result = ma_thread_create(&pDevice->thread, pContext->threadPriority, pContext->threadStackSize, ma_worker_thread, pDevice, &pContext->allocationCallbacks);
  35138. if (result != MA_SUCCESS) {
  35139. ma_device_uninit(pDevice);
  35140. return result;
  35141. }
  35142. /* Wait for the worker thread to put the device into it's stopped state for real. */
  35143. ma_event_wait(&pDevice->stopEvent);
  35144. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  35145. } else {
  35146. /*
  35147. If the backend is asynchronous and the device is duplex, we'll need an intermediary ring buffer. Note that this needs to be done
  35148. after ma_device__post_init_setup().
  35149. */
  35150. if (ma_context_is_backend_asynchronous(pContext)) {
  35151. if (pConfig->deviceType == ma_device_type_duplex) {
  35152. result = ma_duplex_rb_init(pDevice->capture.format, pDevice->capture.channels, pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB);
  35153. if (result != MA_SUCCESS) {
  35154. ma_device_uninit(pDevice);
  35155. return result;
  35156. }
  35157. }
  35158. }
  35159. ma_device__set_state(pDevice, ma_device_state_stopped);
  35160. }
  35161. /* Log device information. */
  35162. {
  35163. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[%s]\n", ma_get_backend_name(pDevice->pContext->backend));
  35164. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  35165. char name[MA_MAX_DEVICE_NAME_LENGTH + 1];
  35166. ma_device_get_name(pDevice, (pDevice->type == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, name, sizeof(name), NULL);
  35167. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Capture");
  35168. 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));
  35169. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->capture.internalChannels, pDevice->capture.channels);
  35170. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->capture.internalSampleRate, pDevice->sampleRate);
  35171. 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));
  35172. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n");
  35173. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->capture.converter.hasPreFormatConversion ? "YES" : "NO");
  35174. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->capture.converter.hasPostFormatConversion ? "YES" : "NO");
  35175. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->capture.converter.hasChannelConverter ? "YES" : "NO");
  35176. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->capture.converter.hasResampler ? "YES" : "NO");
  35177. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->capture.converter.isPassthrough ? "YES" : "NO");
  35178. {
  35179. char channelMapStr[1024];
  35180. ma_channel_map_to_string(pDevice->capture.internalChannelMap, pDevice->capture.internalChannels, channelMapStr, sizeof(channelMapStr));
  35181. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr);
  35182. ma_channel_map_to_string(pDevice->capture.channelMap, pDevice->capture.channels, channelMapStr, sizeof(channelMapStr));
  35183. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr);
  35184. }
  35185. }
  35186. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  35187. char name[MA_MAX_DEVICE_NAME_LENGTH + 1];
  35188. ma_device_get_name(pDevice, ma_device_type_playback, name, sizeof(name), NULL);
  35189. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Playback");
  35190. 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));
  35191. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->playback.channels, pDevice->playback.internalChannels);
  35192. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->playback.internalSampleRate);
  35193. 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));
  35194. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n");
  35195. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->playback.converter.hasPreFormatConversion ? "YES" : "NO");
  35196. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->playback.converter.hasPostFormatConversion ? "YES" : "NO");
  35197. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->playback.converter.hasChannelConverter ? "YES" : "NO");
  35198. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->playback.converter.hasResampler ? "YES" : "NO");
  35199. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->playback.converter.isPassthrough ? "YES" : "NO");
  35200. {
  35201. char channelMapStr[1024];
  35202. ma_channel_map_to_string(pDevice->playback.channelMap, pDevice->playback.channels, channelMapStr, sizeof(channelMapStr));
  35203. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr);
  35204. ma_channel_map_to_string(pDevice->playback.internalChannelMap, pDevice->playback.internalChannels, channelMapStr, sizeof(channelMapStr));
  35205. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr);
  35206. }
  35207. }
  35208. }
  35209. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  35210. return MA_SUCCESS;
  35211. }
  35212. 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)
  35213. {
  35214. ma_result result;
  35215. ma_context* pContext;
  35216. ma_backend defaultBackends[ma_backend_null+1];
  35217. ma_uint32 iBackend;
  35218. ma_backend* pBackendsToIterate;
  35219. ma_uint32 backendsToIterateCount;
  35220. ma_allocation_callbacks allocationCallbacks;
  35221. if (pConfig == NULL) {
  35222. return MA_INVALID_ARGS;
  35223. }
  35224. if (pContextConfig != NULL) {
  35225. result = ma_allocation_callbacks_init_copy(&allocationCallbacks, &pContextConfig->allocationCallbacks);
  35226. if (result != MA_SUCCESS) {
  35227. return result;
  35228. }
  35229. } else {
  35230. allocationCallbacks = ma_allocation_callbacks_init_default();
  35231. }
  35232. pContext = (ma_context*)ma_malloc(sizeof(*pContext), &allocationCallbacks);
  35233. if (pContext == NULL) {
  35234. return MA_OUT_OF_MEMORY;
  35235. }
  35236. for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) {
  35237. defaultBackends[iBackend] = (ma_backend)iBackend;
  35238. }
  35239. pBackendsToIterate = (ma_backend*)backends;
  35240. backendsToIterateCount = backendCount;
  35241. if (pBackendsToIterate == NULL) {
  35242. pBackendsToIterate = (ma_backend*)defaultBackends;
  35243. backendsToIterateCount = ma_countof(defaultBackends);
  35244. }
  35245. result = MA_NO_BACKEND;
  35246. for (iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) {
  35247. /*
  35248. This is a hack for iOS. If the context config is null, there's a good chance the
  35249. `ma_device_init(NULL, &deviceConfig, pDevice);` pattern is being used. In this
  35250. case, set the session category based on the device type.
  35251. */
  35252. #if defined(MA_APPLE_MOBILE)
  35253. ma_context_config contextConfig;
  35254. if (pContextConfig == NULL) {
  35255. contextConfig = ma_context_config_init();
  35256. switch (pConfig->deviceType) {
  35257. case ma_device_type_duplex: {
  35258. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_play_and_record;
  35259. } break;
  35260. case ma_device_type_capture: {
  35261. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_record;
  35262. } break;
  35263. case ma_device_type_playback:
  35264. default: {
  35265. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_playback;
  35266. } break;
  35267. }
  35268. pContextConfig = &contextConfig;
  35269. }
  35270. #endif
  35271. result = ma_context_init(&pBackendsToIterate[iBackend], 1, pContextConfig, pContext);
  35272. if (result == MA_SUCCESS) {
  35273. result = ma_device_init(pContext, pConfig, pDevice);
  35274. if (result == MA_SUCCESS) {
  35275. break; /* Success. */
  35276. } else {
  35277. ma_context_uninit(pContext); /* Failure. */
  35278. }
  35279. }
  35280. }
  35281. if (result != MA_SUCCESS) {
  35282. ma_free(pContext, &allocationCallbacks);
  35283. return result;
  35284. }
  35285. pDevice->isOwnerOfContext = MA_TRUE;
  35286. return result;
  35287. }
  35288. MA_API void ma_device_uninit(ma_device* pDevice)
  35289. {
  35290. if (!ma_device__is_initialized(pDevice)) {
  35291. return;
  35292. }
  35293. /*
  35294. It's possible for the miniaudio side of the device and the backend to not be in sync due to
  35295. system-level situations such as the computer being put into sleep mode and the backend not
  35296. notifying miniaudio of the fact the device has stopped. It's possible for this to result in a
  35297. deadlock due to miniaudio thinking the device is in a running state, when in fact it's not
  35298. running at all. For this reason I am no longer explicitly stopping the device. I don't think
  35299. this should affect anyone in practice since uninitializing the backend will naturally stop the
  35300. device anyway.
  35301. */
  35302. #if 0
  35303. {
  35304. /* 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. */
  35305. if (ma_device_is_started(pDevice)) {
  35306. ma_device_stop(pDevice);
  35307. }
  35308. }
  35309. #endif
  35310. /* Putting the device into an uninitialized state will make the worker thread return. */
  35311. ma_device__set_state(pDevice, ma_device_state_uninitialized);
  35312. /* Wake up the worker thread and wait for it to properly terminate. */
  35313. if (!ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35314. ma_event_signal(&pDevice->wakeupEvent);
  35315. ma_thread_wait(&pDevice->thread);
  35316. }
  35317. if (pDevice->pContext->callbacks.onDeviceUninit != NULL) {
  35318. pDevice->pContext->callbacks.onDeviceUninit(pDevice);
  35319. }
  35320. ma_event_uninit(&pDevice->stopEvent);
  35321. ma_event_uninit(&pDevice->startEvent);
  35322. ma_event_uninit(&pDevice->wakeupEvent);
  35323. ma_mutex_uninit(&pDevice->startStopLock);
  35324. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35325. if (pDevice->type == ma_device_type_duplex) {
  35326. ma_duplex_rb_uninit(&pDevice->duplexRB);
  35327. }
  35328. }
  35329. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  35330. ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks);
  35331. }
  35332. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  35333. ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks);
  35334. }
  35335. if (pDevice->playback.pInputCache != NULL) {
  35336. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  35337. }
  35338. if (pDevice->capture.pIntermediaryBuffer != NULL) {
  35339. ma_free(pDevice->capture.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  35340. }
  35341. if (pDevice->playback.pIntermediaryBuffer != NULL) {
  35342. ma_free(pDevice->playback.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  35343. }
  35344. if (pDevice->isOwnerOfContext) {
  35345. ma_allocation_callbacks allocationCallbacks = pDevice->pContext->allocationCallbacks;
  35346. ma_context_uninit(pDevice->pContext);
  35347. ma_free(pDevice->pContext, &allocationCallbacks);
  35348. }
  35349. MA_ZERO_OBJECT(pDevice);
  35350. }
  35351. MA_API ma_context* ma_device_get_context(ma_device* pDevice)
  35352. {
  35353. if (pDevice == NULL) {
  35354. return NULL;
  35355. }
  35356. return pDevice->pContext;
  35357. }
  35358. MA_API ma_log* ma_device_get_log(ma_device* pDevice)
  35359. {
  35360. return ma_context_get_log(ma_device_get_context(pDevice));
  35361. }
  35362. MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo)
  35363. {
  35364. if (pDeviceInfo == NULL) {
  35365. return MA_INVALID_ARGS;
  35366. }
  35367. MA_ZERO_OBJECT(pDeviceInfo);
  35368. if (pDevice == NULL) {
  35369. return MA_INVALID_ARGS;
  35370. }
  35371. /* If the onDeviceGetInfo() callback is set, use that. Otherwise we'll fall back to ma_context_get_device_info(). */
  35372. if (pDevice->pContext->callbacks.onDeviceGetInfo != NULL) {
  35373. return pDevice->pContext->callbacks.onDeviceGetInfo(pDevice, type, pDeviceInfo);
  35374. }
  35375. /* Getting here means onDeviceGetInfo is not implemented so we need to fall back to an alternative. */
  35376. if (type == ma_device_type_playback) {
  35377. return ma_context_get_device_info(pDevice->pContext, type, pDevice->playback.pID, pDeviceInfo);
  35378. } else {
  35379. return ma_context_get_device_info(pDevice->pContext, type, pDevice->capture.pID, pDeviceInfo);
  35380. }
  35381. }
  35382. MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator)
  35383. {
  35384. ma_result result;
  35385. ma_device_info deviceInfo;
  35386. if (pLengthNotIncludingNullTerminator != NULL) {
  35387. *pLengthNotIncludingNullTerminator = 0;
  35388. }
  35389. if (pName != NULL && nameCap > 0) {
  35390. pName[0] = '\0';
  35391. }
  35392. result = ma_device_get_info(pDevice, type, &deviceInfo);
  35393. if (result != MA_SUCCESS) {
  35394. return result;
  35395. }
  35396. if (pName != NULL) {
  35397. ma_strncpy_s(pName, nameCap, deviceInfo.name, (size_t)-1);
  35398. /*
  35399. For safety, make sure the length is based on the truncated output string rather than the
  35400. source. Otherwise the caller might assume the output buffer contains more content than it
  35401. actually does.
  35402. */
  35403. if (pLengthNotIncludingNullTerminator != NULL) {
  35404. *pLengthNotIncludingNullTerminator = strlen(pName);
  35405. }
  35406. } else {
  35407. /* Name not specified. Just report the length of the source string. */
  35408. if (pLengthNotIncludingNullTerminator != NULL) {
  35409. *pLengthNotIncludingNullTerminator = strlen(deviceInfo.name);
  35410. }
  35411. }
  35412. return MA_SUCCESS;
  35413. }
  35414. MA_API ma_result ma_device_start(ma_device* pDevice)
  35415. {
  35416. ma_result result;
  35417. if (pDevice == NULL) {
  35418. return MA_INVALID_ARGS;
  35419. }
  35420. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  35421. return MA_INVALID_OPERATION; /* Not initialized. */
  35422. }
  35423. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  35424. return MA_SUCCESS; /* Already started. */
  35425. }
  35426. ma_mutex_lock(&pDevice->startStopLock);
  35427. {
  35428. /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. */
  35429. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  35430. ma_device__set_state(pDevice, ma_device_state_starting);
  35431. /* Asynchronous backends need to be handled differently. */
  35432. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35433. if (pDevice->pContext->callbacks.onDeviceStart != NULL) {
  35434. result = pDevice->pContext->callbacks.onDeviceStart(pDevice);
  35435. } else {
  35436. result = MA_INVALID_OPERATION;
  35437. }
  35438. if (result == MA_SUCCESS) {
  35439. ma_device__set_state(pDevice, ma_device_state_started);
  35440. ma_device__on_notification_started(pDevice);
  35441. }
  35442. } else {
  35443. /*
  35444. Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the
  35445. thread and then wait for the start event.
  35446. */
  35447. ma_event_signal(&pDevice->wakeupEvent);
  35448. /*
  35449. Wait for the worker thread to finish starting the device. Note that the worker thread will be the one who puts the device
  35450. into the started state. Don't call ma_device__set_state() here.
  35451. */
  35452. ma_event_wait(&pDevice->startEvent);
  35453. result = pDevice->workResult;
  35454. }
  35455. /* We changed the state from stopped to started, so if we failed, make sure we put the state back to stopped. */
  35456. if (result != MA_SUCCESS) {
  35457. ma_device__set_state(pDevice, ma_device_state_stopped);
  35458. }
  35459. }
  35460. ma_mutex_unlock(&pDevice->startStopLock);
  35461. return result;
  35462. }
  35463. MA_API ma_result ma_device_stop(ma_device* pDevice)
  35464. {
  35465. ma_result result;
  35466. if (pDevice == NULL) {
  35467. return MA_INVALID_ARGS;
  35468. }
  35469. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  35470. return MA_INVALID_OPERATION; /* Not initialized. */
  35471. }
  35472. if (ma_device_get_state(pDevice) == ma_device_state_stopped) {
  35473. return MA_SUCCESS; /* Already stopped. */
  35474. }
  35475. ma_mutex_lock(&pDevice->startStopLock);
  35476. {
  35477. /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a started or paused state. */
  35478. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_started);
  35479. ma_device__set_state(pDevice, ma_device_state_stopping);
  35480. /* Asynchronous backends need to be handled differently. */
  35481. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  35482. /* Asynchronous backends must have a stop operation. */
  35483. if (pDevice->pContext->callbacks.onDeviceStop != NULL) {
  35484. result = pDevice->pContext->callbacks.onDeviceStop(pDevice);
  35485. } else {
  35486. result = MA_INVALID_OPERATION;
  35487. }
  35488. ma_device__set_state(pDevice, ma_device_state_stopped);
  35489. } else {
  35490. /*
  35491. Synchronous backends. The stop callback is always called from the worker thread. Do not call the stop callback here. If
  35492. 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
  35493. sure the state of the device is *not* playing right now, which it shouldn't be since we set it above. This is super
  35494. important though, so I'm asserting it here as well for extra safety in case we accidentally change something later.
  35495. */
  35496. MA_ASSERT(ma_device_get_state(pDevice) != ma_device_state_started);
  35497. if (pDevice->pContext->callbacks.onDeviceDataLoopWakeup != NULL) {
  35498. pDevice->pContext->callbacks.onDeviceDataLoopWakeup(pDevice);
  35499. }
  35500. /*
  35501. We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be
  35502. the one who puts the device into the stopped state. Don't call ma_device__set_state() here.
  35503. */
  35504. ma_event_wait(&pDevice->stopEvent);
  35505. result = MA_SUCCESS;
  35506. }
  35507. /*
  35508. This is a safety measure to ensure the internal buffer has been cleared so any leftover
  35509. does not get played the next time the device starts. Ideally this should be drained by
  35510. the backend first.
  35511. */
  35512. pDevice->playback.intermediaryBufferLen = 0;
  35513. pDevice->playback.inputCacheConsumed = 0;
  35514. pDevice->playback.inputCacheRemaining = 0;
  35515. }
  35516. ma_mutex_unlock(&pDevice->startStopLock);
  35517. return result;
  35518. }
  35519. MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice)
  35520. {
  35521. return ma_device_get_state(pDevice) == ma_device_state_started;
  35522. }
  35523. MA_API ma_device_state ma_device_get_state(const ma_device* pDevice)
  35524. {
  35525. if (pDevice == NULL) {
  35526. return ma_device_state_uninitialized;
  35527. }
  35528. return ma_atomic_device_state_get((ma_atomic_device_state*)&pDevice->state); /* Naughty cast to get rid of a const warning. */
  35529. }
  35530. MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume)
  35531. {
  35532. if (pDevice == NULL) {
  35533. return MA_INVALID_ARGS;
  35534. }
  35535. if (volume < 0.0f) {
  35536. return MA_INVALID_ARGS;
  35537. }
  35538. ma_atomic_float_set(&pDevice->masterVolumeFactor, volume);
  35539. return MA_SUCCESS;
  35540. }
  35541. MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume)
  35542. {
  35543. if (pVolume == NULL) {
  35544. return MA_INVALID_ARGS;
  35545. }
  35546. if (pDevice == NULL) {
  35547. *pVolume = 0;
  35548. return MA_INVALID_ARGS;
  35549. }
  35550. *pVolume = ma_atomic_float_get(&pDevice->masterVolumeFactor);
  35551. return MA_SUCCESS;
  35552. }
  35553. MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB)
  35554. {
  35555. if (gainDB > 0) {
  35556. return MA_INVALID_ARGS;
  35557. }
  35558. return ma_device_set_master_volume(pDevice, ma_volume_db_to_linear(gainDB));
  35559. }
  35560. MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB)
  35561. {
  35562. float factor;
  35563. ma_result result;
  35564. if (pGainDB == NULL) {
  35565. return MA_INVALID_ARGS;
  35566. }
  35567. result = ma_device_get_master_volume(pDevice, &factor);
  35568. if (result != MA_SUCCESS) {
  35569. *pGainDB = 0;
  35570. return result;
  35571. }
  35572. *pGainDB = ma_volume_linear_to_db(factor);
  35573. return MA_SUCCESS;
  35574. }
  35575. MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  35576. {
  35577. if (pDevice == NULL) {
  35578. return MA_INVALID_ARGS;
  35579. }
  35580. if (pOutput == NULL && pInput == NULL) {
  35581. return MA_INVALID_ARGS;
  35582. }
  35583. if (pDevice->type == ma_device_type_duplex) {
  35584. if (pInput != NULL) {
  35585. ma_device__handle_duplex_callback_capture(pDevice, frameCount, pInput, &pDevice->duplexRB.rb);
  35586. }
  35587. if (pOutput != NULL) {
  35588. ma_device__handle_duplex_callback_playback(pDevice, frameCount, pOutput, &pDevice->duplexRB.rb);
  35589. }
  35590. } else {
  35591. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_loopback) {
  35592. if (pInput == NULL) {
  35593. return MA_INVALID_ARGS;
  35594. }
  35595. ma_device__send_frames_to_client(pDevice, frameCount, pInput);
  35596. }
  35597. if (pDevice->type == ma_device_type_playback) {
  35598. if (pOutput == NULL) {
  35599. return MA_INVALID_ARGS;
  35600. }
  35601. ma_device__read_frames_from_client(pDevice, frameCount, pOutput);
  35602. }
  35603. }
  35604. return MA_SUCCESS;
  35605. }
  35606. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  35607. {
  35608. if (pDescriptor == NULL) {
  35609. return 0;
  35610. }
  35611. /*
  35612. We must have a non-0 native sample rate, but some backends don't allow retrieval of this at the
  35613. time when the size of the buffer needs to be determined. In this case we need to just take a best
  35614. guess and move on. We'll try using the sample rate in pDescriptor first. If that's not set we'll
  35615. just fall back to MA_DEFAULT_SAMPLE_RATE.
  35616. */
  35617. if (nativeSampleRate == 0) {
  35618. nativeSampleRate = pDescriptor->sampleRate;
  35619. }
  35620. if (nativeSampleRate == 0) {
  35621. nativeSampleRate = MA_DEFAULT_SAMPLE_RATE;
  35622. }
  35623. MA_ASSERT(nativeSampleRate != 0);
  35624. if (pDescriptor->periodSizeInFrames == 0) {
  35625. if (pDescriptor->periodSizeInMilliseconds == 0) {
  35626. if (performanceProfile == ma_performance_profile_low_latency) {
  35627. return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, nativeSampleRate);
  35628. } else {
  35629. return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, nativeSampleRate);
  35630. }
  35631. } else {
  35632. return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  35633. }
  35634. } else {
  35635. return pDescriptor->periodSizeInFrames;
  35636. }
  35637. }
  35638. #endif /* MA_NO_DEVICE_IO */
  35639. MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate)
  35640. {
  35641. /* Prevent a division by zero. */
  35642. if (sampleRate == 0) {
  35643. return 0;
  35644. }
  35645. return bufferSizeInFrames*1000 / sampleRate;
  35646. }
  35647. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate)
  35648. {
  35649. /* Prevent a division by zero. */
  35650. if (sampleRate == 0) {
  35651. return 0;
  35652. }
  35653. return bufferSizeInMilliseconds*sampleRate / 1000;
  35654. }
  35655. MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  35656. {
  35657. if (dst == src) {
  35658. return; /* No-op. */
  35659. }
  35660. ma_copy_memory_64(dst, src, frameCount * ma_get_bytes_per_frame(format, channels));
  35661. }
  35662. MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  35663. {
  35664. if (format == ma_format_u8) {
  35665. ma_uint64 sampleCount = frameCount * channels;
  35666. ma_uint64 iSample;
  35667. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35668. ((ma_uint8*)p)[iSample] = 128;
  35669. }
  35670. } else {
  35671. ma_zero_memory_64(p, frameCount * ma_get_bytes_per_frame(format, channels));
  35672. }
  35673. }
  35674. MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
  35675. {
  35676. return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
  35677. }
  35678. MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
  35679. {
  35680. return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
  35681. }
  35682. MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count)
  35683. {
  35684. ma_uint64 iSample;
  35685. MA_ASSERT(pDst != NULL);
  35686. MA_ASSERT(pSrc != NULL);
  35687. for (iSample = 0; iSample < count; iSample += 1) {
  35688. pDst[iSample] = ma_clip_u8(pSrc[iSample]);
  35689. }
  35690. }
  35691. MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count)
  35692. {
  35693. ma_uint64 iSample;
  35694. MA_ASSERT(pDst != NULL);
  35695. MA_ASSERT(pSrc != NULL);
  35696. for (iSample = 0; iSample < count; iSample += 1) {
  35697. pDst[iSample] = ma_clip_s16(pSrc[iSample]);
  35698. }
  35699. }
  35700. MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count)
  35701. {
  35702. ma_uint64 iSample;
  35703. MA_ASSERT(pDst != NULL);
  35704. MA_ASSERT(pSrc != NULL);
  35705. for (iSample = 0; iSample < count; iSample += 1) {
  35706. ma_int64 s = ma_clip_s24(pSrc[iSample]);
  35707. pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0);
  35708. pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8);
  35709. pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16);
  35710. }
  35711. }
  35712. MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count)
  35713. {
  35714. ma_uint64 iSample;
  35715. MA_ASSERT(pDst != NULL);
  35716. MA_ASSERT(pSrc != NULL);
  35717. for (iSample = 0; iSample < count; iSample += 1) {
  35718. pDst[iSample] = ma_clip_s32(pSrc[iSample]);
  35719. }
  35720. }
  35721. MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count)
  35722. {
  35723. ma_uint64 iSample;
  35724. MA_ASSERT(pDst != NULL);
  35725. MA_ASSERT(pSrc != NULL);
  35726. for (iSample = 0; iSample < count; iSample += 1) {
  35727. pDst[iSample] = ma_clip_f32(pSrc[iSample]);
  35728. }
  35729. }
  35730. MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  35731. {
  35732. ma_uint64 sampleCount;
  35733. MA_ASSERT(pDst != NULL);
  35734. MA_ASSERT(pSrc != NULL);
  35735. sampleCount = frameCount * channels;
  35736. switch (format) {
  35737. case ma_format_u8: ma_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount); break;
  35738. case ma_format_s16: ma_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount); break;
  35739. case ma_format_s24: ma_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount); break;
  35740. case ma_format_s32: ma_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount); break;
  35741. case ma_format_f32: ma_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount); break;
  35742. /* 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. */
  35743. case ma_format_unknown:
  35744. case ma_format_count:
  35745. break;
  35746. }
  35747. }
  35748. MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor)
  35749. {
  35750. ma_uint64 iSample;
  35751. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35752. return;
  35753. }
  35754. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35755. pSamplesOut[iSample] = (ma_uint8)(pSamplesIn[iSample] * factor);
  35756. }
  35757. }
  35758. MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor)
  35759. {
  35760. ma_uint64 iSample;
  35761. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35762. return;
  35763. }
  35764. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35765. pSamplesOut[iSample] = (ma_int16)(pSamplesIn[iSample] * factor);
  35766. }
  35767. }
  35768. MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor)
  35769. {
  35770. ma_uint64 iSample;
  35771. ma_uint8* pSamplesOut8;
  35772. ma_uint8* pSamplesIn8;
  35773. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35774. return;
  35775. }
  35776. pSamplesOut8 = (ma_uint8*)pSamplesOut;
  35777. pSamplesIn8 = (ma_uint8*)pSamplesIn;
  35778. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35779. ma_int32 sampleS32;
  35780. sampleS32 = (ma_int32)(((ma_uint32)(pSamplesIn8[iSample*3+0]) << 8) | ((ma_uint32)(pSamplesIn8[iSample*3+1]) << 16) | ((ma_uint32)(pSamplesIn8[iSample*3+2])) << 24);
  35781. sampleS32 = (ma_int32)(sampleS32 * factor);
  35782. pSamplesOut8[iSample*3+0] = (ma_uint8)(((ma_uint32)sampleS32 & 0x0000FF00) >> 8);
  35783. pSamplesOut8[iSample*3+1] = (ma_uint8)(((ma_uint32)sampleS32 & 0x00FF0000) >> 16);
  35784. pSamplesOut8[iSample*3+2] = (ma_uint8)(((ma_uint32)sampleS32 & 0xFF000000) >> 24);
  35785. }
  35786. }
  35787. MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor)
  35788. {
  35789. ma_uint64 iSample;
  35790. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35791. return;
  35792. }
  35793. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35794. pSamplesOut[iSample] = (ma_int32)(pSamplesIn[iSample] * factor);
  35795. }
  35796. }
  35797. MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor)
  35798. {
  35799. ma_uint64 iSample;
  35800. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  35801. return;
  35802. }
  35803. if (factor == 1) {
  35804. if (pSamplesOut == pSamplesIn) {
  35805. /* In place. No-op. */
  35806. } else {
  35807. /* Just a copy. */
  35808. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35809. pSamplesOut[iSample] = pSamplesIn[iSample];
  35810. }
  35811. }
  35812. } else {
  35813. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  35814. pSamplesOut[iSample] = pSamplesIn[iSample] * factor;
  35815. }
  35816. }
  35817. }
  35818. MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor)
  35819. {
  35820. ma_copy_and_apply_volume_factor_u8(pSamples, pSamples, sampleCount, factor);
  35821. }
  35822. MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor)
  35823. {
  35824. ma_copy_and_apply_volume_factor_s16(pSamples, pSamples, sampleCount, factor);
  35825. }
  35826. MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor)
  35827. {
  35828. ma_copy_and_apply_volume_factor_s24(pSamples, pSamples, sampleCount, factor);
  35829. }
  35830. MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor)
  35831. {
  35832. ma_copy_and_apply_volume_factor_s32(pSamples, pSamples, sampleCount, factor);
  35833. }
  35834. MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor)
  35835. {
  35836. ma_copy_and_apply_volume_factor_f32(pSamples, pSamples, sampleCount, factor);
  35837. }
  35838. 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)
  35839. {
  35840. ma_copy_and_apply_volume_factor_u8(pFramesOut, pFramesIn, frameCount*channels, factor);
  35841. }
  35842. 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)
  35843. {
  35844. ma_copy_and_apply_volume_factor_s16(pFramesOut, pFramesIn, frameCount*channels, factor);
  35845. }
  35846. 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)
  35847. {
  35848. ma_copy_and_apply_volume_factor_s24(pFramesOut, pFramesIn, frameCount*channels, factor);
  35849. }
  35850. 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)
  35851. {
  35852. ma_copy_and_apply_volume_factor_s32(pFramesOut, pFramesIn, frameCount*channels, factor);
  35853. }
  35854. 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)
  35855. {
  35856. ma_copy_and_apply_volume_factor_f32(pFramesOut, pFramesIn, frameCount*channels, factor);
  35857. }
  35858. 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)
  35859. {
  35860. switch (format)
  35861. {
  35862. case ma_format_u8: ma_copy_and_apply_volume_factor_pcm_frames_u8 ((ma_uint8*)pFramesOut, (const ma_uint8*)pFramesIn, frameCount, channels, factor); return;
  35863. case ma_format_s16: ma_copy_and_apply_volume_factor_pcm_frames_s16((ma_int16*)pFramesOut, (const ma_int16*)pFramesIn, frameCount, channels, factor); return;
  35864. case ma_format_s24: ma_copy_and_apply_volume_factor_pcm_frames_s24( pFramesOut, pFramesIn, frameCount, channels, factor); return;
  35865. case ma_format_s32: ma_copy_and_apply_volume_factor_pcm_frames_s32((ma_int32*)pFramesOut, (const ma_int32*)pFramesIn, frameCount, channels, factor); return;
  35866. case ma_format_f32: ma_copy_and_apply_volume_factor_pcm_frames_f32( (float*)pFramesOut, (const float*)pFramesIn, frameCount, channels, factor); return;
  35867. default: return; /* Do nothing. */
  35868. }
  35869. }
  35870. MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35871. {
  35872. ma_copy_and_apply_volume_factor_pcm_frames_u8(pFrames, pFrames, frameCount, channels, factor);
  35873. }
  35874. MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35875. {
  35876. ma_copy_and_apply_volume_factor_pcm_frames_s16(pFrames, pFrames, frameCount, channels, factor);
  35877. }
  35878. MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35879. {
  35880. ma_copy_and_apply_volume_factor_pcm_frames_s24(pFrames, pFrames, frameCount, channels, factor);
  35881. }
  35882. MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35883. {
  35884. ma_copy_and_apply_volume_factor_pcm_frames_s32(pFrames, pFrames, frameCount, channels, factor);
  35885. }
  35886. MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  35887. {
  35888. ma_copy_and_apply_volume_factor_pcm_frames_f32(pFrames, pFrames, frameCount, channels, factor);
  35889. }
  35890. MA_API void ma_apply_volume_factor_pcm_frames(void* pFramesOut, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor)
  35891. {
  35892. ma_copy_and_apply_volume_factor_pcm_frames(pFramesOut, pFramesOut, frameCount, format, channels, factor);
  35893. }
  35894. 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)
  35895. {
  35896. ma_uint64 iFrame;
  35897. if (channels == 2) {
  35898. /* TODO: Do an optimized implementation for stereo and mono. Can do a SIMD optimized implementation as well. */
  35899. }
  35900. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35901. ma_uint32 iChannel;
  35902. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35903. pFramesOut[iFrame * channels + iChannel] = pFramesIn[iFrame * channels + iChannel] * pChannelGains[iChannel];
  35904. }
  35905. }
  35906. }
  35907. static MA_INLINE ma_int16 ma_apply_volume_unclipped_u8(ma_int16 x, ma_int16 volume)
  35908. {
  35909. return (ma_int16)(((ma_int32)x * (ma_int32)volume) >> 8);
  35910. }
  35911. static MA_INLINE ma_int32 ma_apply_volume_unclipped_s16(ma_int32 x, ma_int16 volume)
  35912. {
  35913. return (ma_int32)((x * volume) >> 8);
  35914. }
  35915. static MA_INLINE ma_int64 ma_apply_volume_unclipped_s24(ma_int64 x, ma_int16 volume)
  35916. {
  35917. return (ma_int64)((x * volume) >> 8);
  35918. }
  35919. static MA_INLINE ma_int64 ma_apply_volume_unclipped_s32(ma_int64 x, ma_int16 volume)
  35920. {
  35921. return (ma_int64)((x * volume) >> 8);
  35922. }
  35923. static MA_INLINE float ma_apply_volume_unclipped_f32(float x, float volume)
  35924. {
  35925. return x * volume;
  35926. }
  35927. MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume)
  35928. {
  35929. ma_uint64 iSample;
  35930. ma_int16 volumeFixed;
  35931. MA_ASSERT(pDst != NULL);
  35932. MA_ASSERT(pSrc != NULL);
  35933. volumeFixed = ma_float_to_fixed_16(volume);
  35934. for (iSample = 0; iSample < count; iSample += 1) {
  35935. pDst[iSample] = ma_clip_u8(ma_apply_volume_unclipped_u8(pSrc[iSample], volumeFixed));
  35936. }
  35937. }
  35938. MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume)
  35939. {
  35940. ma_uint64 iSample;
  35941. ma_int16 volumeFixed;
  35942. MA_ASSERT(pDst != NULL);
  35943. MA_ASSERT(pSrc != NULL);
  35944. volumeFixed = ma_float_to_fixed_16(volume);
  35945. for (iSample = 0; iSample < count; iSample += 1) {
  35946. pDst[iSample] = ma_clip_s16(ma_apply_volume_unclipped_s16(pSrc[iSample], volumeFixed));
  35947. }
  35948. }
  35949. MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume)
  35950. {
  35951. ma_uint64 iSample;
  35952. ma_int16 volumeFixed;
  35953. MA_ASSERT(pDst != NULL);
  35954. MA_ASSERT(pSrc != NULL);
  35955. volumeFixed = ma_float_to_fixed_16(volume);
  35956. for (iSample = 0; iSample < count; iSample += 1) {
  35957. ma_int64 s = ma_clip_s24(ma_apply_volume_unclipped_s24(pSrc[iSample], volumeFixed));
  35958. pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0);
  35959. pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8);
  35960. pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16);
  35961. }
  35962. }
  35963. MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume)
  35964. {
  35965. ma_uint64 iSample;
  35966. ma_int16 volumeFixed;
  35967. MA_ASSERT(pDst != NULL);
  35968. MA_ASSERT(pSrc != NULL);
  35969. volumeFixed = ma_float_to_fixed_16(volume);
  35970. for (iSample = 0; iSample < count; iSample += 1) {
  35971. pDst[iSample] = ma_clip_s32(ma_apply_volume_unclipped_s32(pSrc[iSample], volumeFixed));
  35972. }
  35973. }
  35974. MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume)
  35975. {
  35976. ma_uint64 iSample;
  35977. MA_ASSERT(pDst != NULL);
  35978. MA_ASSERT(pSrc != NULL);
  35979. /* For the f32 case we need to make sure this supports in-place processing where the input and output buffers are the same. */
  35980. for (iSample = 0; iSample < count; iSample += 1) {
  35981. pDst[iSample] = ma_clip_f32(ma_apply_volume_unclipped_f32(pSrc[iSample], volume));
  35982. }
  35983. }
  35984. 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)
  35985. {
  35986. MA_ASSERT(pDst != NULL);
  35987. MA_ASSERT(pSrc != NULL);
  35988. if (volume == 1) {
  35989. ma_clip_pcm_frames(pDst, pSrc, frameCount, format, channels); /* Optimized case for volume = 1. */
  35990. } else if (volume == 0) {
  35991. ma_silence_pcm_frames(pDst, frameCount, format, channels); /* Optimized case for volume = 0. */
  35992. } else {
  35993. ma_uint64 sampleCount = frameCount * channels;
  35994. switch (format) {
  35995. case ma_format_u8: ma_copy_and_apply_volume_and_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount, volume); break;
  35996. case ma_format_s16: ma_copy_and_apply_volume_and_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount, volume); break;
  35997. case ma_format_s24: ma_copy_and_apply_volume_and_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break;
  35998. case ma_format_s32: ma_copy_and_apply_volume_and_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break;
  35999. case ma_format_f32: ma_copy_and_apply_volume_and_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount, volume); break;
  36000. /* 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. */
  36001. case ma_format_unknown:
  36002. case ma_format_count:
  36003. break;
  36004. }
  36005. }
  36006. }
  36007. MA_API float ma_volume_linear_to_db(float factor)
  36008. {
  36009. return 20*ma_log10f(factor);
  36010. }
  36011. MA_API float ma_volume_db_to_linear(float gain)
  36012. {
  36013. return ma_powf(10, gain/20.0f);
  36014. }
  36015. MA_API ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume)
  36016. {
  36017. ma_uint64 iSample;
  36018. ma_uint64 sampleCount;
  36019. if (pDst == NULL || pSrc == NULL || channels == 0) {
  36020. return MA_INVALID_ARGS;
  36021. }
  36022. if (volume == 0) {
  36023. return MA_SUCCESS; /* No changes if the volume is 0. */
  36024. }
  36025. sampleCount = frameCount * channels;
  36026. if (volume == 1) {
  36027. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  36028. pDst[iSample] += pSrc[iSample];
  36029. }
  36030. } else {
  36031. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  36032. pDst[iSample] += ma_apply_volume_unclipped_f32(pSrc[iSample], volume);
  36033. }
  36034. }
  36035. return MA_SUCCESS;
  36036. }
  36037. /**************************************************************************************************************************************************************
  36038. Format Conversion
  36039. **************************************************************************************************************************************************************/
  36040. static MA_INLINE ma_int16 ma_pcm_sample_f32_to_s16(float x)
  36041. {
  36042. return (ma_int16)(x * 32767.0f);
  36043. }
  36044. static MA_INLINE ma_int16 ma_pcm_sample_u8_to_s16_no_scale(ma_uint8 x)
  36045. {
  36046. return (ma_int16)((ma_int16)x - 128);
  36047. }
  36048. static MA_INLINE ma_int64 ma_pcm_sample_s24_to_s32_no_scale(const ma_uint8* x)
  36049. {
  36050. 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. */
  36051. }
  36052. static MA_INLINE void ma_pcm_sample_s32_to_s24_no_scale(ma_int64 x, ma_uint8* s24)
  36053. {
  36054. s24[0] = (ma_uint8)((x & 0x000000FF) >> 0);
  36055. s24[1] = (ma_uint8)((x & 0x0000FF00) >> 8);
  36056. s24[2] = (ma_uint8)((x & 0x00FF0000) >> 16);
  36057. }
  36058. /* u8 */
  36059. MA_API void ma_pcm_u8_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36060. {
  36061. (void)ditherMode;
  36062. ma_copy_memory_64(dst, src, count * sizeof(ma_uint8));
  36063. }
  36064. static MA_INLINE void ma_pcm_u8_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36065. {
  36066. ma_int16* dst_s16 = (ma_int16*)dst;
  36067. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36068. ma_uint64 i;
  36069. for (i = 0; i < count; i += 1) {
  36070. ma_int16 x = src_u8[i];
  36071. x = (ma_int16)(x - 128);
  36072. x = (ma_int16)(x << 8);
  36073. dst_s16[i] = x;
  36074. }
  36075. (void)ditherMode;
  36076. }
  36077. static MA_INLINE void ma_pcm_u8_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36078. {
  36079. ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode);
  36080. }
  36081. #if defined(MA_SUPPORT_SSE2)
  36082. static MA_INLINE void ma_pcm_u8_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36083. {
  36084. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  36085. }
  36086. #endif
  36087. #if defined(MA_SUPPORT_NEON)
  36088. static MA_INLINE void ma_pcm_u8_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36089. {
  36090. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  36091. }
  36092. #endif
  36093. MA_API void ma_pcm_u8_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36094. {
  36095. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36096. ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode);
  36097. #else
  36098. # if defined(MA_SUPPORT_SSE2)
  36099. if (ma_has_sse2()) {
  36100. ma_pcm_u8_to_s16__sse2(dst, src, count, ditherMode);
  36101. } else
  36102. #elif defined(MA_SUPPORT_NEON)
  36103. if (ma_has_neon()) {
  36104. ma_pcm_u8_to_s16__neon(dst, src, count, ditherMode);
  36105. } else
  36106. #endif
  36107. {
  36108. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  36109. }
  36110. #endif
  36111. }
  36112. static MA_INLINE void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36113. {
  36114. ma_uint8* dst_s24 = (ma_uint8*)dst;
  36115. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36116. ma_uint64 i;
  36117. for (i = 0; i < count; i += 1) {
  36118. ma_int16 x = src_u8[i];
  36119. x = (ma_int16)(x - 128);
  36120. dst_s24[i*3+0] = 0;
  36121. dst_s24[i*3+1] = 0;
  36122. dst_s24[i*3+2] = (ma_uint8)((ma_int8)x);
  36123. }
  36124. (void)ditherMode;
  36125. }
  36126. static MA_INLINE void ma_pcm_u8_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36127. {
  36128. ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode);
  36129. }
  36130. #if defined(MA_SUPPORT_SSE2)
  36131. static MA_INLINE void ma_pcm_u8_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36132. {
  36133. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  36134. }
  36135. #endif
  36136. #if defined(MA_SUPPORT_NEON)
  36137. static MA_INLINE void ma_pcm_u8_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36138. {
  36139. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  36140. }
  36141. #endif
  36142. MA_API void ma_pcm_u8_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36143. {
  36144. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36145. ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode);
  36146. #else
  36147. # if defined(MA_SUPPORT_SSE2)
  36148. if (ma_has_sse2()) {
  36149. ma_pcm_u8_to_s24__sse2(dst, src, count, ditherMode);
  36150. } else
  36151. #elif defined(MA_SUPPORT_NEON)
  36152. if (ma_has_neon()) {
  36153. ma_pcm_u8_to_s24__neon(dst, src, count, ditherMode);
  36154. } else
  36155. #endif
  36156. {
  36157. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  36158. }
  36159. #endif
  36160. }
  36161. static MA_INLINE void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36162. {
  36163. ma_int32* dst_s32 = (ma_int32*)dst;
  36164. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36165. ma_uint64 i;
  36166. for (i = 0; i < count; i += 1) {
  36167. ma_int32 x = src_u8[i];
  36168. x = x - 128;
  36169. x = x << 24;
  36170. dst_s32[i] = x;
  36171. }
  36172. (void)ditherMode;
  36173. }
  36174. static MA_INLINE void ma_pcm_u8_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36175. {
  36176. ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode);
  36177. }
  36178. #if defined(MA_SUPPORT_SSE2)
  36179. static MA_INLINE void ma_pcm_u8_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36180. {
  36181. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  36182. }
  36183. #endif
  36184. #if defined(MA_SUPPORT_NEON)
  36185. static MA_INLINE void ma_pcm_u8_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36186. {
  36187. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  36188. }
  36189. #endif
  36190. MA_API void ma_pcm_u8_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36191. {
  36192. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36193. ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode);
  36194. #else
  36195. # if defined(MA_SUPPORT_SSE2)
  36196. if (ma_has_sse2()) {
  36197. ma_pcm_u8_to_s32__sse2(dst, src, count, ditherMode);
  36198. } else
  36199. #elif defined(MA_SUPPORT_NEON)
  36200. if (ma_has_neon()) {
  36201. ma_pcm_u8_to_s32__neon(dst, src, count, ditherMode);
  36202. } else
  36203. #endif
  36204. {
  36205. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  36206. }
  36207. #endif
  36208. }
  36209. static MA_INLINE void ma_pcm_u8_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36210. {
  36211. float* dst_f32 = (float*)dst;
  36212. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36213. ma_uint64 i;
  36214. for (i = 0; i < count; i += 1) {
  36215. float x = (float)src_u8[i];
  36216. x = x * 0.00784313725490196078f; /* 0..255 to 0..2 */
  36217. x = x - 1; /* 0..2 to -1..1 */
  36218. dst_f32[i] = x;
  36219. }
  36220. (void)ditherMode;
  36221. }
  36222. static MA_INLINE void ma_pcm_u8_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36223. {
  36224. ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
  36225. }
  36226. #if defined(MA_SUPPORT_SSE2)
  36227. static MA_INLINE void ma_pcm_u8_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36228. {
  36229. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  36230. }
  36231. #endif
  36232. #if defined(MA_SUPPORT_NEON)
  36233. static MA_INLINE void ma_pcm_u8_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36234. {
  36235. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  36236. }
  36237. #endif
  36238. MA_API void ma_pcm_u8_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36239. {
  36240. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36241. ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
  36242. #else
  36243. # if defined(MA_SUPPORT_SSE2)
  36244. if (ma_has_sse2()) {
  36245. ma_pcm_u8_to_f32__sse2(dst, src, count, ditherMode);
  36246. } else
  36247. #elif defined(MA_SUPPORT_NEON)
  36248. if (ma_has_neon()) {
  36249. ma_pcm_u8_to_f32__neon(dst, src, count, ditherMode);
  36250. } else
  36251. #endif
  36252. {
  36253. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  36254. }
  36255. #endif
  36256. }
  36257. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36258. static MA_INLINE void ma_pcm_interleave_u8__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36259. {
  36260. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36261. const ma_uint8** src_u8 = (const ma_uint8**)src;
  36262. ma_uint64 iFrame;
  36263. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36264. ma_uint32 iChannel;
  36265. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36266. dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
  36267. }
  36268. }
  36269. }
  36270. #else
  36271. static MA_INLINE void ma_pcm_interleave_u8__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36272. {
  36273. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36274. const ma_uint8** src_u8 = (const ma_uint8**)src;
  36275. if (channels == 1) {
  36276. ma_copy_memory_64(dst, src[0], frameCount * sizeof(ma_uint8));
  36277. } else if (channels == 2) {
  36278. ma_uint64 iFrame;
  36279. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36280. dst_u8[iFrame*2 + 0] = src_u8[0][iFrame];
  36281. dst_u8[iFrame*2 + 1] = src_u8[1][iFrame];
  36282. }
  36283. } else {
  36284. ma_uint64 iFrame;
  36285. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36286. ma_uint32 iChannel;
  36287. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36288. dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
  36289. }
  36290. }
  36291. }
  36292. }
  36293. #endif
  36294. MA_API void ma_pcm_interleave_u8(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36295. {
  36296. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36297. ma_pcm_interleave_u8__reference(dst, src, frameCount, channels);
  36298. #else
  36299. ma_pcm_interleave_u8__optimized(dst, src, frameCount, channels);
  36300. #endif
  36301. }
  36302. static MA_INLINE void ma_pcm_deinterleave_u8__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36303. {
  36304. ma_uint8** dst_u8 = (ma_uint8**)dst;
  36305. const ma_uint8* src_u8 = (const ma_uint8*)src;
  36306. ma_uint64 iFrame;
  36307. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36308. ma_uint32 iChannel;
  36309. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36310. dst_u8[iChannel][iFrame] = src_u8[iFrame*channels + iChannel];
  36311. }
  36312. }
  36313. }
  36314. static MA_INLINE void ma_pcm_deinterleave_u8__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36315. {
  36316. ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
  36317. }
  36318. MA_API void ma_pcm_deinterleave_u8(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36319. {
  36320. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36321. ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
  36322. #else
  36323. ma_pcm_deinterleave_u8__optimized(dst, src, frameCount, channels);
  36324. #endif
  36325. }
  36326. /* s16 */
  36327. static MA_INLINE void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36328. {
  36329. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36330. const ma_int16* src_s16 = (const ma_int16*)src;
  36331. if (ditherMode == ma_dither_mode_none) {
  36332. ma_uint64 i;
  36333. for (i = 0; i < count; i += 1) {
  36334. ma_int16 x = src_s16[i];
  36335. x = (ma_int16)(x >> 8);
  36336. x = (ma_int16)(x + 128);
  36337. dst_u8[i] = (ma_uint8)x;
  36338. }
  36339. } else {
  36340. ma_uint64 i;
  36341. for (i = 0; i < count; i += 1) {
  36342. ma_int16 x = src_s16[i];
  36343. /* Dither. Don't overflow. */
  36344. ma_int32 dither = ma_dither_s32(ditherMode, -0x80, 0x7F);
  36345. if ((x + dither) <= 0x7FFF) {
  36346. x = (ma_int16)(x + dither);
  36347. } else {
  36348. x = 0x7FFF;
  36349. }
  36350. x = (ma_int16)(x >> 8);
  36351. x = (ma_int16)(x + 128);
  36352. dst_u8[i] = (ma_uint8)x;
  36353. }
  36354. }
  36355. }
  36356. static MA_INLINE void ma_pcm_s16_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36357. {
  36358. ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
  36359. }
  36360. #if defined(MA_SUPPORT_SSE2)
  36361. static MA_INLINE void ma_pcm_s16_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36362. {
  36363. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  36364. }
  36365. #endif
  36366. #if defined(MA_SUPPORT_NEON)
  36367. static MA_INLINE void ma_pcm_s16_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36368. {
  36369. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  36370. }
  36371. #endif
  36372. MA_API void ma_pcm_s16_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36373. {
  36374. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36375. ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
  36376. #else
  36377. # if defined(MA_SUPPORT_SSE2)
  36378. if (ma_has_sse2()) {
  36379. ma_pcm_s16_to_u8__sse2(dst, src, count, ditherMode);
  36380. } else
  36381. #elif defined(MA_SUPPORT_NEON)
  36382. if (ma_has_neon()) {
  36383. ma_pcm_s16_to_u8__neon(dst, src, count, ditherMode);
  36384. } else
  36385. #endif
  36386. {
  36387. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  36388. }
  36389. #endif
  36390. }
  36391. MA_API void ma_pcm_s16_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36392. {
  36393. (void)ditherMode;
  36394. ma_copy_memory_64(dst, src, count * sizeof(ma_int16));
  36395. }
  36396. static MA_INLINE void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36397. {
  36398. ma_uint8* dst_s24 = (ma_uint8*)dst;
  36399. const ma_int16* src_s16 = (const ma_int16*)src;
  36400. ma_uint64 i;
  36401. for (i = 0; i < count; i += 1) {
  36402. dst_s24[i*3+0] = 0;
  36403. dst_s24[i*3+1] = (ma_uint8)(src_s16[i] & 0xFF);
  36404. dst_s24[i*3+2] = (ma_uint8)(src_s16[i] >> 8);
  36405. }
  36406. (void)ditherMode;
  36407. }
  36408. static MA_INLINE void ma_pcm_s16_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36409. {
  36410. ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode);
  36411. }
  36412. #if defined(MA_SUPPORT_SSE2)
  36413. static MA_INLINE void ma_pcm_s16_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36414. {
  36415. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  36416. }
  36417. #endif
  36418. #if defined(MA_SUPPORT_NEON)
  36419. static MA_INLINE void ma_pcm_s16_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36420. {
  36421. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  36422. }
  36423. #endif
  36424. MA_API void ma_pcm_s16_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36425. {
  36426. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36427. ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode);
  36428. #else
  36429. # if defined(MA_SUPPORT_SSE2)
  36430. if (ma_has_sse2()) {
  36431. ma_pcm_s16_to_s24__sse2(dst, src, count, ditherMode);
  36432. } else
  36433. #elif defined(MA_SUPPORT_NEON)
  36434. if (ma_has_neon()) {
  36435. ma_pcm_s16_to_s24__neon(dst, src, count, ditherMode);
  36436. } else
  36437. #endif
  36438. {
  36439. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  36440. }
  36441. #endif
  36442. }
  36443. static MA_INLINE void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36444. {
  36445. ma_int32* dst_s32 = (ma_int32*)dst;
  36446. const ma_int16* src_s16 = (const ma_int16*)src;
  36447. ma_uint64 i;
  36448. for (i = 0; i < count; i += 1) {
  36449. dst_s32[i] = src_s16[i] << 16;
  36450. }
  36451. (void)ditherMode;
  36452. }
  36453. static MA_INLINE void ma_pcm_s16_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36454. {
  36455. ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode);
  36456. }
  36457. #if defined(MA_SUPPORT_SSE2)
  36458. static MA_INLINE void ma_pcm_s16_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36459. {
  36460. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  36461. }
  36462. #endif
  36463. #if defined(MA_SUPPORT_NEON)
  36464. static MA_INLINE void ma_pcm_s16_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36465. {
  36466. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  36467. }
  36468. #endif
  36469. MA_API void ma_pcm_s16_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36470. {
  36471. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36472. ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode);
  36473. #else
  36474. # if defined(MA_SUPPORT_SSE2)
  36475. if (ma_has_sse2()) {
  36476. ma_pcm_s16_to_s32__sse2(dst, src, count, ditherMode);
  36477. } else
  36478. #elif defined(MA_SUPPORT_NEON)
  36479. if (ma_has_neon()) {
  36480. ma_pcm_s16_to_s32__neon(dst, src, count, ditherMode);
  36481. } else
  36482. #endif
  36483. {
  36484. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  36485. }
  36486. #endif
  36487. }
  36488. static MA_INLINE void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36489. {
  36490. float* dst_f32 = (float*)dst;
  36491. const ma_int16* src_s16 = (const ma_int16*)src;
  36492. ma_uint64 i;
  36493. for (i = 0; i < count; i += 1) {
  36494. float x = (float)src_s16[i];
  36495. #if 0
  36496. /* The accurate way. */
  36497. x = x + 32768.0f; /* -32768..32767 to 0..65535 */
  36498. x = x * 0.00003051804379339284f; /* 0..65535 to 0..2 */
  36499. x = x - 1; /* 0..2 to -1..1 */
  36500. #else
  36501. /* The fast way. */
  36502. x = x * 0.000030517578125f; /* -32768..32767 to -1..0.999969482421875 */
  36503. #endif
  36504. dst_f32[i] = x;
  36505. }
  36506. (void)ditherMode;
  36507. }
  36508. static MA_INLINE void ma_pcm_s16_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36509. {
  36510. ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
  36511. }
  36512. #if defined(MA_SUPPORT_SSE2)
  36513. static MA_INLINE void ma_pcm_s16_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36514. {
  36515. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  36516. }
  36517. #endif
  36518. #if defined(MA_SUPPORT_NEON)
  36519. static MA_INLINE void ma_pcm_s16_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36520. {
  36521. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  36522. }
  36523. #endif
  36524. MA_API void ma_pcm_s16_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36525. {
  36526. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36527. ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
  36528. #else
  36529. # if defined(MA_SUPPORT_SSE2)
  36530. if (ma_has_sse2()) {
  36531. ma_pcm_s16_to_f32__sse2(dst, src, count, ditherMode);
  36532. } else
  36533. #elif defined(MA_SUPPORT_NEON)
  36534. if (ma_has_neon()) {
  36535. ma_pcm_s16_to_f32__neon(dst, src, count, ditherMode);
  36536. } else
  36537. #endif
  36538. {
  36539. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  36540. }
  36541. #endif
  36542. }
  36543. static MA_INLINE void ma_pcm_interleave_s16__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36544. {
  36545. ma_int16* dst_s16 = (ma_int16*)dst;
  36546. const ma_int16** src_s16 = (const ma_int16**)src;
  36547. ma_uint64 iFrame;
  36548. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36549. ma_uint32 iChannel;
  36550. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36551. dst_s16[iFrame*channels + iChannel] = src_s16[iChannel][iFrame];
  36552. }
  36553. }
  36554. }
  36555. static MA_INLINE void ma_pcm_interleave_s16__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36556. {
  36557. ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
  36558. }
  36559. MA_API void ma_pcm_interleave_s16(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36560. {
  36561. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36562. ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
  36563. #else
  36564. ma_pcm_interleave_s16__optimized(dst, src, frameCount, channels);
  36565. #endif
  36566. }
  36567. static MA_INLINE void ma_pcm_deinterleave_s16__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36568. {
  36569. ma_int16** dst_s16 = (ma_int16**)dst;
  36570. const ma_int16* src_s16 = (const ma_int16*)src;
  36571. ma_uint64 iFrame;
  36572. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36573. ma_uint32 iChannel;
  36574. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36575. dst_s16[iChannel][iFrame] = src_s16[iFrame*channels + iChannel];
  36576. }
  36577. }
  36578. }
  36579. static MA_INLINE void ma_pcm_deinterleave_s16__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36580. {
  36581. ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
  36582. }
  36583. MA_API void ma_pcm_deinterleave_s16(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36584. {
  36585. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36586. ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
  36587. #else
  36588. ma_pcm_deinterleave_s16__optimized(dst, src, frameCount, channels);
  36589. #endif
  36590. }
  36591. /* s24 */
  36592. static MA_INLINE void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36593. {
  36594. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36595. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36596. if (ditherMode == ma_dither_mode_none) {
  36597. ma_uint64 i;
  36598. for (i = 0; i < count; i += 1) {
  36599. dst_u8[i] = (ma_uint8)((ma_int8)src_s24[i*3 + 2] + 128);
  36600. }
  36601. } else {
  36602. ma_uint64 i;
  36603. for (i = 0; i < count; i += 1) {
  36604. 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);
  36605. /* Dither. Don't overflow. */
  36606. ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
  36607. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36608. x = x + dither;
  36609. } else {
  36610. x = 0x7FFFFFFF;
  36611. }
  36612. x = x >> 24;
  36613. x = x + 128;
  36614. dst_u8[i] = (ma_uint8)x;
  36615. }
  36616. }
  36617. }
  36618. static MA_INLINE void ma_pcm_s24_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36619. {
  36620. ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
  36621. }
  36622. #if defined(MA_SUPPORT_SSE2)
  36623. static MA_INLINE void ma_pcm_s24_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36624. {
  36625. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  36626. }
  36627. #endif
  36628. #if defined(MA_SUPPORT_NEON)
  36629. static MA_INLINE void ma_pcm_s24_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36630. {
  36631. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  36632. }
  36633. #endif
  36634. MA_API void ma_pcm_s24_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36635. {
  36636. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36637. ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
  36638. #else
  36639. # if defined(MA_SUPPORT_SSE2)
  36640. if (ma_has_sse2()) {
  36641. ma_pcm_s24_to_u8__sse2(dst, src, count, ditherMode);
  36642. } else
  36643. #elif defined(MA_SUPPORT_NEON)
  36644. if (ma_has_neon()) {
  36645. ma_pcm_s24_to_u8__neon(dst, src, count, ditherMode);
  36646. } else
  36647. #endif
  36648. {
  36649. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  36650. }
  36651. #endif
  36652. }
  36653. static MA_INLINE void ma_pcm_s24_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36654. {
  36655. ma_int16* dst_s16 = (ma_int16*)dst;
  36656. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36657. if (ditherMode == ma_dither_mode_none) {
  36658. ma_uint64 i;
  36659. for (i = 0; i < count; i += 1) {
  36660. ma_uint16 dst_lo = ((ma_uint16)src_s24[i*3 + 1]);
  36661. ma_uint16 dst_hi = (ma_uint16)((ma_uint16)src_s24[i*3 + 2] << 8);
  36662. dst_s16[i] = (ma_int16)(dst_lo | dst_hi);
  36663. }
  36664. } else {
  36665. ma_uint64 i;
  36666. for (i = 0; i < count; i += 1) {
  36667. 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);
  36668. /* Dither. Don't overflow. */
  36669. ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF);
  36670. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36671. x = x + dither;
  36672. } else {
  36673. x = 0x7FFFFFFF;
  36674. }
  36675. x = x >> 16;
  36676. dst_s16[i] = (ma_int16)x;
  36677. }
  36678. }
  36679. }
  36680. static MA_INLINE void ma_pcm_s24_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36681. {
  36682. ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode);
  36683. }
  36684. #if defined(MA_SUPPORT_SSE2)
  36685. static MA_INLINE void ma_pcm_s24_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36686. {
  36687. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  36688. }
  36689. #endif
  36690. #if defined(MA_SUPPORT_NEON)
  36691. static MA_INLINE void ma_pcm_s24_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36692. {
  36693. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  36694. }
  36695. #endif
  36696. MA_API void ma_pcm_s24_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36697. {
  36698. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36699. ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode);
  36700. #else
  36701. # if defined(MA_SUPPORT_SSE2)
  36702. if (ma_has_sse2()) {
  36703. ma_pcm_s24_to_s16__sse2(dst, src, count, ditherMode);
  36704. } else
  36705. #elif defined(MA_SUPPORT_NEON)
  36706. if (ma_has_neon()) {
  36707. ma_pcm_s24_to_s16__neon(dst, src, count, ditherMode);
  36708. } else
  36709. #endif
  36710. {
  36711. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  36712. }
  36713. #endif
  36714. }
  36715. MA_API void ma_pcm_s24_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36716. {
  36717. (void)ditherMode;
  36718. ma_copy_memory_64(dst, src, count * 3);
  36719. }
  36720. static MA_INLINE void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36721. {
  36722. ma_int32* dst_s32 = (ma_int32*)dst;
  36723. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36724. ma_uint64 i;
  36725. for (i = 0; i < count; i += 1) {
  36726. 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);
  36727. }
  36728. (void)ditherMode;
  36729. }
  36730. static MA_INLINE void ma_pcm_s24_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36731. {
  36732. ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode);
  36733. }
  36734. #if defined(MA_SUPPORT_SSE2)
  36735. static MA_INLINE void ma_pcm_s24_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36736. {
  36737. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  36738. }
  36739. #endif
  36740. #if defined(MA_SUPPORT_NEON)
  36741. static MA_INLINE void ma_pcm_s24_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36742. {
  36743. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  36744. }
  36745. #endif
  36746. MA_API void ma_pcm_s24_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36747. {
  36748. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36749. ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode);
  36750. #else
  36751. # if defined(MA_SUPPORT_SSE2)
  36752. if (ma_has_sse2()) {
  36753. ma_pcm_s24_to_s32__sse2(dst, src, count, ditherMode);
  36754. } else
  36755. #elif defined(MA_SUPPORT_NEON)
  36756. if (ma_has_neon()) {
  36757. ma_pcm_s24_to_s32__neon(dst, src, count, ditherMode);
  36758. } else
  36759. #endif
  36760. {
  36761. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  36762. }
  36763. #endif
  36764. }
  36765. static MA_INLINE void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36766. {
  36767. float* dst_f32 = (float*)dst;
  36768. const ma_uint8* src_s24 = (const ma_uint8*)src;
  36769. ma_uint64 i;
  36770. for (i = 0; i < count; i += 1) {
  36771. 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);
  36772. #if 0
  36773. /* The accurate way. */
  36774. x = x + 8388608.0f; /* -8388608..8388607 to 0..16777215 */
  36775. x = x * 0.00000011920929665621f; /* 0..16777215 to 0..2 */
  36776. x = x - 1; /* 0..2 to -1..1 */
  36777. #else
  36778. /* The fast way. */
  36779. x = x * 0.00000011920928955078125f; /* -8388608..8388607 to -1..0.999969482421875 */
  36780. #endif
  36781. dst_f32[i] = x;
  36782. }
  36783. (void)ditherMode;
  36784. }
  36785. static MA_INLINE void ma_pcm_s24_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36786. {
  36787. ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
  36788. }
  36789. #if defined(MA_SUPPORT_SSE2)
  36790. static MA_INLINE void ma_pcm_s24_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36791. {
  36792. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  36793. }
  36794. #endif
  36795. #if defined(MA_SUPPORT_NEON)
  36796. static MA_INLINE void ma_pcm_s24_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36797. {
  36798. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  36799. }
  36800. #endif
  36801. MA_API void ma_pcm_s24_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36802. {
  36803. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36804. ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
  36805. #else
  36806. # if defined(MA_SUPPORT_SSE2)
  36807. if (ma_has_sse2()) {
  36808. ma_pcm_s24_to_f32__sse2(dst, src, count, ditherMode);
  36809. } else
  36810. #elif defined(MA_SUPPORT_NEON)
  36811. if (ma_has_neon()) {
  36812. ma_pcm_s24_to_f32__neon(dst, src, count, ditherMode);
  36813. } else
  36814. #endif
  36815. {
  36816. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  36817. }
  36818. #endif
  36819. }
  36820. static MA_INLINE void ma_pcm_interleave_s24__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36821. {
  36822. ma_uint8* dst8 = (ma_uint8*)dst;
  36823. const ma_uint8** src8 = (const ma_uint8**)src;
  36824. ma_uint64 iFrame;
  36825. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36826. ma_uint32 iChannel;
  36827. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36828. dst8[iFrame*3*channels + iChannel*3 + 0] = src8[iChannel][iFrame*3 + 0];
  36829. dst8[iFrame*3*channels + iChannel*3 + 1] = src8[iChannel][iFrame*3 + 1];
  36830. dst8[iFrame*3*channels + iChannel*3 + 2] = src8[iChannel][iFrame*3 + 2];
  36831. }
  36832. }
  36833. }
  36834. static MA_INLINE void ma_pcm_interleave_s24__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36835. {
  36836. ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
  36837. }
  36838. MA_API void ma_pcm_interleave_s24(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36839. {
  36840. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36841. ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
  36842. #else
  36843. ma_pcm_interleave_s24__optimized(dst, src, frameCount, channels);
  36844. #endif
  36845. }
  36846. static MA_INLINE void ma_pcm_deinterleave_s24__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36847. {
  36848. ma_uint8** dst8 = (ma_uint8**)dst;
  36849. const ma_uint8* src8 = (const ma_uint8*)src;
  36850. ma_uint32 iFrame;
  36851. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36852. ma_uint32 iChannel;
  36853. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36854. dst8[iChannel][iFrame*3 + 0] = src8[iFrame*3*channels + iChannel*3 + 0];
  36855. dst8[iChannel][iFrame*3 + 1] = src8[iFrame*3*channels + iChannel*3 + 1];
  36856. dst8[iChannel][iFrame*3 + 2] = src8[iFrame*3*channels + iChannel*3 + 2];
  36857. }
  36858. }
  36859. }
  36860. static MA_INLINE void ma_pcm_deinterleave_s24__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36861. {
  36862. ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
  36863. }
  36864. MA_API void ma_pcm_deinterleave_s24(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36865. {
  36866. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36867. ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
  36868. #else
  36869. ma_pcm_deinterleave_s24__optimized(dst, src, frameCount, channels);
  36870. #endif
  36871. }
  36872. /* s32 */
  36873. static MA_INLINE void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36874. {
  36875. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36876. const ma_int32* src_s32 = (const ma_int32*)src;
  36877. if (ditherMode == ma_dither_mode_none) {
  36878. ma_uint64 i;
  36879. for (i = 0; i < count; i += 1) {
  36880. ma_int32 x = src_s32[i];
  36881. x = x >> 24;
  36882. x = x + 128;
  36883. dst_u8[i] = (ma_uint8)x;
  36884. }
  36885. } else {
  36886. ma_uint64 i;
  36887. for (i = 0; i < count; i += 1) {
  36888. ma_int32 x = src_s32[i];
  36889. /* Dither. Don't overflow. */
  36890. ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
  36891. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36892. x = x + dither;
  36893. } else {
  36894. x = 0x7FFFFFFF;
  36895. }
  36896. x = x >> 24;
  36897. x = x + 128;
  36898. dst_u8[i] = (ma_uint8)x;
  36899. }
  36900. }
  36901. }
  36902. static MA_INLINE void ma_pcm_s32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36903. {
  36904. ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
  36905. }
  36906. #if defined(MA_SUPPORT_SSE2)
  36907. static MA_INLINE void ma_pcm_s32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36908. {
  36909. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  36910. }
  36911. #endif
  36912. #if defined(MA_SUPPORT_NEON)
  36913. static MA_INLINE void ma_pcm_s32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36914. {
  36915. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  36916. }
  36917. #endif
  36918. MA_API void ma_pcm_s32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36919. {
  36920. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36921. ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
  36922. #else
  36923. # if defined(MA_SUPPORT_SSE2)
  36924. if (ma_has_sse2()) {
  36925. ma_pcm_s32_to_u8__sse2(dst, src, count, ditherMode);
  36926. } else
  36927. #elif defined(MA_SUPPORT_NEON)
  36928. if (ma_has_neon()) {
  36929. ma_pcm_s32_to_u8__neon(dst, src, count, ditherMode);
  36930. } else
  36931. #endif
  36932. {
  36933. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  36934. }
  36935. #endif
  36936. }
  36937. static MA_INLINE void ma_pcm_s32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36938. {
  36939. ma_int16* dst_s16 = (ma_int16*)dst;
  36940. const ma_int32* src_s32 = (const ma_int32*)src;
  36941. if (ditherMode == ma_dither_mode_none) {
  36942. ma_uint64 i;
  36943. for (i = 0; i < count; i += 1) {
  36944. ma_int32 x = src_s32[i];
  36945. x = x >> 16;
  36946. dst_s16[i] = (ma_int16)x;
  36947. }
  36948. } else {
  36949. ma_uint64 i;
  36950. for (i = 0; i < count; i += 1) {
  36951. ma_int32 x = src_s32[i];
  36952. /* Dither. Don't overflow. */
  36953. ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF);
  36954. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  36955. x = x + dither;
  36956. } else {
  36957. x = 0x7FFFFFFF;
  36958. }
  36959. x = x >> 16;
  36960. dst_s16[i] = (ma_int16)x;
  36961. }
  36962. }
  36963. }
  36964. static MA_INLINE void ma_pcm_s32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36965. {
  36966. ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode);
  36967. }
  36968. #if defined(MA_SUPPORT_SSE2)
  36969. static MA_INLINE void ma_pcm_s32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36970. {
  36971. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  36972. }
  36973. #endif
  36974. #if defined(MA_SUPPORT_NEON)
  36975. static MA_INLINE void ma_pcm_s32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36976. {
  36977. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  36978. }
  36979. #endif
  36980. MA_API void ma_pcm_s32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36981. {
  36982. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36983. ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode);
  36984. #else
  36985. # if defined(MA_SUPPORT_SSE2)
  36986. if (ma_has_sse2()) {
  36987. ma_pcm_s32_to_s16__sse2(dst, src, count, ditherMode);
  36988. } else
  36989. #elif defined(MA_SUPPORT_NEON)
  36990. if (ma_has_neon()) {
  36991. ma_pcm_s32_to_s16__neon(dst, src, count, ditherMode);
  36992. } else
  36993. #endif
  36994. {
  36995. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  36996. }
  36997. #endif
  36998. }
  36999. static MA_INLINE void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37000. {
  37001. ma_uint8* dst_s24 = (ma_uint8*)dst;
  37002. const ma_int32* src_s32 = (const ma_int32*)src;
  37003. ma_uint64 i;
  37004. for (i = 0; i < count; i += 1) {
  37005. ma_uint32 x = (ma_uint32)src_s32[i];
  37006. dst_s24[i*3+0] = (ma_uint8)((x & 0x0000FF00) >> 8);
  37007. dst_s24[i*3+1] = (ma_uint8)((x & 0x00FF0000) >> 16);
  37008. dst_s24[i*3+2] = (ma_uint8)((x & 0xFF000000) >> 24);
  37009. }
  37010. (void)ditherMode; /* No dithering for s32 -> s24. */
  37011. }
  37012. static MA_INLINE void ma_pcm_s32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37013. {
  37014. ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode);
  37015. }
  37016. #if defined(MA_SUPPORT_SSE2)
  37017. static MA_INLINE void ma_pcm_s32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37018. {
  37019. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  37020. }
  37021. #endif
  37022. #if defined(MA_SUPPORT_NEON)
  37023. static MA_INLINE void ma_pcm_s32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37024. {
  37025. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  37026. }
  37027. #endif
  37028. MA_API void ma_pcm_s32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37029. {
  37030. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37031. ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode);
  37032. #else
  37033. # if defined(MA_SUPPORT_SSE2)
  37034. if (ma_has_sse2()) {
  37035. ma_pcm_s32_to_s24__sse2(dst, src, count, ditherMode);
  37036. } else
  37037. #elif defined(MA_SUPPORT_NEON)
  37038. if (ma_has_neon()) {
  37039. ma_pcm_s32_to_s24__neon(dst, src, count, ditherMode);
  37040. } else
  37041. #endif
  37042. {
  37043. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  37044. }
  37045. #endif
  37046. }
  37047. MA_API void ma_pcm_s32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37048. {
  37049. (void)ditherMode;
  37050. ma_copy_memory_64(dst, src, count * sizeof(ma_int32));
  37051. }
  37052. static MA_INLINE void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37053. {
  37054. float* dst_f32 = (float*)dst;
  37055. const ma_int32* src_s32 = (const ma_int32*)src;
  37056. ma_uint64 i;
  37057. for (i = 0; i < count; i += 1) {
  37058. double x = src_s32[i];
  37059. #if 0
  37060. x = x + 2147483648.0;
  37061. x = x * 0.0000000004656612873077392578125;
  37062. x = x - 1;
  37063. #else
  37064. x = x / 2147483648.0;
  37065. #endif
  37066. dst_f32[i] = (float)x;
  37067. }
  37068. (void)ditherMode; /* No dithering for s32 -> f32. */
  37069. }
  37070. static MA_INLINE void ma_pcm_s32_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37071. {
  37072. ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
  37073. }
  37074. #if defined(MA_SUPPORT_SSE2)
  37075. static MA_INLINE void ma_pcm_s32_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37076. {
  37077. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  37078. }
  37079. #endif
  37080. #if defined(MA_SUPPORT_NEON)
  37081. static MA_INLINE void ma_pcm_s32_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37082. {
  37083. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  37084. }
  37085. #endif
  37086. MA_API void ma_pcm_s32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37087. {
  37088. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37089. ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
  37090. #else
  37091. # if defined(MA_SUPPORT_SSE2)
  37092. if (ma_has_sse2()) {
  37093. ma_pcm_s32_to_f32__sse2(dst, src, count, ditherMode);
  37094. } else
  37095. #elif defined(MA_SUPPORT_NEON)
  37096. if (ma_has_neon()) {
  37097. ma_pcm_s32_to_f32__neon(dst, src, count, ditherMode);
  37098. } else
  37099. #endif
  37100. {
  37101. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  37102. }
  37103. #endif
  37104. }
  37105. static MA_INLINE void ma_pcm_interleave_s32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37106. {
  37107. ma_int32* dst_s32 = (ma_int32*)dst;
  37108. const ma_int32** src_s32 = (const ma_int32**)src;
  37109. ma_uint64 iFrame;
  37110. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37111. ma_uint32 iChannel;
  37112. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37113. dst_s32[iFrame*channels + iChannel] = src_s32[iChannel][iFrame];
  37114. }
  37115. }
  37116. }
  37117. static MA_INLINE void ma_pcm_interleave_s32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37118. {
  37119. ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
  37120. }
  37121. MA_API void ma_pcm_interleave_s32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37122. {
  37123. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37124. ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
  37125. #else
  37126. ma_pcm_interleave_s32__optimized(dst, src, frameCount, channels);
  37127. #endif
  37128. }
  37129. static MA_INLINE void ma_pcm_deinterleave_s32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37130. {
  37131. ma_int32** dst_s32 = (ma_int32**)dst;
  37132. const ma_int32* src_s32 = (const ma_int32*)src;
  37133. ma_uint64 iFrame;
  37134. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37135. ma_uint32 iChannel;
  37136. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37137. dst_s32[iChannel][iFrame] = src_s32[iFrame*channels + iChannel];
  37138. }
  37139. }
  37140. }
  37141. static MA_INLINE void ma_pcm_deinterleave_s32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37142. {
  37143. ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
  37144. }
  37145. MA_API void ma_pcm_deinterleave_s32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37146. {
  37147. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37148. ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
  37149. #else
  37150. ma_pcm_deinterleave_s32__optimized(dst, src, frameCount, channels);
  37151. #endif
  37152. }
  37153. /* f32 */
  37154. static MA_INLINE void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37155. {
  37156. ma_uint64 i;
  37157. ma_uint8* dst_u8 = (ma_uint8*)dst;
  37158. const float* src_f32 = (const float*)src;
  37159. float ditherMin = 0;
  37160. float ditherMax = 0;
  37161. if (ditherMode != ma_dither_mode_none) {
  37162. ditherMin = 1.0f / -128;
  37163. ditherMax = 1.0f / 127;
  37164. }
  37165. for (i = 0; i < count; i += 1) {
  37166. float x = src_f32[i];
  37167. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37168. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37169. x = x + 1; /* -1..1 to 0..2 */
  37170. x = x * 127.5f; /* 0..2 to 0..255 */
  37171. dst_u8[i] = (ma_uint8)x;
  37172. }
  37173. }
  37174. static MA_INLINE void ma_pcm_f32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37175. {
  37176. ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
  37177. }
  37178. #if defined(MA_SUPPORT_SSE2)
  37179. static MA_INLINE void ma_pcm_f32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37180. {
  37181. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  37182. }
  37183. #endif
  37184. #if defined(MA_SUPPORT_NEON)
  37185. static MA_INLINE void ma_pcm_f32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37186. {
  37187. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  37188. }
  37189. #endif
  37190. MA_API void ma_pcm_f32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37191. {
  37192. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37193. ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
  37194. #else
  37195. # if defined(MA_SUPPORT_SSE2)
  37196. if (ma_has_sse2()) {
  37197. ma_pcm_f32_to_u8__sse2(dst, src, count, ditherMode);
  37198. } else
  37199. #elif defined(MA_SUPPORT_NEON)
  37200. if (ma_has_neon()) {
  37201. ma_pcm_f32_to_u8__neon(dst, src, count, ditherMode);
  37202. } else
  37203. #endif
  37204. {
  37205. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  37206. }
  37207. #endif
  37208. }
  37209. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37210. static MA_INLINE void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37211. {
  37212. ma_uint64 i;
  37213. ma_int16* dst_s16 = (ma_int16*)dst;
  37214. const float* src_f32 = (const float*)src;
  37215. float ditherMin = 0;
  37216. float ditherMax = 0;
  37217. if (ditherMode != ma_dither_mode_none) {
  37218. ditherMin = 1.0f / -32768;
  37219. ditherMax = 1.0f / 32767;
  37220. }
  37221. for (i = 0; i < count; i += 1) {
  37222. float x = src_f32[i];
  37223. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37224. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37225. #if 0
  37226. /* The accurate way. */
  37227. x = x + 1; /* -1..1 to 0..2 */
  37228. x = x * 32767.5f; /* 0..2 to 0..65535 */
  37229. x = x - 32768.0f; /* 0...65535 to -32768..32767 */
  37230. #else
  37231. /* The fast way. */
  37232. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37233. #endif
  37234. dst_s16[i] = (ma_int16)x;
  37235. }
  37236. }
  37237. #else
  37238. static MA_INLINE void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37239. {
  37240. ma_uint64 i;
  37241. ma_uint64 i4;
  37242. ma_uint64 count4;
  37243. ma_int16* dst_s16 = (ma_int16*)dst;
  37244. const float* src_f32 = (const float*)src;
  37245. float ditherMin = 0;
  37246. float ditherMax = 0;
  37247. if (ditherMode != ma_dither_mode_none) {
  37248. ditherMin = 1.0f / -32768;
  37249. ditherMax = 1.0f / 32767;
  37250. }
  37251. /* Unrolled. */
  37252. i = 0;
  37253. count4 = count >> 2;
  37254. for (i4 = 0; i4 < count4; i4 += 1) {
  37255. float d0 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37256. float d1 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37257. float d2 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37258. float d3 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37259. float x0 = src_f32[i+0];
  37260. float x1 = src_f32[i+1];
  37261. float x2 = src_f32[i+2];
  37262. float x3 = src_f32[i+3];
  37263. x0 = x0 + d0;
  37264. x1 = x1 + d1;
  37265. x2 = x2 + d2;
  37266. x3 = x3 + d3;
  37267. x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
  37268. x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
  37269. x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
  37270. x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
  37271. x0 = x0 * 32767.0f;
  37272. x1 = x1 * 32767.0f;
  37273. x2 = x2 * 32767.0f;
  37274. x3 = x3 * 32767.0f;
  37275. dst_s16[i+0] = (ma_int16)x0;
  37276. dst_s16[i+1] = (ma_int16)x1;
  37277. dst_s16[i+2] = (ma_int16)x2;
  37278. dst_s16[i+3] = (ma_int16)x3;
  37279. i += 4;
  37280. }
  37281. /* Leftover. */
  37282. for (; i < count; i += 1) {
  37283. float x = src_f32[i];
  37284. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37285. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37286. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37287. dst_s16[i] = (ma_int16)x;
  37288. }
  37289. }
  37290. #if defined(MA_SUPPORT_SSE2)
  37291. static MA_INLINE void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37292. {
  37293. ma_uint64 i;
  37294. ma_uint64 i8;
  37295. ma_uint64 count8;
  37296. ma_int16* dst_s16;
  37297. const float* src_f32;
  37298. float ditherMin;
  37299. float ditherMax;
  37300. /* Both the input and output buffers need to be aligned to 16 bytes. */
  37301. if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) {
  37302. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37303. return;
  37304. }
  37305. dst_s16 = (ma_int16*)dst;
  37306. src_f32 = (const float*)src;
  37307. ditherMin = 0;
  37308. ditherMax = 0;
  37309. if (ditherMode != ma_dither_mode_none) {
  37310. ditherMin = 1.0f / -32768;
  37311. ditherMax = 1.0f / 32767;
  37312. }
  37313. i = 0;
  37314. /* SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */
  37315. count8 = count >> 3;
  37316. for (i8 = 0; i8 < count8; i8 += 1) {
  37317. __m128 d0;
  37318. __m128 d1;
  37319. __m128 x0;
  37320. __m128 x1;
  37321. if (ditherMode == ma_dither_mode_none) {
  37322. d0 = _mm_set1_ps(0);
  37323. d1 = _mm_set1_ps(0);
  37324. } else if (ditherMode == ma_dither_mode_rectangle) {
  37325. d0 = _mm_set_ps(
  37326. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37327. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37328. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37329. ma_dither_f32_rectangle(ditherMin, ditherMax)
  37330. );
  37331. d1 = _mm_set_ps(
  37332. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37333. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37334. ma_dither_f32_rectangle(ditherMin, ditherMax),
  37335. ma_dither_f32_rectangle(ditherMin, ditherMax)
  37336. );
  37337. } else {
  37338. d0 = _mm_set_ps(
  37339. ma_dither_f32_triangle(ditherMin, ditherMax),
  37340. ma_dither_f32_triangle(ditherMin, ditherMax),
  37341. ma_dither_f32_triangle(ditherMin, ditherMax),
  37342. ma_dither_f32_triangle(ditherMin, ditherMax)
  37343. );
  37344. d1 = _mm_set_ps(
  37345. ma_dither_f32_triangle(ditherMin, ditherMax),
  37346. ma_dither_f32_triangle(ditherMin, ditherMax),
  37347. ma_dither_f32_triangle(ditherMin, ditherMax),
  37348. ma_dither_f32_triangle(ditherMin, ditherMax)
  37349. );
  37350. }
  37351. x0 = *((__m128*)(src_f32 + i) + 0);
  37352. x1 = *((__m128*)(src_f32 + i) + 1);
  37353. x0 = _mm_add_ps(x0, d0);
  37354. x1 = _mm_add_ps(x1, d1);
  37355. x0 = _mm_mul_ps(x0, _mm_set1_ps(32767.0f));
  37356. x1 = _mm_mul_ps(x1, _mm_set1_ps(32767.0f));
  37357. _mm_stream_si128(((__m128i*)(dst_s16 + i)), _mm_packs_epi32(_mm_cvttps_epi32(x0), _mm_cvttps_epi32(x1)));
  37358. i += 8;
  37359. }
  37360. /* Leftover. */
  37361. for (; i < count; i += 1) {
  37362. float x = src_f32[i];
  37363. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37364. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37365. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37366. dst_s16[i] = (ma_int16)x;
  37367. }
  37368. }
  37369. #endif /* SSE2 */
  37370. #if defined(MA_SUPPORT_NEON)
  37371. static MA_INLINE void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37372. {
  37373. ma_uint64 i;
  37374. ma_uint64 i8;
  37375. ma_uint64 count8;
  37376. ma_int16* dst_s16;
  37377. const float* src_f32;
  37378. float ditherMin;
  37379. float ditherMax;
  37380. if (!ma_has_neon()) {
  37381. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37382. return;
  37383. }
  37384. /* Both the input and output buffers need to be aligned to 16 bytes. */
  37385. if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) {
  37386. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37387. return;
  37388. }
  37389. dst_s16 = (ma_int16*)dst;
  37390. src_f32 = (const float*)src;
  37391. ditherMin = 0;
  37392. ditherMax = 0;
  37393. if (ditherMode != ma_dither_mode_none) {
  37394. ditherMin = 1.0f / -32768;
  37395. ditherMax = 1.0f / 32767;
  37396. }
  37397. i = 0;
  37398. /* NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */
  37399. count8 = count >> 3;
  37400. for (i8 = 0; i8 < count8; i8 += 1) {
  37401. float32x4_t d0;
  37402. float32x4_t d1;
  37403. float32x4_t x0;
  37404. float32x4_t x1;
  37405. int32x4_t i0;
  37406. int32x4_t i1;
  37407. if (ditherMode == ma_dither_mode_none) {
  37408. d0 = vmovq_n_f32(0);
  37409. d1 = vmovq_n_f32(0);
  37410. } else if (ditherMode == ma_dither_mode_rectangle) {
  37411. float d0v[4];
  37412. float d1v[4];
  37413. d0v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37414. d0v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37415. d0v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37416. d0v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37417. d0 = vld1q_f32(d0v);
  37418. d1v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37419. d1v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37420. d1v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37421. d1v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  37422. d1 = vld1q_f32(d1v);
  37423. } else {
  37424. float d0v[4];
  37425. float d1v[4];
  37426. d0v[0] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37427. d0v[1] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37428. d0v[2] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37429. d0v[3] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37430. d0 = vld1q_f32(d0v);
  37431. d1v[0] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37432. d1v[1] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37433. d1v[2] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37434. d1v[3] = ma_dither_f32_triangle(ditherMin, ditherMax);
  37435. d1 = vld1q_f32(d1v);
  37436. }
  37437. x0 = *((float32x4_t*)(src_f32 + i) + 0);
  37438. x1 = *((float32x4_t*)(src_f32 + i) + 1);
  37439. x0 = vaddq_f32(x0, d0);
  37440. x1 = vaddq_f32(x1, d1);
  37441. x0 = vmulq_n_f32(x0, 32767.0f);
  37442. x1 = vmulq_n_f32(x1, 32767.0f);
  37443. i0 = vcvtq_s32_f32(x0);
  37444. i1 = vcvtq_s32_f32(x1);
  37445. *((int16x8_t*)(dst_s16 + i)) = vcombine_s16(vqmovn_s32(i0), vqmovn_s32(i1));
  37446. i += 8;
  37447. }
  37448. /* Leftover. */
  37449. for (; i < count; i += 1) {
  37450. float x = src_f32[i];
  37451. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  37452. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37453. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  37454. dst_s16[i] = (ma_int16)x;
  37455. }
  37456. }
  37457. #endif /* Neon */
  37458. #endif /* MA_USE_REFERENCE_CONVERSION_APIS */
  37459. MA_API void ma_pcm_f32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37460. {
  37461. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37462. ma_pcm_f32_to_s16__reference(dst, src, count, ditherMode);
  37463. #else
  37464. # if defined(MA_SUPPORT_SSE2)
  37465. if (ma_has_sse2()) {
  37466. ma_pcm_f32_to_s16__sse2(dst, src, count, ditherMode);
  37467. } else
  37468. #elif defined(MA_SUPPORT_NEON)
  37469. if (ma_has_neon()) {
  37470. ma_pcm_f32_to_s16__neon(dst, src, count, ditherMode);
  37471. } else
  37472. #endif
  37473. {
  37474. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  37475. }
  37476. #endif
  37477. }
  37478. static MA_INLINE void ma_pcm_f32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37479. {
  37480. ma_uint8* dst_s24 = (ma_uint8*)dst;
  37481. const float* src_f32 = (const float*)src;
  37482. ma_uint64 i;
  37483. for (i = 0; i < count; i += 1) {
  37484. ma_int32 r;
  37485. float x = src_f32[i];
  37486. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37487. #if 0
  37488. /* The accurate way. */
  37489. x = x + 1; /* -1..1 to 0..2 */
  37490. x = x * 8388607.5f; /* 0..2 to 0..16777215 */
  37491. x = x - 8388608.0f; /* 0..16777215 to -8388608..8388607 */
  37492. #else
  37493. /* The fast way. */
  37494. x = x * 8388607.0f; /* -1..1 to -8388607..8388607 */
  37495. #endif
  37496. r = (ma_int32)x;
  37497. dst_s24[(i*3)+0] = (ma_uint8)((r & 0x0000FF) >> 0);
  37498. dst_s24[(i*3)+1] = (ma_uint8)((r & 0x00FF00) >> 8);
  37499. dst_s24[(i*3)+2] = (ma_uint8)((r & 0xFF0000) >> 16);
  37500. }
  37501. (void)ditherMode; /* No dithering for f32 -> s24. */
  37502. }
  37503. static MA_INLINE void ma_pcm_f32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37504. {
  37505. ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode);
  37506. }
  37507. #if defined(MA_SUPPORT_SSE2)
  37508. static MA_INLINE void ma_pcm_f32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37509. {
  37510. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  37511. }
  37512. #endif
  37513. #if defined(MA_SUPPORT_NEON)
  37514. static MA_INLINE void ma_pcm_f32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37515. {
  37516. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  37517. }
  37518. #endif
  37519. MA_API void ma_pcm_f32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37520. {
  37521. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37522. ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode);
  37523. #else
  37524. # if defined(MA_SUPPORT_SSE2)
  37525. if (ma_has_sse2()) {
  37526. ma_pcm_f32_to_s24__sse2(dst, src, count, ditherMode);
  37527. } else
  37528. #elif defined(MA_SUPPORT_NEON)
  37529. if (ma_has_neon()) {
  37530. ma_pcm_f32_to_s24__neon(dst, src, count, ditherMode);
  37531. } else
  37532. #endif
  37533. {
  37534. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  37535. }
  37536. #endif
  37537. }
  37538. static MA_INLINE void ma_pcm_f32_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37539. {
  37540. ma_int32* dst_s32 = (ma_int32*)dst;
  37541. const float* src_f32 = (const float*)src;
  37542. ma_uint32 i;
  37543. for (i = 0; i < count; i += 1) {
  37544. double x = src_f32[i];
  37545. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  37546. #if 0
  37547. /* The accurate way. */
  37548. x = x + 1; /* -1..1 to 0..2 */
  37549. x = x * 2147483647.5; /* 0..2 to 0..4294967295 */
  37550. x = x - 2147483648.0; /* 0...4294967295 to -2147483648..2147483647 */
  37551. #else
  37552. /* The fast way. */
  37553. x = x * 2147483647.0; /* -1..1 to -2147483647..2147483647 */
  37554. #endif
  37555. dst_s32[i] = (ma_int32)x;
  37556. }
  37557. (void)ditherMode; /* No dithering for f32 -> s32. */
  37558. }
  37559. static MA_INLINE void ma_pcm_f32_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37560. {
  37561. ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
  37562. }
  37563. #if defined(MA_SUPPORT_SSE2)
  37564. static MA_INLINE void ma_pcm_f32_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37565. {
  37566. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  37567. }
  37568. #endif
  37569. #if defined(MA_SUPPORT_NEON)
  37570. static MA_INLINE void ma_pcm_f32_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37571. {
  37572. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  37573. }
  37574. #endif
  37575. MA_API void ma_pcm_f32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37576. {
  37577. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37578. ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
  37579. #else
  37580. # if defined(MA_SUPPORT_SSE2)
  37581. if (ma_has_sse2()) {
  37582. ma_pcm_f32_to_s32__sse2(dst, src, count, ditherMode);
  37583. } else
  37584. #elif defined(MA_SUPPORT_NEON)
  37585. if (ma_has_neon()) {
  37586. ma_pcm_f32_to_s32__neon(dst, src, count, ditherMode);
  37587. } else
  37588. #endif
  37589. {
  37590. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  37591. }
  37592. #endif
  37593. }
  37594. MA_API void ma_pcm_f32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  37595. {
  37596. (void)ditherMode;
  37597. ma_copy_memory_64(dst, src, count * sizeof(float));
  37598. }
  37599. static void ma_pcm_interleave_f32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37600. {
  37601. float* dst_f32 = (float*)dst;
  37602. const float** src_f32 = (const float**)src;
  37603. ma_uint64 iFrame;
  37604. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37605. ma_uint32 iChannel;
  37606. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37607. dst_f32[iFrame*channels + iChannel] = src_f32[iChannel][iFrame];
  37608. }
  37609. }
  37610. }
  37611. static void ma_pcm_interleave_f32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37612. {
  37613. ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
  37614. }
  37615. MA_API void ma_pcm_interleave_f32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  37616. {
  37617. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37618. ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
  37619. #else
  37620. ma_pcm_interleave_f32__optimized(dst, src, frameCount, channels);
  37621. #endif
  37622. }
  37623. static void ma_pcm_deinterleave_f32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37624. {
  37625. float** dst_f32 = (float**)dst;
  37626. const float* src_f32 = (const float*)src;
  37627. ma_uint64 iFrame;
  37628. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37629. ma_uint32 iChannel;
  37630. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  37631. dst_f32[iChannel][iFrame] = src_f32[iFrame*channels + iChannel];
  37632. }
  37633. }
  37634. }
  37635. static void ma_pcm_deinterleave_f32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37636. {
  37637. ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
  37638. }
  37639. MA_API void ma_pcm_deinterleave_f32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  37640. {
  37641. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  37642. ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
  37643. #else
  37644. ma_pcm_deinterleave_f32__optimized(dst, src, frameCount, channels);
  37645. #endif
  37646. }
  37647. MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode)
  37648. {
  37649. if (formatOut == formatIn) {
  37650. ma_copy_memory_64(pOut, pIn, sampleCount * ma_get_bytes_per_sample(formatOut));
  37651. return;
  37652. }
  37653. switch (formatIn)
  37654. {
  37655. case ma_format_u8:
  37656. {
  37657. switch (formatOut)
  37658. {
  37659. case ma_format_s16: ma_pcm_u8_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37660. case ma_format_s24: ma_pcm_u8_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37661. case ma_format_s32: ma_pcm_u8_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37662. case ma_format_f32: ma_pcm_u8_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37663. default: break;
  37664. }
  37665. } break;
  37666. case ma_format_s16:
  37667. {
  37668. switch (formatOut)
  37669. {
  37670. case ma_format_u8: ma_pcm_s16_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37671. case ma_format_s24: ma_pcm_s16_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37672. case ma_format_s32: ma_pcm_s16_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37673. case ma_format_f32: ma_pcm_s16_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37674. default: break;
  37675. }
  37676. } break;
  37677. case ma_format_s24:
  37678. {
  37679. switch (formatOut)
  37680. {
  37681. case ma_format_u8: ma_pcm_s24_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37682. case ma_format_s16: ma_pcm_s24_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37683. case ma_format_s32: ma_pcm_s24_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37684. case ma_format_f32: ma_pcm_s24_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37685. default: break;
  37686. }
  37687. } break;
  37688. case ma_format_s32:
  37689. {
  37690. switch (formatOut)
  37691. {
  37692. case ma_format_u8: ma_pcm_s32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37693. case ma_format_s16: ma_pcm_s32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37694. case ma_format_s24: ma_pcm_s32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37695. case ma_format_f32: ma_pcm_s32_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  37696. default: break;
  37697. }
  37698. } break;
  37699. case ma_format_f32:
  37700. {
  37701. switch (formatOut)
  37702. {
  37703. case ma_format_u8: ma_pcm_f32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  37704. case ma_format_s16: ma_pcm_f32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  37705. case ma_format_s24: ma_pcm_f32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  37706. case ma_format_s32: ma_pcm_f32_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  37707. default: break;
  37708. }
  37709. } break;
  37710. default: break;
  37711. }
  37712. }
  37713. 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)
  37714. {
  37715. ma_pcm_convert(pOut, formatOut, pIn, formatIn, frameCount * channels, ditherMode);
  37716. }
  37717. MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames)
  37718. {
  37719. if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) {
  37720. return; /* Invalid args. */
  37721. }
  37722. /* For efficiency we do this per format. */
  37723. switch (format) {
  37724. case ma_format_s16:
  37725. {
  37726. const ma_int16* pSrcS16 = (const ma_int16*)pInterleavedPCMFrames;
  37727. ma_uint64 iPCMFrame;
  37728. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37729. ma_uint32 iChannel;
  37730. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37731. ma_int16* pDstS16 = (ma_int16*)ppDeinterleavedPCMFrames[iChannel];
  37732. pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel];
  37733. }
  37734. }
  37735. } break;
  37736. case ma_format_f32:
  37737. {
  37738. const float* pSrcF32 = (const float*)pInterleavedPCMFrames;
  37739. ma_uint64 iPCMFrame;
  37740. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37741. ma_uint32 iChannel;
  37742. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37743. float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel];
  37744. pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel];
  37745. }
  37746. }
  37747. } break;
  37748. default:
  37749. {
  37750. ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
  37751. ma_uint64 iPCMFrame;
  37752. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37753. ma_uint32 iChannel;
  37754. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37755. void* pDst = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
  37756. const void* pSrc = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
  37757. memcpy(pDst, pSrc, sampleSizeInBytes);
  37758. }
  37759. }
  37760. } break;
  37761. }
  37762. }
  37763. MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames)
  37764. {
  37765. switch (format)
  37766. {
  37767. case ma_format_s16:
  37768. {
  37769. ma_int16* pDstS16 = (ma_int16*)pInterleavedPCMFrames;
  37770. ma_uint64 iPCMFrame;
  37771. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37772. ma_uint32 iChannel;
  37773. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37774. const ma_int16* pSrcS16 = (const ma_int16*)ppDeinterleavedPCMFrames[iChannel];
  37775. pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame];
  37776. }
  37777. }
  37778. } break;
  37779. case ma_format_f32:
  37780. {
  37781. float* pDstF32 = (float*)pInterleavedPCMFrames;
  37782. ma_uint64 iPCMFrame;
  37783. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37784. ma_uint32 iChannel;
  37785. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37786. const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel];
  37787. pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame];
  37788. }
  37789. }
  37790. } break;
  37791. default:
  37792. {
  37793. ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
  37794. ma_uint64 iPCMFrame;
  37795. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  37796. ma_uint32 iChannel;
  37797. for (iChannel = 0; iChannel < channels; ++iChannel) {
  37798. void* pDst = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
  37799. const void* pSrc = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
  37800. memcpy(pDst, pSrc, sampleSizeInBytes);
  37801. }
  37802. }
  37803. } break;
  37804. }
  37805. }
  37806. /**************************************************************************************************************************************************************
  37807. Biquad Filter
  37808. **************************************************************************************************************************************************************/
  37809. #ifndef MA_BIQUAD_FIXED_POINT_SHIFT
  37810. #define MA_BIQUAD_FIXED_POINT_SHIFT 14
  37811. #endif
  37812. static ma_int32 ma_biquad_float_to_fp(double x)
  37813. {
  37814. return (ma_int32)(x * (1 << MA_BIQUAD_FIXED_POINT_SHIFT));
  37815. }
  37816. 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)
  37817. {
  37818. ma_biquad_config config;
  37819. MA_ZERO_OBJECT(&config);
  37820. config.format = format;
  37821. config.channels = channels;
  37822. config.b0 = b0;
  37823. config.b1 = b1;
  37824. config.b2 = b2;
  37825. config.a0 = a0;
  37826. config.a1 = a1;
  37827. config.a2 = a2;
  37828. return config;
  37829. }
  37830. typedef struct
  37831. {
  37832. size_t sizeInBytes;
  37833. size_t r1Offset;
  37834. size_t r2Offset;
  37835. } ma_biquad_heap_layout;
  37836. static ma_result ma_biquad_get_heap_layout(const ma_biquad_config* pConfig, ma_biquad_heap_layout* pHeapLayout)
  37837. {
  37838. MA_ASSERT(pHeapLayout != NULL);
  37839. MA_ZERO_OBJECT(pHeapLayout);
  37840. if (pConfig == NULL) {
  37841. return MA_INVALID_ARGS;
  37842. }
  37843. if (pConfig->channels == 0) {
  37844. return MA_INVALID_ARGS;
  37845. }
  37846. pHeapLayout->sizeInBytes = 0;
  37847. /* R0 */
  37848. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  37849. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  37850. /* R1 */
  37851. pHeapLayout->r2Offset = pHeapLayout->sizeInBytes;
  37852. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  37853. /* Make sure allocation size is aligned. */
  37854. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  37855. return MA_SUCCESS;
  37856. }
  37857. MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes)
  37858. {
  37859. ma_result result;
  37860. ma_biquad_heap_layout heapLayout;
  37861. if (pHeapSizeInBytes == NULL) {
  37862. return MA_INVALID_ARGS;
  37863. }
  37864. *pHeapSizeInBytes = 0;
  37865. result = ma_biquad_get_heap_layout(pConfig, &heapLayout);
  37866. if (result != MA_SUCCESS) {
  37867. return result;
  37868. }
  37869. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  37870. return MA_SUCCESS;
  37871. }
  37872. MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ)
  37873. {
  37874. ma_result result;
  37875. ma_biquad_heap_layout heapLayout;
  37876. if (pBQ == NULL) {
  37877. return MA_INVALID_ARGS;
  37878. }
  37879. MA_ZERO_OBJECT(pBQ);
  37880. result = ma_biquad_get_heap_layout(pConfig, &heapLayout);
  37881. if (result != MA_SUCCESS) {
  37882. return result;
  37883. }
  37884. pBQ->_pHeap = pHeap;
  37885. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  37886. pBQ->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  37887. pBQ->pR2 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r2Offset);
  37888. return ma_biquad_reinit(pConfig, pBQ);
  37889. }
  37890. MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ)
  37891. {
  37892. ma_result result;
  37893. size_t heapSizeInBytes;
  37894. void* pHeap;
  37895. result = ma_biquad_get_heap_size(pConfig, &heapSizeInBytes);
  37896. if (result != MA_SUCCESS) {
  37897. return result;
  37898. }
  37899. if (heapSizeInBytes > 0) {
  37900. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  37901. if (pHeap == NULL) {
  37902. return MA_OUT_OF_MEMORY;
  37903. }
  37904. } else {
  37905. pHeap = NULL;
  37906. }
  37907. result = ma_biquad_init_preallocated(pConfig, pHeap, pBQ);
  37908. if (result != MA_SUCCESS) {
  37909. ma_free(pHeap, pAllocationCallbacks);
  37910. return result;
  37911. }
  37912. pBQ->_ownsHeap = MA_TRUE;
  37913. return MA_SUCCESS;
  37914. }
  37915. MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks)
  37916. {
  37917. if (pBQ == NULL) {
  37918. return;
  37919. }
  37920. if (pBQ->_ownsHeap) {
  37921. ma_free(pBQ->_pHeap, pAllocationCallbacks);
  37922. }
  37923. }
  37924. MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ)
  37925. {
  37926. if (pBQ == NULL || pConfig == NULL) {
  37927. return MA_INVALID_ARGS;
  37928. }
  37929. if (pConfig->a0 == 0) {
  37930. return MA_INVALID_ARGS; /* Division by zero. */
  37931. }
  37932. /* Only supporting f32 and s16. */
  37933. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  37934. return MA_INVALID_ARGS;
  37935. }
  37936. /* The format cannot be changed after initialization. */
  37937. if (pBQ->format != ma_format_unknown && pBQ->format != pConfig->format) {
  37938. return MA_INVALID_OPERATION;
  37939. }
  37940. /* The channel count cannot be changed after initialization. */
  37941. if (pBQ->channels != 0 && pBQ->channels != pConfig->channels) {
  37942. return MA_INVALID_OPERATION;
  37943. }
  37944. pBQ->format = pConfig->format;
  37945. pBQ->channels = pConfig->channels;
  37946. /* Normalize. */
  37947. if (pConfig->format == ma_format_f32) {
  37948. pBQ->b0.f32 = (float)(pConfig->b0 / pConfig->a0);
  37949. pBQ->b1.f32 = (float)(pConfig->b1 / pConfig->a0);
  37950. pBQ->b2.f32 = (float)(pConfig->b2 / pConfig->a0);
  37951. pBQ->a1.f32 = (float)(pConfig->a1 / pConfig->a0);
  37952. pBQ->a2.f32 = (float)(pConfig->a2 / pConfig->a0);
  37953. } else {
  37954. pBQ->b0.s32 = ma_biquad_float_to_fp(pConfig->b0 / pConfig->a0);
  37955. pBQ->b1.s32 = ma_biquad_float_to_fp(pConfig->b1 / pConfig->a0);
  37956. pBQ->b2.s32 = ma_biquad_float_to_fp(pConfig->b2 / pConfig->a0);
  37957. pBQ->a1.s32 = ma_biquad_float_to_fp(pConfig->a1 / pConfig->a0);
  37958. pBQ->a2.s32 = ma_biquad_float_to_fp(pConfig->a2 / pConfig->a0);
  37959. }
  37960. return MA_SUCCESS;
  37961. }
  37962. MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ)
  37963. {
  37964. if (pBQ == NULL) {
  37965. return MA_INVALID_ARGS;
  37966. }
  37967. if (pBQ->format == ma_format_f32) {
  37968. pBQ->pR1->f32 = 0;
  37969. pBQ->pR2->f32 = 0;
  37970. } else {
  37971. pBQ->pR1->s32 = 0;
  37972. pBQ->pR2->s32 = 0;
  37973. }
  37974. return MA_SUCCESS;
  37975. }
  37976. static MA_INLINE void ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(ma_biquad* pBQ, float* pY, const float* pX)
  37977. {
  37978. ma_uint32 c;
  37979. const ma_uint32 channels = pBQ->channels;
  37980. const float b0 = pBQ->b0.f32;
  37981. const float b1 = pBQ->b1.f32;
  37982. const float b2 = pBQ->b2.f32;
  37983. const float a1 = pBQ->a1.f32;
  37984. const float a2 = pBQ->a2.f32;
  37985. MA_ASSUME(channels > 0);
  37986. for (c = 0; c < channels; c += 1) {
  37987. float r1 = pBQ->pR1[c].f32;
  37988. float r2 = pBQ->pR2[c].f32;
  37989. float x = pX[c];
  37990. float y;
  37991. y = b0*x + r1;
  37992. r1 = b1*x - a1*y + r2;
  37993. r2 = b2*x - a2*y;
  37994. pY[c] = y;
  37995. pBQ->pR1[c].f32 = r1;
  37996. pBQ->pR2[c].f32 = r2;
  37997. }
  37998. }
  37999. static MA_INLINE void ma_biquad_process_pcm_frame_f32(ma_biquad* pBQ, float* pY, const float* pX)
  38000. {
  38001. ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
  38002. }
  38003. static MA_INLINE void ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
  38004. {
  38005. ma_uint32 c;
  38006. const ma_uint32 channels = pBQ->channels;
  38007. const ma_int32 b0 = pBQ->b0.s32;
  38008. const ma_int32 b1 = pBQ->b1.s32;
  38009. const ma_int32 b2 = pBQ->b2.s32;
  38010. const ma_int32 a1 = pBQ->a1.s32;
  38011. const ma_int32 a2 = pBQ->a2.s32;
  38012. MA_ASSUME(channels > 0);
  38013. for (c = 0; c < channels; c += 1) {
  38014. ma_int32 r1 = pBQ->pR1[c].s32;
  38015. ma_int32 r2 = pBQ->pR2[c].s32;
  38016. ma_int32 x = pX[c];
  38017. ma_int32 y;
  38018. y = (b0*x + r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  38019. r1 = (b1*x - a1*y + r2);
  38020. r2 = (b2*x - a2*y);
  38021. pY[c] = (ma_int16)ma_clamp(y, -32768, 32767);
  38022. pBQ->pR1[c].s32 = r1;
  38023. pBQ->pR2[c].s32 = r2;
  38024. }
  38025. }
  38026. static MA_INLINE void ma_biquad_process_pcm_frame_s16(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
  38027. {
  38028. ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
  38029. }
  38030. MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38031. {
  38032. ma_uint32 n;
  38033. if (pBQ == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38034. return MA_INVALID_ARGS;
  38035. }
  38036. /* 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. */
  38037. if (pBQ->format == ma_format_f32) {
  38038. /* */ float* pY = ( float*)pFramesOut;
  38039. const float* pX = (const float*)pFramesIn;
  38040. for (n = 0; n < frameCount; n += 1) {
  38041. ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
  38042. pY += pBQ->channels;
  38043. pX += pBQ->channels;
  38044. }
  38045. } else if (pBQ->format == ma_format_s16) {
  38046. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38047. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38048. for (n = 0; n < frameCount; n += 1) {
  38049. ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
  38050. pY += pBQ->channels;
  38051. pX += pBQ->channels;
  38052. }
  38053. } else {
  38054. MA_ASSERT(MA_FALSE);
  38055. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38056. }
  38057. return MA_SUCCESS;
  38058. }
  38059. MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ)
  38060. {
  38061. if (pBQ == NULL) {
  38062. return 0;
  38063. }
  38064. return 2;
  38065. }
  38066. /**************************************************************************************************************************************************************
  38067. Low-Pass Filter
  38068. **************************************************************************************************************************************************************/
  38069. MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
  38070. {
  38071. ma_lpf1_config config;
  38072. MA_ZERO_OBJECT(&config);
  38073. config.format = format;
  38074. config.channels = channels;
  38075. config.sampleRate = sampleRate;
  38076. config.cutoffFrequency = cutoffFrequency;
  38077. config.q = 0.5;
  38078. return config;
  38079. }
  38080. MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  38081. {
  38082. ma_lpf2_config config;
  38083. MA_ZERO_OBJECT(&config);
  38084. config.format = format;
  38085. config.channels = channels;
  38086. config.sampleRate = sampleRate;
  38087. config.cutoffFrequency = cutoffFrequency;
  38088. config.q = q;
  38089. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  38090. if (config.q == 0) {
  38091. config.q = 0.707107;
  38092. }
  38093. return config;
  38094. }
  38095. typedef struct
  38096. {
  38097. size_t sizeInBytes;
  38098. size_t r1Offset;
  38099. } ma_lpf1_heap_layout;
  38100. static ma_result ma_lpf1_get_heap_layout(const ma_lpf1_config* pConfig, ma_lpf1_heap_layout* pHeapLayout)
  38101. {
  38102. MA_ASSERT(pHeapLayout != NULL);
  38103. MA_ZERO_OBJECT(pHeapLayout);
  38104. if (pConfig == NULL) {
  38105. return MA_INVALID_ARGS;
  38106. }
  38107. if (pConfig->channels == 0) {
  38108. return MA_INVALID_ARGS;
  38109. }
  38110. pHeapLayout->sizeInBytes = 0;
  38111. /* R1 */
  38112. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  38113. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  38114. /* Make sure allocation size is aligned. */
  38115. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38116. return MA_SUCCESS;
  38117. }
  38118. MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes)
  38119. {
  38120. ma_result result;
  38121. ma_lpf1_heap_layout heapLayout;
  38122. if (pHeapSizeInBytes == NULL) {
  38123. return MA_INVALID_ARGS;
  38124. }
  38125. result = ma_lpf1_get_heap_layout(pConfig, &heapLayout);
  38126. if (result != MA_SUCCESS) {
  38127. return result;
  38128. }
  38129. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38130. return MA_SUCCESS;
  38131. }
  38132. MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF)
  38133. {
  38134. ma_result result;
  38135. ma_lpf1_heap_layout heapLayout;
  38136. if (pLPF == NULL) {
  38137. return MA_INVALID_ARGS;
  38138. }
  38139. MA_ZERO_OBJECT(pLPF);
  38140. result = ma_lpf1_get_heap_layout(pConfig, &heapLayout);
  38141. if (result != MA_SUCCESS) {
  38142. return result;
  38143. }
  38144. pLPF->_pHeap = pHeap;
  38145. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38146. pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  38147. return ma_lpf1_reinit(pConfig, pLPF);
  38148. }
  38149. MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF)
  38150. {
  38151. ma_result result;
  38152. size_t heapSizeInBytes;
  38153. void* pHeap;
  38154. result = ma_lpf1_get_heap_size(pConfig, &heapSizeInBytes);
  38155. if (result != MA_SUCCESS) {
  38156. return result;
  38157. }
  38158. if (heapSizeInBytes > 0) {
  38159. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38160. if (pHeap == NULL) {
  38161. return MA_OUT_OF_MEMORY;
  38162. }
  38163. } else {
  38164. pHeap = NULL;
  38165. }
  38166. result = ma_lpf1_init_preallocated(pConfig, pHeap, pLPF);
  38167. if (result != MA_SUCCESS) {
  38168. ma_free(pHeap, pAllocationCallbacks);
  38169. return result;
  38170. }
  38171. pLPF->_ownsHeap = MA_TRUE;
  38172. return MA_SUCCESS;
  38173. }
  38174. MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38175. {
  38176. if (pLPF == NULL) {
  38177. return;
  38178. }
  38179. if (pLPF->_ownsHeap) {
  38180. ma_free(pLPF->_pHeap, pAllocationCallbacks);
  38181. }
  38182. }
  38183. MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF)
  38184. {
  38185. double a;
  38186. if (pLPF == NULL || pConfig == NULL) {
  38187. return MA_INVALID_ARGS;
  38188. }
  38189. /* Only supporting f32 and s16. */
  38190. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38191. return MA_INVALID_ARGS;
  38192. }
  38193. /* The format cannot be changed after initialization. */
  38194. if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
  38195. return MA_INVALID_OPERATION;
  38196. }
  38197. /* The channel count cannot be changed after initialization. */
  38198. if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
  38199. return MA_INVALID_OPERATION;
  38200. }
  38201. pLPF->format = pConfig->format;
  38202. pLPF->channels = pConfig->channels;
  38203. a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
  38204. if (pConfig->format == ma_format_f32) {
  38205. pLPF->a.f32 = (float)a;
  38206. } else {
  38207. pLPF->a.s32 = ma_biquad_float_to_fp(a);
  38208. }
  38209. return MA_SUCCESS;
  38210. }
  38211. MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF)
  38212. {
  38213. if (pLPF == NULL) {
  38214. return MA_INVALID_ARGS;
  38215. }
  38216. if (pLPF->format == ma_format_f32) {
  38217. pLPF->a.f32 = 0;
  38218. } else {
  38219. pLPF->a.s32 = 0;
  38220. }
  38221. return MA_SUCCESS;
  38222. }
  38223. static MA_INLINE void ma_lpf1_process_pcm_frame_f32(ma_lpf1* pLPF, float* pY, const float* pX)
  38224. {
  38225. ma_uint32 c;
  38226. const ma_uint32 channels = pLPF->channels;
  38227. const float a = pLPF->a.f32;
  38228. const float b = 1 - a;
  38229. MA_ASSUME(channels > 0);
  38230. for (c = 0; c < channels; c += 1) {
  38231. float r1 = pLPF->pR1[c].f32;
  38232. float x = pX[c];
  38233. float y;
  38234. y = b*x + a*r1;
  38235. pY[c] = y;
  38236. pLPF->pR1[c].f32 = y;
  38237. }
  38238. }
  38239. static MA_INLINE void ma_lpf1_process_pcm_frame_s16(ma_lpf1* pLPF, ma_int16* pY, const ma_int16* pX)
  38240. {
  38241. ma_uint32 c;
  38242. const ma_uint32 channels = pLPF->channels;
  38243. const ma_int32 a = pLPF->a.s32;
  38244. const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
  38245. MA_ASSUME(channels > 0);
  38246. for (c = 0; c < channels; c += 1) {
  38247. ma_int32 r1 = pLPF->pR1[c].s32;
  38248. ma_int32 x = pX[c];
  38249. ma_int32 y;
  38250. y = (b*x + a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  38251. pY[c] = (ma_int16)y;
  38252. pLPF->pR1[c].s32 = (ma_int32)y;
  38253. }
  38254. }
  38255. MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38256. {
  38257. ma_uint32 n;
  38258. if (pLPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38259. return MA_INVALID_ARGS;
  38260. }
  38261. /* 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. */
  38262. if (pLPF->format == ma_format_f32) {
  38263. /* */ float* pY = ( float*)pFramesOut;
  38264. const float* pX = (const float*)pFramesIn;
  38265. for (n = 0; n < frameCount; n += 1) {
  38266. ma_lpf1_process_pcm_frame_f32(pLPF, pY, pX);
  38267. pY += pLPF->channels;
  38268. pX += pLPF->channels;
  38269. }
  38270. } else if (pLPF->format == ma_format_s16) {
  38271. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38272. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38273. for (n = 0; n < frameCount; n += 1) {
  38274. ma_lpf1_process_pcm_frame_s16(pLPF, pY, pX);
  38275. pY += pLPF->channels;
  38276. pX += pLPF->channels;
  38277. }
  38278. } else {
  38279. MA_ASSERT(MA_FALSE);
  38280. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38281. }
  38282. return MA_SUCCESS;
  38283. }
  38284. MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF)
  38285. {
  38286. if (pLPF == NULL) {
  38287. return 0;
  38288. }
  38289. return 1;
  38290. }
  38291. static MA_INLINE ma_biquad_config ma_lpf2__get_biquad_config(const ma_lpf2_config* pConfig)
  38292. {
  38293. ma_biquad_config bqConfig;
  38294. double q;
  38295. double w;
  38296. double s;
  38297. double c;
  38298. double a;
  38299. MA_ASSERT(pConfig != NULL);
  38300. q = pConfig->q;
  38301. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  38302. s = ma_sind(w);
  38303. c = ma_cosd(w);
  38304. a = s / (2*q);
  38305. bqConfig.b0 = (1 - c) / 2;
  38306. bqConfig.b1 = 1 - c;
  38307. bqConfig.b2 = (1 - c) / 2;
  38308. bqConfig.a0 = 1 + a;
  38309. bqConfig.a1 = -2 * c;
  38310. bqConfig.a2 = 1 - a;
  38311. bqConfig.format = pConfig->format;
  38312. bqConfig.channels = pConfig->channels;
  38313. return bqConfig;
  38314. }
  38315. MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes)
  38316. {
  38317. ma_biquad_config bqConfig;
  38318. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  38319. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  38320. }
  38321. MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pLPF)
  38322. {
  38323. ma_result result;
  38324. ma_biquad_config bqConfig;
  38325. if (pLPF == NULL) {
  38326. return MA_INVALID_ARGS;
  38327. }
  38328. MA_ZERO_OBJECT(pLPF);
  38329. if (pConfig == NULL) {
  38330. return MA_INVALID_ARGS;
  38331. }
  38332. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  38333. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pLPF->bq);
  38334. if (result != MA_SUCCESS) {
  38335. return result;
  38336. }
  38337. return MA_SUCCESS;
  38338. }
  38339. MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF)
  38340. {
  38341. ma_result result;
  38342. size_t heapSizeInBytes;
  38343. void* pHeap;
  38344. result = ma_lpf2_get_heap_size(pConfig, &heapSizeInBytes);
  38345. if (result != MA_SUCCESS) {
  38346. return result;
  38347. }
  38348. if (heapSizeInBytes > 0) {
  38349. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38350. if (pHeap == NULL) {
  38351. return MA_OUT_OF_MEMORY;
  38352. }
  38353. } else {
  38354. pHeap = NULL;
  38355. }
  38356. result = ma_lpf2_init_preallocated(pConfig, pHeap, pLPF);
  38357. if (result != MA_SUCCESS) {
  38358. ma_free(pHeap, pAllocationCallbacks);
  38359. return result;
  38360. }
  38361. pLPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  38362. return MA_SUCCESS;
  38363. }
  38364. MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38365. {
  38366. if (pLPF == NULL) {
  38367. return;
  38368. }
  38369. ma_biquad_uninit(&pLPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  38370. }
  38371. MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF)
  38372. {
  38373. ma_result result;
  38374. ma_biquad_config bqConfig;
  38375. if (pLPF == NULL || pConfig == NULL) {
  38376. return MA_INVALID_ARGS;
  38377. }
  38378. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  38379. result = ma_biquad_reinit(&bqConfig, &pLPF->bq);
  38380. if (result != MA_SUCCESS) {
  38381. return result;
  38382. }
  38383. return MA_SUCCESS;
  38384. }
  38385. MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF)
  38386. {
  38387. if (pLPF == NULL) {
  38388. return MA_INVALID_ARGS;
  38389. }
  38390. ma_biquad_clear_cache(&pLPF->bq);
  38391. return MA_SUCCESS;
  38392. }
  38393. static MA_INLINE void ma_lpf2_process_pcm_frame_s16(ma_lpf2* pLPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  38394. {
  38395. ma_biquad_process_pcm_frame_s16(&pLPF->bq, pFrameOut, pFrameIn);
  38396. }
  38397. static MA_INLINE void ma_lpf2_process_pcm_frame_f32(ma_lpf2* pLPF, float* pFrameOut, const float* pFrameIn)
  38398. {
  38399. ma_biquad_process_pcm_frame_f32(&pLPF->bq, pFrameOut, pFrameIn);
  38400. }
  38401. MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38402. {
  38403. if (pLPF == NULL) {
  38404. return MA_INVALID_ARGS;
  38405. }
  38406. return ma_biquad_process_pcm_frames(&pLPF->bq, pFramesOut, pFramesIn, frameCount);
  38407. }
  38408. MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF)
  38409. {
  38410. if (pLPF == NULL) {
  38411. return 0;
  38412. }
  38413. return ma_biquad_get_latency(&pLPF->bq);
  38414. }
  38415. MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  38416. {
  38417. ma_lpf_config config;
  38418. MA_ZERO_OBJECT(&config);
  38419. config.format = format;
  38420. config.channels = channels;
  38421. config.sampleRate = sampleRate;
  38422. config.cutoffFrequency = cutoffFrequency;
  38423. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  38424. return config;
  38425. }
  38426. typedef struct
  38427. {
  38428. size_t sizeInBytes;
  38429. size_t lpf1Offset;
  38430. size_t lpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */
  38431. } ma_lpf_heap_layout;
  38432. static void ma_lpf_calculate_sub_lpf_counts(ma_uint32 order, ma_uint32* pLPF1Count, ma_uint32* pLPF2Count)
  38433. {
  38434. MA_ASSERT(pLPF1Count != NULL);
  38435. MA_ASSERT(pLPF2Count != NULL);
  38436. *pLPF1Count = order % 2;
  38437. *pLPF2Count = order / 2;
  38438. }
  38439. static ma_result ma_lpf_get_heap_layout(const ma_lpf_config* pConfig, ma_lpf_heap_layout* pHeapLayout)
  38440. {
  38441. ma_result result;
  38442. ma_uint32 lpf1Count;
  38443. ma_uint32 lpf2Count;
  38444. ma_uint32 ilpf1;
  38445. ma_uint32 ilpf2;
  38446. MA_ASSERT(pHeapLayout != NULL);
  38447. MA_ZERO_OBJECT(pHeapLayout);
  38448. if (pConfig == NULL) {
  38449. return MA_INVALID_ARGS;
  38450. }
  38451. if (pConfig->channels == 0) {
  38452. return MA_INVALID_ARGS;
  38453. }
  38454. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38455. return MA_INVALID_ARGS;
  38456. }
  38457. ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count);
  38458. pHeapLayout->sizeInBytes = 0;
  38459. /* LPF 1 */
  38460. pHeapLayout->lpf1Offset = pHeapLayout->sizeInBytes;
  38461. for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) {
  38462. size_t lpf1HeapSizeInBytes;
  38463. ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  38464. result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes);
  38465. if (result != MA_SUCCESS) {
  38466. return result;
  38467. }
  38468. pHeapLayout->sizeInBytes += sizeof(ma_lpf1) + lpf1HeapSizeInBytes;
  38469. }
  38470. /* LPF 2*/
  38471. pHeapLayout->lpf2Offset = pHeapLayout->sizeInBytes;
  38472. for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
  38473. size_t lpf2HeapSizeInBytes;
  38474. 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. */
  38475. result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes);
  38476. if (result != MA_SUCCESS) {
  38477. return result;
  38478. }
  38479. pHeapLayout->sizeInBytes += sizeof(ma_lpf2) + lpf2HeapSizeInBytes;
  38480. }
  38481. /* Make sure allocation size is aligned. */
  38482. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38483. return MA_SUCCESS;
  38484. }
  38485. static ma_result ma_lpf_reinit__internal(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF, ma_bool32 isNew)
  38486. {
  38487. ma_result result;
  38488. ma_uint32 lpf1Count;
  38489. ma_uint32 lpf2Count;
  38490. ma_uint32 ilpf1;
  38491. ma_uint32 ilpf2;
  38492. ma_lpf_heap_layout heapLayout; /* Only used if isNew is true. */
  38493. if (pLPF == NULL || pConfig == NULL) {
  38494. return MA_INVALID_ARGS;
  38495. }
  38496. /* Only supporting f32 and s16. */
  38497. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38498. return MA_INVALID_ARGS;
  38499. }
  38500. /* The format cannot be changed after initialization. */
  38501. if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
  38502. return MA_INVALID_OPERATION;
  38503. }
  38504. /* The channel count cannot be changed after initialization. */
  38505. if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
  38506. return MA_INVALID_OPERATION;
  38507. }
  38508. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38509. return MA_INVALID_ARGS;
  38510. }
  38511. ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count);
  38512. /* The filter order can't change between reinits. */
  38513. if (!isNew) {
  38514. if (pLPF->lpf1Count != lpf1Count || pLPF->lpf2Count != lpf2Count) {
  38515. return MA_INVALID_OPERATION;
  38516. }
  38517. }
  38518. if (isNew) {
  38519. result = ma_lpf_get_heap_layout(pConfig, &heapLayout);
  38520. if (result != MA_SUCCESS) {
  38521. return result;
  38522. }
  38523. pLPF->_pHeap = pHeap;
  38524. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38525. pLPF->pLPF1 = (ma_lpf1*)ma_offset_ptr(pHeap, heapLayout.lpf1Offset);
  38526. pLPF->pLPF2 = (ma_lpf2*)ma_offset_ptr(pHeap, heapLayout.lpf2Offset);
  38527. } else {
  38528. MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */
  38529. }
  38530. for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) {
  38531. ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  38532. if (isNew) {
  38533. size_t lpf1HeapSizeInBytes;
  38534. result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes);
  38535. if (result == MA_SUCCESS) {
  38536. result = ma_lpf1_init_preallocated(&lpf1Config, ma_offset_ptr(pHeap, heapLayout.lpf1Offset + (sizeof(ma_lpf1) * lpf1Count) + (ilpf1 * lpf1HeapSizeInBytes)), &pLPF->pLPF1[ilpf1]);
  38537. }
  38538. } else {
  38539. result = ma_lpf1_reinit(&lpf1Config, &pLPF->pLPF1[ilpf1]);
  38540. }
  38541. if (result != MA_SUCCESS) {
  38542. ma_uint32 jlpf1;
  38543. for (jlpf1 = 0; jlpf1 < ilpf1; jlpf1 += 1) {
  38544. ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38545. }
  38546. return result;
  38547. }
  38548. }
  38549. for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
  38550. ma_lpf2_config lpf2Config;
  38551. double q;
  38552. double a;
  38553. /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
  38554. if (lpf1Count == 1) {
  38555. a = (1 + ilpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
  38556. } else {
  38557. a = (1 + ilpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
  38558. }
  38559. q = 1 / (2*ma_cosd(a));
  38560. lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  38561. if (isNew) {
  38562. size_t lpf2HeapSizeInBytes;
  38563. result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes);
  38564. if (result == MA_SUCCESS) {
  38565. result = ma_lpf2_init_preallocated(&lpf2Config, ma_offset_ptr(pHeap, heapLayout.lpf2Offset + (sizeof(ma_lpf2) * lpf2Count) + (ilpf2 * lpf2HeapSizeInBytes)), &pLPF->pLPF2[ilpf2]);
  38566. }
  38567. } else {
  38568. result = ma_lpf2_reinit(&lpf2Config, &pLPF->pLPF2[ilpf2]);
  38569. }
  38570. if (result != MA_SUCCESS) {
  38571. ma_uint32 jlpf1;
  38572. ma_uint32 jlpf2;
  38573. for (jlpf1 = 0; jlpf1 < lpf1Count; jlpf1 += 1) {
  38574. ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38575. }
  38576. for (jlpf2 = 0; jlpf2 < ilpf2; jlpf2 += 1) {
  38577. ma_lpf2_uninit(&pLPF->pLPF2[jlpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38578. }
  38579. return result;
  38580. }
  38581. }
  38582. pLPF->lpf1Count = lpf1Count;
  38583. pLPF->lpf2Count = lpf2Count;
  38584. pLPF->format = pConfig->format;
  38585. pLPF->channels = pConfig->channels;
  38586. pLPF->sampleRate = pConfig->sampleRate;
  38587. return MA_SUCCESS;
  38588. }
  38589. MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes)
  38590. {
  38591. ma_result result;
  38592. ma_lpf_heap_layout heapLayout;
  38593. if (pHeapSizeInBytes == NULL) {
  38594. return MA_INVALID_ARGS;
  38595. }
  38596. *pHeapSizeInBytes = 0;
  38597. result = ma_lpf_get_heap_layout(pConfig, &heapLayout);
  38598. if (result != MA_SUCCESS) {
  38599. return result;
  38600. }
  38601. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38602. return result;
  38603. }
  38604. MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF)
  38605. {
  38606. if (pLPF == NULL) {
  38607. return MA_INVALID_ARGS;
  38608. }
  38609. MA_ZERO_OBJECT(pLPF);
  38610. return ma_lpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE);
  38611. }
  38612. MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF)
  38613. {
  38614. ma_result result;
  38615. size_t heapSizeInBytes;
  38616. void* pHeap;
  38617. result = ma_lpf_get_heap_size(pConfig, &heapSizeInBytes);
  38618. if (result != MA_SUCCESS) {
  38619. return result;
  38620. }
  38621. if (heapSizeInBytes > 0) {
  38622. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38623. if (pHeap == NULL) {
  38624. return MA_OUT_OF_MEMORY;
  38625. }
  38626. } else {
  38627. pHeap = NULL;
  38628. }
  38629. result = ma_lpf_init_preallocated(pConfig, pHeap, pLPF);
  38630. if (result != MA_SUCCESS) {
  38631. ma_free(pHeap, pAllocationCallbacks);
  38632. return result;
  38633. }
  38634. pLPF->_ownsHeap = MA_TRUE;
  38635. return MA_SUCCESS;
  38636. }
  38637. MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38638. {
  38639. ma_uint32 ilpf1;
  38640. ma_uint32 ilpf2;
  38641. if (pLPF == NULL) {
  38642. return;
  38643. }
  38644. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38645. ma_lpf1_uninit(&pLPF->pLPF1[ilpf1], pAllocationCallbacks);
  38646. }
  38647. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38648. ma_lpf2_uninit(&pLPF->pLPF2[ilpf2], pAllocationCallbacks);
  38649. }
  38650. if (pLPF->_ownsHeap) {
  38651. ma_free(pLPF->_pHeap, pAllocationCallbacks);
  38652. }
  38653. }
  38654. MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF)
  38655. {
  38656. return ma_lpf_reinit__internal(pConfig, NULL, pLPF, /*isNew*/MA_FALSE);
  38657. }
  38658. MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF)
  38659. {
  38660. ma_uint32 ilpf1;
  38661. ma_uint32 ilpf2;
  38662. if (pLPF == NULL) {
  38663. return MA_INVALID_ARGS;
  38664. }
  38665. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38666. ma_lpf1_clear_cache(&pLPF->pLPF1[ilpf1]);
  38667. }
  38668. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38669. ma_lpf2_clear_cache(&pLPF->pLPF2[ilpf2]);
  38670. }
  38671. return MA_SUCCESS;
  38672. }
  38673. static MA_INLINE void ma_lpf_process_pcm_frame_f32(ma_lpf* pLPF, float* pY, const void* pX)
  38674. {
  38675. ma_uint32 ilpf1;
  38676. ma_uint32 ilpf2;
  38677. MA_ASSERT(pLPF->format == ma_format_f32);
  38678. MA_MOVE_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
  38679. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38680. ma_lpf1_process_pcm_frame_f32(&pLPF->pLPF1[ilpf1], pY, pY);
  38681. }
  38682. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38683. ma_lpf2_process_pcm_frame_f32(&pLPF->pLPF2[ilpf2], pY, pY);
  38684. }
  38685. }
  38686. static MA_INLINE void ma_lpf_process_pcm_frame_s16(ma_lpf* pLPF, ma_int16* pY, const ma_int16* pX)
  38687. {
  38688. ma_uint32 ilpf1;
  38689. ma_uint32 ilpf2;
  38690. MA_ASSERT(pLPF->format == ma_format_s16);
  38691. MA_MOVE_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
  38692. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38693. ma_lpf1_process_pcm_frame_s16(&pLPF->pLPF1[ilpf1], pY, pY);
  38694. }
  38695. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38696. ma_lpf2_process_pcm_frame_s16(&pLPF->pLPF2[ilpf2], pY, pY);
  38697. }
  38698. }
  38699. MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38700. {
  38701. ma_result result;
  38702. ma_uint32 ilpf1;
  38703. ma_uint32 ilpf2;
  38704. if (pLPF == NULL) {
  38705. return MA_INVALID_ARGS;
  38706. }
  38707. /* Faster path for in-place. */
  38708. if (pFramesOut == pFramesIn) {
  38709. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  38710. result = ma_lpf1_process_pcm_frames(&pLPF->pLPF1[ilpf1], pFramesOut, pFramesOut, frameCount);
  38711. if (result != MA_SUCCESS) {
  38712. return result;
  38713. }
  38714. }
  38715. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  38716. result = ma_lpf2_process_pcm_frames(&pLPF->pLPF2[ilpf2], pFramesOut, pFramesOut, frameCount);
  38717. if (result != MA_SUCCESS) {
  38718. return result;
  38719. }
  38720. }
  38721. }
  38722. /* Slightly slower path for copying. */
  38723. if (pFramesOut != pFramesIn) {
  38724. ma_uint32 iFrame;
  38725. /* */ if (pLPF->format == ma_format_f32) {
  38726. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  38727. const float* pFramesInF32 = (const float*)pFramesIn;
  38728. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38729. ma_lpf_process_pcm_frame_f32(pLPF, pFramesOutF32, pFramesInF32);
  38730. pFramesOutF32 += pLPF->channels;
  38731. pFramesInF32 += pLPF->channels;
  38732. }
  38733. } else if (pLPF->format == ma_format_s16) {
  38734. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  38735. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  38736. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38737. ma_lpf_process_pcm_frame_s16(pLPF, pFramesOutS16, pFramesInS16);
  38738. pFramesOutS16 += pLPF->channels;
  38739. pFramesInS16 += pLPF->channels;
  38740. }
  38741. } else {
  38742. MA_ASSERT(MA_FALSE);
  38743. return MA_INVALID_OPERATION; /* Should never hit this. */
  38744. }
  38745. }
  38746. return MA_SUCCESS;
  38747. }
  38748. MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF)
  38749. {
  38750. if (pLPF == NULL) {
  38751. return 0;
  38752. }
  38753. return pLPF->lpf2Count*2 + pLPF->lpf1Count;
  38754. }
  38755. /**************************************************************************************************************************************************************
  38756. High-Pass Filtering
  38757. **************************************************************************************************************************************************************/
  38758. MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
  38759. {
  38760. ma_hpf1_config config;
  38761. MA_ZERO_OBJECT(&config);
  38762. config.format = format;
  38763. config.channels = channels;
  38764. config.sampleRate = sampleRate;
  38765. config.cutoffFrequency = cutoffFrequency;
  38766. return config;
  38767. }
  38768. MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  38769. {
  38770. ma_hpf2_config config;
  38771. MA_ZERO_OBJECT(&config);
  38772. config.format = format;
  38773. config.channels = channels;
  38774. config.sampleRate = sampleRate;
  38775. config.cutoffFrequency = cutoffFrequency;
  38776. config.q = q;
  38777. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  38778. if (config.q == 0) {
  38779. config.q = 0.707107;
  38780. }
  38781. return config;
  38782. }
  38783. typedef struct
  38784. {
  38785. size_t sizeInBytes;
  38786. size_t r1Offset;
  38787. } ma_hpf1_heap_layout;
  38788. static ma_result ma_hpf1_get_heap_layout(const ma_hpf1_config* pConfig, ma_hpf1_heap_layout* pHeapLayout)
  38789. {
  38790. MA_ASSERT(pHeapLayout != NULL);
  38791. MA_ZERO_OBJECT(pHeapLayout);
  38792. if (pConfig == NULL) {
  38793. return MA_INVALID_ARGS;
  38794. }
  38795. if (pConfig->channels == 0) {
  38796. return MA_INVALID_ARGS;
  38797. }
  38798. pHeapLayout->sizeInBytes = 0;
  38799. /* R1 */
  38800. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  38801. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  38802. /* Make sure allocation size is aligned. */
  38803. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38804. return MA_SUCCESS;
  38805. }
  38806. MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes)
  38807. {
  38808. ma_result result;
  38809. ma_hpf1_heap_layout heapLayout;
  38810. if (pHeapSizeInBytes == NULL) {
  38811. return MA_INVALID_ARGS;
  38812. }
  38813. result = ma_hpf1_get_heap_layout(pConfig, &heapLayout);
  38814. if (result != MA_SUCCESS) {
  38815. return result;
  38816. }
  38817. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38818. return MA_SUCCESS;
  38819. }
  38820. MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF)
  38821. {
  38822. ma_result result;
  38823. ma_hpf1_heap_layout heapLayout;
  38824. if (pLPF == NULL) {
  38825. return MA_INVALID_ARGS;
  38826. }
  38827. MA_ZERO_OBJECT(pLPF);
  38828. result = ma_hpf1_get_heap_layout(pConfig, &heapLayout);
  38829. if (result != MA_SUCCESS) {
  38830. return result;
  38831. }
  38832. pLPF->_pHeap = pHeap;
  38833. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38834. pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  38835. return ma_hpf1_reinit(pConfig, pLPF);
  38836. }
  38837. MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pLPF)
  38838. {
  38839. ma_result result;
  38840. size_t heapSizeInBytes;
  38841. void* pHeap;
  38842. result = ma_hpf1_get_heap_size(pConfig, &heapSizeInBytes);
  38843. if (result != MA_SUCCESS) {
  38844. return result;
  38845. }
  38846. if (heapSizeInBytes > 0) {
  38847. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38848. if (pHeap == NULL) {
  38849. return MA_OUT_OF_MEMORY;
  38850. }
  38851. } else {
  38852. pHeap = NULL;
  38853. }
  38854. result = ma_hpf1_init_preallocated(pConfig, pHeap, pLPF);
  38855. if (result != MA_SUCCESS) {
  38856. ma_free(pHeap, pAllocationCallbacks);
  38857. return result;
  38858. }
  38859. pLPF->_ownsHeap = MA_TRUE;
  38860. return MA_SUCCESS;
  38861. }
  38862. MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38863. {
  38864. if (pHPF == NULL) {
  38865. return;
  38866. }
  38867. if (pHPF->_ownsHeap) {
  38868. ma_free(pHPF->_pHeap, pAllocationCallbacks);
  38869. }
  38870. }
  38871. MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF)
  38872. {
  38873. double a;
  38874. if (pHPF == NULL || pConfig == NULL) {
  38875. return MA_INVALID_ARGS;
  38876. }
  38877. /* Only supporting f32 and s16. */
  38878. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38879. return MA_INVALID_ARGS;
  38880. }
  38881. /* The format cannot be changed after initialization. */
  38882. if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
  38883. return MA_INVALID_OPERATION;
  38884. }
  38885. /* The channel count cannot be changed after initialization. */
  38886. if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
  38887. return MA_INVALID_OPERATION;
  38888. }
  38889. pHPF->format = pConfig->format;
  38890. pHPF->channels = pConfig->channels;
  38891. a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
  38892. if (pConfig->format == ma_format_f32) {
  38893. pHPF->a.f32 = (float)a;
  38894. } else {
  38895. pHPF->a.s32 = ma_biquad_float_to_fp(a);
  38896. }
  38897. return MA_SUCCESS;
  38898. }
  38899. static MA_INLINE void ma_hpf1_process_pcm_frame_f32(ma_hpf1* pHPF, float* pY, const float* pX)
  38900. {
  38901. ma_uint32 c;
  38902. const ma_uint32 channels = pHPF->channels;
  38903. const float a = 1 - pHPF->a.f32;
  38904. const float b = 1 - a;
  38905. MA_ASSUME(channels > 0);
  38906. for (c = 0; c < channels; c += 1) {
  38907. float r1 = pHPF->pR1[c].f32;
  38908. float x = pX[c];
  38909. float y;
  38910. y = b*x - a*r1;
  38911. pY[c] = y;
  38912. pHPF->pR1[c].f32 = y;
  38913. }
  38914. }
  38915. static MA_INLINE void ma_hpf1_process_pcm_frame_s16(ma_hpf1* pHPF, ma_int16* pY, const ma_int16* pX)
  38916. {
  38917. ma_uint32 c;
  38918. const ma_uint32 channels = pHPF->channels;
  38919. const ma_int32 a = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - pHPF->a.s32);
  38920. const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
  38921. MA_ASSUME(channels > 0);
  38922. for (c = 0; c < channels; c += 1) {
  38923. ma_int32 r1 = pHPF->pR1[c].s32;
  38924. ma_int32 x = pX[c];
  38925. ma_int32 y;
  38926. y = (b*x - a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  38927. pY[c] = (ma_int16)y;
  38928. pHPF->pR1[c].s32 = (ma_int32)y;
  38929. }
  38930. }
  38931. MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38932. {
  38933. ma_uint32 n;
  38934. if (pHPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38935. return MA_INVALID_ARGS;
  38936. }
  38937. /* 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. */
  38938. if (pHPF->format == ma_format_f32) {
  38939. /* */ float* pY = ( float*)pFramesOut;
  38940. const float* pX = (const float*)pFramesIn;
  38941. for (n = 0; n < frameCount; n += 1) {
  38942. ma_hpf1_process_pcm_frame_f32(pHPF, pY, pX);
  38943. pY += pHPF->channels;
  38944. pX += pHPF->channels;
  38945. }
  38946. } else if (pHPF->format == ma_format_s16) {
  38947. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38948. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38949. for (n = 0; n < frameCount; n += 1) {
  38950. ma_hpf1_process_pcm_frame_s16(pHPF, pY, pX);
  38951. pY += pHPF->channels;
  38952. pX += pHPF->channels;
  38953. }
  38954. } else {
  38955. MA_ASSERT(MA_FALSE);
  38956. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38957. }
  38958. return MA_SUCCESS;
  38959. }
  38960. MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF)
  38961. {
  38962. if (pHPF == NULL) {
  38963. return 0;
  38964. }
  38965. return 1;
  38966. }
  38967. static MA_INLINE ma_biquad_config ma_hpf2__get_biquad_config(const ma_hpf2_config* pConfig)
  38968. {
  38969. ma_biquad_config bqConfig;
  38970. double q;
  38971. double w;
  38972. double s;
  38973. double c;
  38974. double a;
  38975. MA_ASSERT(pConfig != NULL);
  38976. q = pConfig->q;
  38977. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  38978. s = ma_sind(w);
  38979. c = ma_cosd(w);
  38980. a = s / (2*q);
  38981. bqConfig.b0 = (1 + c) / 2;
  38982. bqConfig.b1 = -(1 + c);
  38983. bqConfig.b2 = (1 + c) / 2;
  38984. bqConfig.a0 = 1 + a;
  38985. bqConfig.a1 = -2 * c;
  38986. bqConfig.a2 = 1 - a;
  38987. bqConfig.format = pConfig->format;
  38988. bqConfig.channels = pConfig->channels;
  38989. return bqConfig;
  38990. }
  38991. MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes)
  38992. {
  38993. ma_biquad_config bqConfig;
  38994. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  38995. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  38996. }
  38997. MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF)
  38998. {
  38999. ma_result result;
  39000. ma_biquad_config bqConfig;
  39001. if (pHPF == NULL) {
  39002. return MA_INVALID_ARGS;
  39003. }
  39004. MA_ZERO_OBJECT(pHPF);
  39005. if (pConfig == NULL) {
  39006. return MA_INVALID_ARGS;
  39007. }
  39008. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  39009. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pHPF->bq);
  39010. if (result != MA_SUCCESS) {
  39011. return result;
  39012. }
  39013. return MA_SUCCESS;
  39014. }
  39015. MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF)
  39016. {
  39017. ma_result result;
  39018. size_t heapSizeInBytes;
  39019. void* pHeap;
  39020. result = ma_hpf2_get_heap_size(pConfig, &heapSizeInBytes);
  39021. if (result != MA_SUCCESS) {
  39022. return result;
  39023. }
  39024. if (heapSizeInBytes > 0) {
  39025. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39026. if (pHeap == NULL) {
  39027. return MA_OUT_OF_MEMORY;
  39028. }
  39029. } else {
  39030. pHeap = NULL;
  39031. }
  39032. result = ma_hpf2_init_preallocated(pConfig, pHeap, pHPF);
  39033. if (result != MA_SUCCESS) {
  39034. ma_free(pHeap, pAllocationCallbacks);
  39035. return result;
  39036. }
  39037. pHPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39038. return MA_SUCCESS;
  39039. }
  39040. MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39041. {
  39042. if (pHPF == NULL) {
  39043. return;
  39044. }
  39045. ma_biquad_uninit(&pHPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39046. }
  39047. MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF)
  39048. {
  39049. ma_result result;
  39050. ma_biquad_config bqConfig;
  39051. if (pHPF == NULL || pConfig == NULL) {
  39052. return MA_INVALID_ARGS;
  39053. }
  39054. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  39055. result = ma_biquad_reinit(&bqConfig, &pHPF->bq);
  39056. if (result != MA_SUCCESS) {
  39057. return result;
  39058. }
  39059. return MA_SUCCESS;
  39060. }
  39061. static MA_INLINE void ma_hpf2_process_pcm_frame_s16(ma_hpf2* pHPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39062. {
  39063. ma_biquad_process_pcm_frame_s16(&pHPF->bq, pFrameOut, pFrameIn);
  39064. }
  39065. static MA_INLINE void ma_hpf2_process_pcm_frame_f32(ma_hpf2* pHPF, float* pFrameOut, const float* pFrameIn)
  39066. {
  39067. ma_biquad_process_pcm_frame_f32(&pHPF->bq, pFrameOut, pFrameIn);
  39068. }
  39069. MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39070. {
  39071. if (pHPF == NULL) {
  39072. return MA_INVALID_ARGS;
  39073. }
  39074. return ma_biquad_process_pcm_frames(&pHPF->bq, pFramesOut, pFramesIn, frameCount);
  39075. }
  39076. MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF)
  39077. {
  39078. if (pHPF == NULL) {
  39079. return 0;
  39080. }
  39081. return ma_biquad_get_latency(&pHPF->bq);
  39082. }
  39083. MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  39084. {
  39085. ma_hpf_config config;
  39086. MA_ZERO_OBJECT(&config);
  39087. config.format = format;
  39088. config.channels = channels;
  39089. config.sampleRate = sampleRate;
  39090. config.cutoffFrequency = cutoffFrequency;
  39091. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  39092. return config;
  39093. }
  39094. typedef struct
  39095. {
  39096. size_t sizeInBytes;
  39097. size_t hpf1Offset;
  39098. size_t hpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */
  39099. } ma_hpf_heap_layout;
  39100. static void ma_hpf_calculate_sub_hpf_counts(ma_uint32 order, ma_uint32* pHPF1Count, ma_uint32* pHPF2Count)
  39101. {
  39102. MA_ASSERT(pHPF1Count != NULL);
  39103. MA_ASSERT(pHPF2Count != NULL);
  39104. *pHPF1Count = order % 2;
  39105. *pHPF2Count = order / 2;
  39106. }
  39107. static ma_result ma_hpf_get_heap_layout(const ma_hpf_config* pConfig, ma_hpf_heap_layout* pHeapLayout)
  39108. {
  39109. ma_result result;
  39110. ma_uint32 hpf1Count;
  39111. ma_uint32 hpf2Count;
  39112. ma_uint32 ihpf1;
  39113. ma_uint32 ihpf2;
  39114. MA_ASSERT(pHeapLayout != NULL);
  39115. MA_ZERO_OBJECT(pHeapLayout);
  39116. if (pConfig == NULL) {
  39117. return MA_INVALID_ARGS;
  39118. }
  39119. if (pConfig->channels == 0) {
  39120. return MA_INVALID_ARGS;
  39121. }
  39122. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39123. return MA_INVALID_ARGS;
  39124. }
  39125. ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count);
  39126. pHeapLayout->sizeInBytes = 0;
  39127. /* HPF 1 */
  39128. pHeapLayout->hpf1Offset = pHeapLayout->sizeInBytes;
  39129. for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) {
  39130. size_t hpf1HeapSizeInBytes;
  39131. ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  39132. result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes);
  39133. if (result != MA_SUCCESS) {
  39134. return result;
  39135. }
  39136. pHeapLayout->sizeInBytes += sizeof(ma_hpf1) + hpf1HeapSizeInBytes;
  39137. }
  39138. /* HPF 2*/
  39139. pHeapLayout->hpf2Offset = pHeapLayout->sizeInBytes;
  39140. for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
  39141. size_t hpf2HeapSizeInBytes;
  39142. 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. */
  39143. result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes);
  39144. if (result != MA_SUCCESS) {
  39145. return result;
  39146. }
  39147. pHeapLayout->sizeInBytes += sizeof(ma_hpf2) + hpf2HeapSizeInBytes;
  39148. }
  39149. /* Make sure allocation size is aligned. */
  39150. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  39151. return MA_SUCCESS;
  39152. }
  39153. static ma_result ma_hpf_reinit__internal(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pHPF, ma_bool32 isNew)
  39154. {
  39155. ma_result result;
  39156. ma_uint32 hpf1Count;
  39157. ma_uint32 hpf2Count;
  39158. ma_uint32 ihpf1;
  39159. ma_uint32 ihpf2;
  39160. ma_hpf_heap_layout heapLayout; /* Only used if isNew is true. */
  39161. if (pHPF == NULL || pConfig == NULL) {
  39162. return MA_INVALID_ARGS;
  39163. }
  39164. /* Only supporting f32 and s16. */
  39165. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  39166. return MA_INVALID_ARGS;
  39167. }
  39168. /* The format cannot be changed after initialization. */
  39169. if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
  39170. return MA_INVALID_OPERATION;
  39171. }
  39172. /* The channel count cannot be changed after initialization. */
  39173. if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
  39174. return MA_INVALID_OPERATION;
  39175. }
  39176. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39177. return MA_INVALID_ARGS;
  39178. }
  39179. ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count);
  39180. /* The filter order can't change between reinits. */
  39181. if (!isNew) {
  39182. if (pHPF->hpf1Count != hpf1Count || pHPF->hpf2Count != hpf2Count) {
  39183. return MA_INVALID_OPERATION;
  39184. }
  39185. }
  39186. if (isNew) {
  39187. result = ma_hpf_get_heap_layout(pConfig, &heapLayout);
  39188. if (result != MA_SUCCESS) {
  39189. return result;
  39190. }
  39191. pHPF->_pHeap = pHeap;
  39192. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  39193. pHPF->pHPF1 = (ma_hpf1*)ma_offset_ptr(pHeap, heapLayout.hpf1Offset);
  39194. pHPF->pHPF2 = (ma_hpf2*)ma_offset_ptr(pHeap, heapLayout.hpf2Offset);
  39195. } else {
  39196. MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */
  39197. }
  39198. for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) {
  39199. ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  39200. if (isNew) {
  39201. size_t hpf1HeapSizeInBytes;
  39202. result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes);
  39203. if (result == MA_SUCCESS) {
  39204. result = ma_hpf1_init_preallocated(&hpf1Config, ma_offset_ptr(pHeap, heapLayout.hpf1Offset + (sizeof(ma_hpf1) * hpf1Count) + (ihpf1 * hpf1HeapSizeInBytes)), &pHPF->pHPF1[ihpf1]);
  39205. }
  39206. } else {
  39207. result = ma_hpf1_reinit(&hpf1Config, &pHPF->pHPF1[ihpf1]);
  39208. }
  39209. if (result != MA_SUCCESS) {
  39210. ma_uint32 jhpf1;
  39211. for (jhpf1 = 0; jhpf1 < ihpf1; jhpf1 += 1) {
  39212. ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  39213. }
  39214. return result;
  39215. }
  39216. }
  39217. for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
  39218. ma_hpf2_config hpf2Config;
  39219. double q;
  39220. double a;
  39221. /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
  39222. if (hpf1Count == 1) {
  39223. a = (1 + ihpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
  39224. } else {
  39225. a = (1 + ihpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
  39226. }
  39227. q = 1 / (2*ma_cosd(a));
  39228. hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  39229. if (isNew) {
  39230. size_t hpf2HeapSizeInBytes;
  39231. result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes);
  39232. if (result == MA_SUCCESS) {
  39233. result = ma_hpf2_init_preallocated(&hpf2Config, ma_offset_ptr(pHeap, heapLayout.hpf2Offset + (sizeof(ma_hpf2) * hpf2Count) + (ihpf2 * hpf2HeapSizeInBytes)), &pHPF->pHPF2[ihpf2]);
  39234. }
  39235. } else {
  39236. result = ma_hpf2_reinit(&hpf2Config, &pHPF->pHPF2[ihpf2]);
  39237. }
  39238. if (result != MA_SUCCESS) {
  39239. ma_uint32 jhpf1;
  39240. ma_uint32 jhpf2;
  39241. for (jhpf1 = 0; jhpf1 < hpf1Count; jhpf1 += 1) {
  39242. ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  39243. }
  39244. for (jhpf2 = 0; jhpf2 < ihpf2; jhpf2 += 1) {
  39245. ma_hpf2_uninit(&pHPF->pHPF2[jhpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  39246. }
  39247. return result;
  39248. }
  39249. }
  39250. pHPF->hpf1Count = hpf1Count;
  39251. pHPF->hpf2Count = hpf2Count;
  39252. pHPF->format = pConfig->format;
  39253. pHPF->channels = pConfig->channels;
  39254. pHPF->sampleRate = pConfig->sampleRate;
  39255. return MA_SUCCESS;
  39256. }
  39257. MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes)
  39258. {
  39259. ma_result result;
  39260. ma_hpf_heap_layout heapLayout;
  39261. if (pHeapSizeInBytes == NULL) {
  39262. return MA_INVALID_ARGS;
  39263. }
  39264. *pHeapSizeInBytes = 0;
  39265. result = ma_hpf_get_heap_layout(pConfig, &heapLayout);
  39266. if (result != MA_SUCCESS) {
  39267. return result;
  39268. }
  39269. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  39270. return result;
  39271. }
  39272. MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF)
  39273. {
  39274. if (pLPF == NULL) {
  39275. return MA_INVALID_ARGS;
  39276. }
  39277. MA_ZERO_OBJECT(pLPF);
  39278. return ma_hpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE);
  39279. }
  39280. MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF)
  39281. {
  39282. ma_result result;
  39283. size_t heapSizeInBytes;
  39284. void* pHeap;
  39285. result = ma_hpf_get_heap_size(pConfig, &heapSizeInBytes);
  39286. if (result != MA_SUCCESS) {
  39287. return result;
  39288. }
  39289. if (heapSizeInBytes > 0) {
  39290. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39291. if (pHeap == NULL) {
  39292. return MA_OUT_OF_MEMORY;
  39293. }
  39294. } else {
  39295. pHeap = NULL;
  39296. }
  39297. result = ma_hpf_init_preallocated(pConfig, pHeap, pHPF);
  39298. if (result != MA_SUCCESS) {
  39299. ma_free(pHeap, pAllocationCallbacks);
  39300. return result;
  39301. }
  39302. pHPF->_ownsHeap = MA_TRUE;
  39303. return MA_SUCCESS;
  39304. }
  39305. MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39306. {
  39307. ma_uint32 ihpf1;
  39308. ma_uint32 ihpf2;
  39309. if (pHPF == NULL) {
  39310. return;
  39311. }
  39312. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39313. ma_hpf1_uninit(&pHPF->pHPF1[ihpf1], pAllocationCallbacks);
  39314. }
  39315. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39316. ma_hpf2_uninit(&pHPF->pHPF2[ihpf2], pAllocationCallbacks);
  39317. }
  39318. if (pHPF->_ownsHeap) {
  39319. ma_free(pHPF->_pHeap, pAllocationCallbacks);
  39320. }
  39321. }
  39322. MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF)
  39323. {
  39324. return ma_hpf_reinit__internal(pConfig, NULL, pHPF, /*isNew*/MA_FALSE);
  39325. }
  39326. MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39327. {
  39328. ma_result result;
  39329. ma_uint32 ihpf1;
  39330. ma_uint32 ihpf2;
  39331. if (pHPF == NULL) {
  39332. return MA_INVALID_ARGS;
  39333. }
  39334. /* Faster path for in-place. */
  39335. if (pFramesOut == pFramesIn) {
  39336. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39337. result = ma_hpf1_process_pcm_frames(&pHPF->pHPF1[ihpf1], pFramesOut, pFramesOut, frameCount);
  39338. if (result != MA_SUCCESS) {
  39339. return result;
  39340. }
  39341. }
  39342. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39343. result = ma_hpf2_process_pcm_frames(&pHPF->pHPF2[ihpf2], pFramesOut, pFramesOut, frameCount);
  39344. if (result != MA_SUCCESS) {
  39345. return result;
  39346. }
  39347. }
  39348. }
  39349. /* Slightly slower path for copying. */
  39350. if (pFramesOut != pFramesIn) {
  39351. ma_uint32 iFrame;
  39352. /* */ if (pHPF->format == ma_format_f32) {
  39353. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  39354. const float* pFramesInF32 = (const float*)pFramesIn;
  39355. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39356. MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
  39357. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39358. ma_hpf1_process_pcm_frame_f32(&pHPF->pHPF1[ihpf1], pFramesOutF32, pFramesOutF32);
  39359. }
  39360. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39361. ma_hpf2_process_pcm_frame_f32(&pHPF->pHPF2[ihpf2], pFramesOutF32, pFramesOutF32);
  39362. }
  39363. pFramesOutF32 += pHPF->channels;
  39364. pFramesInF32 += pHPF->channels;
  39365. }
  39366. } else if (pHPF->format == ma_format_s16) {
  39367. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  39368. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  39369. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39370. MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
  39371. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  39372. ma_hpf1_process_pcm_frame_s16(&pHPF->pHPF1[ihpf1], pFramesOutS16, pFramesOutS16);
  39373. }
  39374. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  39375. ma_hpf2_process_pcm_frame_s16(&pHPF->pHPF2[ihpf2], pFramesOutS16, pFramesOutS16);
  39376. }
  39377. pFramesOutS16 += pHPF->channels;
  39378. pFramesInS16 += pHPF->channels;
  39379. }
  39380. } else {
  39381. MA_ASSERT(MA_FALSE);
  39382. return MA_INVALID_OPERATION; /* Should never hit this. */
  39383. }
  39384. }
  39385. return MA_SUCCESS;
  39386. }
  39387. MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF)
  39388. {
  39389. if (pHPF == NULL) {
  39390. return 0;
  39391. }
  39392. return pHPF->hpf2Count*2 + pHPF->hpf1Count;
  39393. }
  39394. /**************************************************************************************************************************************************************
  39395. Band-Pass Filtering
  39396. **************************************************************************************************************************************************************/
  39397. MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  39398. {
  39399. ma_bpf2_config config;
  39400. MA_ZERO_OBJECT(&config);
  39401. config.format = format;
  39402. config.channels = channels;
  39403. config.sampleRate = sampleRate;
  39404. config.cutoffFrequency = cutoffFrequency;
  39405. config.q = q;
  39406. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  39407. if (config.q == 0) {
  39408. config.q = 0.707107;
  39409. }
  39410. return config;
  39411. }
  39412. static MA_INLINE ma_biquad_config ma_bpf2__get_biquad_config(const ma_bpf2_config* pConfig)
  39413. {
  39414. ma_biquad_config bqConfig;
  39415. double q;
  39416. double w;
  39417. double s;
  39418. double c;
  39419. double a;
  39420. MA_ASSERT(pConfig != NULL);
  39421. q = pConfig->q;
  39422. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  39423. s = ma_sind(w);
  39424. c = ma_cosd(w);
  39425. a = s / (2*q);
  39426. bqConfig.b0 = q * a;
  39427. bqConfig.b1 = 0;
  39428. bqConfig.b2 = -q * a;
  39429. bqConfig.a0 = 1 + a;
  39430. bqConfig.a1 = -2 * c;
  39431. bqConfig.a2 = 1 - a;
  39432. bqConfig.format = pConfig->format;
  39433. bqConfig.channels = pConfig->channels;
  39434. return bqConfig;
  39435. }
  39436. MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes)
  39437. {
  39438. ma_biquad_config bqConfig;
  39439. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  39440. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39441. }
  39442. MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF)
  39443. {
  39444. ma_result result;
  39445. ma_biquad_config bqConfig;
  39446. if (pBPF == NULL) {
  39447. return MA_INVALID_ARGS;
  39448. }
  39449. MA_ZERO_OBJECT(pBPF);
  39450. if (pConfig == NULL) {
  39451. return MA_INVALID_ARGS;
  39452. }
  39453. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  39454. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pBPF->bq);
  39455. if (result != MA_SUCCESS) {
  39456. return result;
  39457. }
  39458. return MA_SUCCESS;
  39459. }
  39460. MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF)
  39461. {
  39462. ma_result result;
  39463. size_t heapSizeInBytes;
  39464. void* pHeap;
  39465. result = ma_bpf2_get_heap_size(pConfig, &heapSizeInBytes);
  39466. if (result != MA_SUCCESS) {
  39467. return result;
  39468. }
  39469. if (heapSizeInBytes > 0) {
  39470. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39471. if (pHeap == NULL) {
  39472. return MA_OUT_OF_MEMORY;
  39473. }
  39474. } else {
  39475. pHeap = NULL;
  39476. }
  39477. result = ma_bpf2_init_preallocated(pConfig, pHeap, pBPF);
  39478. if (result != MA_SUCCESS) {
  39479. ma_free(pHeap, pAllocationCallbacks);
  39480. return result;
  39481. }
  39482. pBPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39483. return MA_SUCCESS;
  39484. }
  39485. MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39486. {
  39487. if (pBPF == NULL) {
  39488. return;
  39489. }
  39490. ma_biquad_uninit(&pBPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39491. }
  39492. MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF)
  39493. {
  39494. ma_result result;
  39495. ma_biquad_config bqConfig;
  39496. if (pBPF == NULL || pConfig == NULL) {
  39497. return MA_INVALID_ARGS;
  39498. }
  39499. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  39500. result = ma_biquad_reinit(&bqConfig, &pBPF->bq);
  39501. if (result != MA_SUCCESS) {
  39502. return result;
  39503. }
  39504. return MA_SUCCESS;
  39505. }
  39506. static MA_INLINE void ma_bpf2_process_pcm_frame_s16(ma_bpf2* pBPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39507. {
  39508. ma_biquad_process_pcm_frame_s16(&pBPF->bq, pFrameOut, pFrameIn);
  39509. }
  39510. static MA_INLINE void ma_bpf2_process_pcm_frame_f32(ma_bpf2* pBPF, float* pFrameOut, const float* pFrameIn)
  39511. {
  39512. ma_biquad_process_pcm_frame_f32(&pBPF->bq, pFrameOut, pFrameIn);
  39513. }
  39514. MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39515. {
  39516. if (pBPF == NULL) {
  39517. return MA_INVALID_ARGS;
  39518. }
  39519. return ma_biquad_process_pcm_frames(&pBPF->bq, pFramesOut, pFramesIn, frameCount);
  39520. }
  39521. MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF)
  39522. {
  39523. if (pBPF == NULL) {
  39524. return 0;
  39525. }
  39526. return ma_biquad_get_latency(&pBPF->bq);
  39527. }
  39528. MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  39529. {
  39530. ma_bpf_config config;
  39531. MA_ZERO_OBJECT(&config);
  39532. config.format = format;
  39533. config.channels = channels;
  39534. config.sampleRate = sampleRate;
  39535. config.cutoffFrequency = cutoffFrequency;
  39536. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  39537. return config;
  39538. }
  39539. typedef struct
  39540. {
  39541. size_t sizeInBytes;
  39542. size_t bpf2Offset;
  39543. } ma_bpf_heap_layout;
  39544. static ma_result ma_bpf_get_heap_layout(const ma_bpf_config* pConfig, ma_bpf_heap_layout* pHeapLayout)
  39545. {
  39546. ma_result result;
  39547. ma_uint32 bpf2Count;
  39548. ma_uint32 ibpf2;
  39549. MA_ASSERT(pHeapLayout != NULL);
  39550. MA_ZERO_OBJECT(pHeapLayout);
  39551. if (pConfig == NULL) {
  39552. return MA_INVALID_ARGS;
  39553. }
  39554. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39555. return MA_INVALID_ARGS;
  39556. }
  39557. /* We must have an even number of order. */
  39558. if ((pConfig->order & 0x1) != 0) {
  39559. return MA_INVALID_ARGS;
  39560. }
  39561. bpf2Count = pConfig->channels / 2;
  39562. pHeapLayout->sizeInBytes = 0;
  39563. /* BPF 2 */
  39564. pHeapLayout->bpf2Offset = pHeapLayout->sizeInBytes;
  39565. for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
  39566. size_t bpf2HeapSizeInBytes;
  39567. 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. */
  39568. result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes);
  39569. if (result != MA_SUCCESS) {
  39570. return result;
  39571. }
  39572. pHeapLayout->sizeInBytes += sizeof(ma_bpf2) + bpf2HeapSizeInBytes;
  39573. }
  39574. /* Make sure allocation size is aligned. */
  39575. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  39576. return MA_SUCCESS;
  39577. }
  39578. static ma_result ma_bpf_reinit__internal(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF, ma_bool32 isNew)
  39579. {
  39580. ma_result result;
  39581. ma_uint32 bpf2Count;
  39582. ma_uint32 ibpf2;
  39583. ma_bpf_heap_layout heapLayout; /* Only used if isNew is true. */
  39584. if (pBPF == NULL || pConfig == NULL) {
  39585. return MA_INVALID_ARGS;
  39586. }
  39587. /* Only supporting f32 and s16. */
  39588. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  39589. return MA_INVALID_ARGS;
  39590. }
  39591. /* The format cannot be changed after initialization. */
  39592. if (pBPF->format != ma_format_unknown && pBPF->format != pConfig->format) {
  39593. return MA_INVALID_OPERATION;
  39594. }
  39595. /* The channel count cannot be changed after initialization. */
  39596. if (pBPF->channels != 0 && pBPF->channels != pConfig->channels) {
  39597. return MA_INVALID_OPERATION;
  39598. }
  39599. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  39600. return MA_INVALID_ARGS;
  39601. }
  39602. /* We must have an even number of order. */
  39603. if ((pConfig->order & 0x1) != 0) {
  39604. return MA_INVALID_ARGS;
  39605. }
  39606. bpf2Count = pConfig->order / 2;
  39607. /* The filter order can't change between reinits. */
  39608. if (!isNew) {
  39609. if (pBPF->bpf2Count != bpf2Count) {
  39610. return MA_INVALID_OPERATION;
  39611. }
  39612. }
  39613. if (isNew) {
  39614. result = ma_bpf_get_heap_layout(pConfig, &heapLayout);
  39615. if (result != MA_SUCCESS) {
  39616. return result;
  39617. }
  39618. pBPF->_pHeap = pHeap;
  39619. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  39620. pBPF->pBPF2 = (ma_bpf2*)ma_offset_ptr(pHeap, heapLayout.bpf2Offset);
  39621. } else {
  39622. MA_ZERO_OBJECT(&heapLayout);
  39623. }
  39624. for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
  39625. ma_bpf2_config bpf2Config;
  39626. double q;
  39627. /* TODO: Calculate Q to make this a proper Butterworth filter. */
  39628. q = 0.707107;
  39629. bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  39630. if (isNew) {
  39631. size_t bpf2HeapSizeInBytes;
  39632. result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes);
  39633. if (result == MA_SUCCESS) {
  39634. result = ma_bpf2_init_preallocated(&bpf2Config, ma_offset_ptr(pHeap, heapLayout.bpf2Offset + (sizeof(ma_bpf2) * bpf2Count) + (ibpf2 * bpf2HeapSizeInBytes)), &pBPF->pBPF2[ibpf2]);
  39635. }
  39636. } else {
  39637. result = ma_bpf2_reinit(&bpf2Config, &pBPF->pBPF2[ibpf2]);
  39638. }
  39639. if (result != MA_SUCCESS) {
  39640. return result;
  39641. }
  39642. }
  39643. pBPF->bpf2Count = bpf2Count;
  39644. pBPF->format = pConfig->format;
  39645. pBPF->channels = pConfig->channels;
  39646. return MA_SUCCESS;
  39647. }
  39648. MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes)
  39649. {
  39650. ma_result result;
  39651. ma_bpf_heap_layout heapLayout;
  39652. if (pHeapSizeInBytes == NULL) {
  39653. return MA_INVALID_ARGS;
  39654. }
  39655. *pHeapSizeInBytes = 0;
  39656. result = ma_bpf_get_heap_layout(pConfig, &heapLayout);
  39657. if (result != MA_SUCCESS) {
  39658. return result;
  39659. }
  39660. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  39661. return MA_SUCCESS;
  39662. }
  39663. MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF)
  39664. {
  39665. if (pBPF == NULL) {
  39666. return MA_INVALID_ARGS;
  39667. }
  39668. MA_ZERO_OBJECT(pBPF);
  39669. return ma_bpf_reinit__internal(pConfig, pHeap, pBPF, /*isNew*/MA_TRUE);
  39670. }
  39671. MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF)
  39672. {
  39673. ma_result result;
  39674. size_t heapSizeInBytes;
  39675. void* pHeap;
  39676. result = ma_bpf_get_heap_size(pConfig, &heapSizeInBytes);
  39677. if (result != MA_SUCCESS) {
  39678. return result;
  39679. }
  39680. if (heapSizeInBytes > 0) {
  39681. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39682. if (pHeap == NULL) {
  39683. return MA_OUT_OF_MEMORY;
  39684. }
  39685. } else {
  39686. pHeap = NULL;
  39687. }
  39688. result = ma_bpf_init_preallocated(pConfig, pHeap, pBPF);
  39689. if (result != MA_SUCCESS) {
  39690. ma_free(pHeap, pAllocationCallbacks);
  39691. return result;
  39692. }
  39693. pBPF->_ownsHeap = MA_TRUE;
  39694. return MA_SUCCESS;
  39695. }
  39696. MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks)
  39697. {
  39698. ma_uint32 ibpf2;
  39699. if (pBPF == NULL) {
  39700. return;
  39701. }
  39702. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39703. ma_bpf2_uninit(&pBPF->pBPF2[ibpf2], pAllocationCallbacks);
  39704. }
  39705. if (pBPF->_ownsHeap) {
  39706. ma_free(pBPF->_pHeap, pAllocationCallbacks);
  39707. }
  39708. }
  39709. MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF)
  39710. {
  39711. return ma_bpf_reinit__internal(pConfig, NULL, pBPF, /*isNew*/MA_FALSE);
  39712. }
  39713. MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39714. {
  39715. ma_result result;
  39716. ma_uint32 ibpf2;
  39717. if (pBPF == NULL) {
  39718. return MA_INVALID_ARGS;
  39719. }
  39720. /* Faster path for in-place. */
  39721. if (pFramesOut == pFramesIn) {
  39722. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39723. result = ma_bpf2_process_pcm_frames(&pBPF->pBPF2[ibpf2], pFramesOut, pFramesOut, frameCount);
  39724. if (result != MA_SUCCESS) {
  39725. return result;
  39726. }
  39727. }
  39728. }
  39729. /* Slightly slower path for copying. */
  39730. if (pFramesOut != pFramesIn) {
  39731. ma_uint32 iFrame;
  39732. /* */ if (pBPF->format == ma_format_f32) {
  39733. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  39734. const float* pFramesInF32 = (const float*)pFramesIn;
  39735. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39736. MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
  39737. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39738. ma_bpf2_process_pcm_frame_f32(&pBPF->pBPF2[ibpf2], pFramesOutF32, pFramesOutF32);
  39739. }
  39740. pFramesOutF32 += pBPF->channels;
  39741. pFramesInF32 += pBPF->channels;
  39742. }
  39743. } else if (pBPF->format == ma_format_s16) {
  39744. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  39745. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  39746. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39747. MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
  39748. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  39749. ma_bpf2_process_pcm_frame_s16(&pBPF->pBPF2[ibpf2], pFramesOutS16, pFramesOutS16);
  39750. }
  39751. pFramesOutS16 += pBPF->channels;
  39752. pFramesInS16 += pBPF->channels;
  39753. }
  39754. } else {
  39755. MA_ASSERT(MA_FALSE);
  39756. return MA_INVALID_OPERATION; /* Should never hit this. */
  39757. }
  39758. }
  39759. return MA_SUCCESS;
  39760. }
  39761. MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF)
  39762. {
  39763. if (pBPF == NULL) {
  39764. return 0;
  39765. }
  39766. return pBPF->bpf2Count*2;
  39767. }
  39768. /**************************************************************************************************************************************************************
  39769. Notching Filter
  39770. **************************************************************************************************************************************************************/
  39771. MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
  39772. {
  39773. ma_notch2_config config;
  39774. MA_ZERO_OBJECT(&config);
  39775. config.format = format;
  39776. config.channels = channels;
  39777. config.sampleRate = sampleRate;
  39778. config.q = q;
  39779. config.frequency = frequency;
  39780. if (config.q == 0) {
  39781. config.q = 0.707107;
  39782. }
  39783. return config;
  39784. }
  39785. static MA_INLINE ma_biquad_config ma_notch2__get_biquad_config(const ma_notch2_config* pConfig)
  39786. {
  39787. ma_biquad_config bqConfig;
  39788. double q;
  39789. double w;
  39790. double s;
  39791. double c;
  39792. double a;
  39793. MA_ASSERT(pConfig != NULL);
  39794. q = pConfig->q;
  39795. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  39796. s = ma_sind(w);
  39797. c = ma_cosd(w);
  39798. a = s / (2*q);
  39799. bqConfig.b0 = 1;
  39800. bqConfig.b1 = -2 * c;
  39801. bqConfig.b2 = 1;
  39802. bqConfig.a0 = 1 + a;
  39803. bqConfig.a1 = -2 * c;
  39804. bqConfig.a2 = 1 - a;
  39805. bqConfig.format = pConfig->format;
  39806. bqConfig.channels = pConfig->channels;
  39807. return bqConfig;
  39808. }
  39809. MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes)
  39810. {
  39811. ma_biquad_config bqConfig;
  39812. bqConfig = ma_notch2__get_biquad_config(pConfig);
  39813. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39814. }
  39815. MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter)
  39816. {
  39817. ma_result result;
  39818. ma_biquad_config bqConfig;
  39819. if (pFilter == NULL) {
  39820. return MA_INVALID_ARGS;
  39821. }
  39822. MA_ZERO_OBJECT(pFilter);
  39823. if (pConfig == NULL) {
  39824. return MA_INVALID_ARGS;
  39825. }
  39826. bqConfig = ma_notch2__get_biquad_config(pConfig);
  39827. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39828. if (result != MA_SUCCESS) {
  39829. return result;
  39830. }
  39831. return MA_SUCCESS;
  39832. }
  39833. MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter)
  39834. {
  39835. ma_result result;
  39836. size_t heapSizeInBytes;
  39837. void* pHeap;
  39838. result = ma_notch2_get_heap_size(pConfig, &heapSizeInBytes);
  39839. if (result != MA_SUCCESS) {
  39840. return result;
  39841. }
  39842. if (heapSizeInBytes > 0) {
  39843. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39844. if (pHeap == NULL) {
  39845. return MA_OUT_OF_MEMORY;
  39846. }
  39847. } else {
  39848. pHeap = NULL;
  39849. }
  39850. result = ma_notch2_init_preallocated(pConfig, pHeap, pFilter);
  39851. if (result != MA_SUCCESS) {
  39852. ma_free(pHeap, pAllocationCallbacks);
  39853. return result;
  39854. }
  39855. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39856. return MA_SUCCESS;
  39857. }
  39858. MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  39859. {
  39860. if (pFilter == NULL) {
  39861. return;
  39862. }
  39863. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39864. }
  39865. MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter)
  39866. {
  39867. ma_result result;
  39868. ma_biquad_config bqConfig;
  39869. if (pFilter == NULL || pConfig == NULL) {
  39870. return MA_INVALID_ARGS;
  39871. }
  39872. bqConfig = ma_notch2__get_biquad_config(pConfig);
  39873. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  39874. if (result != MA_SUCCESS) {
  39875. return result;
  39876. }
  39877. return MA_SUCCESS;
  39878. }
  39879. static MA_INLINE void ma_notch2_process_pcm_frame_s16(ma_notch2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39880. {
  39881. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  39882. }
  39883. static MA_INLINE void ma_notch2_process_pcm_frame_f32(ma_notch2* pFilter, float* pFrameOut, const float* pFrameIn)
  39884. {
  39885. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  39886. }
  39887. MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39888. {
  39889. if (pFilter == NULL) {
  39890. return MA_INVALID_ARGS;
  39891. }
  39892. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  39893. }
  39894. MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter)
  39895. {
  39896. if (pFilter == NULL) {
  39897. return 0;
  39898. }
  39899. return ma_biquad_get_latency(&pFilter->bq);
  39900. }
  39901. /**************************************************************************************************************************************************************
  39902. Peaking EQ Filter
  39903. **************************************************************************************************************************************************************/
  39904. MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  39905. {
  39906. ma_peak2_config config;
  39907. MA_ZERO_OBJECT(&config);
  39908. config.format = format;
  39909. config.channels = channels;
  39910. config.sampleRate = sampleRate;
  39911. config.gainDB = gainDB;
  39912. config.q = q;
  39913. config.frequency = frequency;
  39914. if (config.q == 0) {
  39915. config.q = 0.707107;
  39916. }
  39917. return config;
  39918. }
  39919. static MA_INLINE ma_biquad_config ma_peak2__get_biquad_config(const ma_peak2_config* pConfig)
  39920. {
  39921. ma_biquad_config bqConfig;
  39922. double q;
  39923. double w;
  39924. double s;
  39925. double c;
  39926. double a;
  39927. double A;
  39928. MA_ASSERT(pConfig != NULL);
  39929. q = pConfig->q;
  39930. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  39931. s = ma_sind(w);
  39932. c = ma_cosd(w);
  39933. a = s / (2*q);
  39934. A = ma_powd(10, (pConfig->gainDB / 40));
  39935. bqConfig.b0 = 1 + (a * A);
  39936. bqConfig.b1 = -2 * c;
  39937. bqConfig.b2 = 1 - (a * A);
  39938. bqConfig.a0 = 1 + (a / A);
  39939. bqConfig.a1 = -2 * c;
  39940. bqConfig.a2 = 1 - (a / A);
  39941. bqConfig.format = pConfig->format;
  39942. bqConfig.channels = pConfig->channels;
  39943. return bqConfig;
  39944. }
  39945. MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes)
  39946. {
  39947. ma_biquad_config bqConfig;
  39948. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39949. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39950. }
  39951. MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter)
  39952. {
  39953. ma_result result;
  39954. ma_biquad_config bqConfig;
  39955. if (pFilter == NULL) {
  39956. return MA_INVALID_ARGS;
  39957. }
  39958. MA_ZERO_OBJECT(pFilter);
  39959. if (pConfig == NULL) {
  39960. return MA_INVALID_ARGS;
  39961. }
  39962. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39963. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39964. if (result != MA_SUCCESS) {
  39965. return result;
  39966. }
  39967. return MA_SUCCESS;
  39968. }
  39969. MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter)
  39970. {
  39971. ma_result result;
  39972. size_t heapSizeInBytes;
  39973. void* pHeap;
  39974. result = ma_peak2_get_heap_size(pConfig, &heapSizeInBytes);
  39975. if (result != MA_SUCCESS) {
  39976. return result;
  39977. }
  39978. if (heapSizeInBytes > 0) {
  39979. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39980. if (pHeap == NULL) {
  39981. return MA_OUT_OF_MEMORY;
  39982. }
  39983. } else {
  39984. pHeap = NULL;
  39985. }
  39986. result = ma_peak2_init_preallocated(pConfig, pHeap, pFilter);
  39987. if (result != MA_SUCCESS) {
  39988. ma_free(pHeap, pAllocationCallbacks);
  39989. return result;
  39990. }
  39991. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39992. return MA_SUCCESS;
  39993. }
  39994. MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  39995. {
  39996. if (pFilter == NULL) {
  39997. return;
  39998. }
  39999. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  40000. }
  40001. MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter)
  40002. {
  40003. ma_result result;
  40004. ma_biquad_config bqConfig;
  40005. if (pFilter == NULL || pConfig == NULL) {
  40006. return MA_INVALID_ARGS;
  40007. }
  40008. bqConfig = ma_peak2__get_biquad_config(pConfig);
  40009. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  40010. if (result != MA_SUCCESS) {
  40011. return result;
  40012. }
  40013. return MA_SUCCESS;
  40014. }
  40015. static MA_INLINE void ma_peak2_process_pcm_frame_s16(ma_peak2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  40016. {
  40017. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  40018. }
  40019. static MA_INLINE void ma_peak2_process_pcm_frame_f32(ma_peak2* pFilter, float* pFrameOut, const float* pFrameIn)
  40020. {
  40021. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  40022. }
  40023. MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40024. {
  40025. if (pFilter == NULL) {
  40026. return MA_INVALID_ARGS;
  40027. }
  40028. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  40029. }
  40030. MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter)
  40031. {
  40032. if (pFilter == NULL) {
  40033. return 0;
  40034. }
  40035. return ma_biquad_get_latency(&pFilter->bq);
  40036. }
  40037. /**************************************************************************************************************************************************************
  40038. Low Shelf Filter
  40039. **************************************************************************************************************************************************************/
  40040. MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
  40041. {
  40042. ma_loshelf2_config config;
  40043. MA_ZERO_OBJECT(&config);
  40044. config.format = format;
  40045. config.channels = channels;
  40046. config.sampleRate = sampleRate;
  40047. config.gainDB = gainDB;
  40048. config.shelfSlope = shelfSlope;
  40049. config.frequency = frequency;
  40050. return config;
  40051. }
  40052. static MA_INLINE ma_biquad_config ma_loshelf2__get_biquad_config(const ma_loshelf2_config* pConfig)
  40053. {
  40054. ma_biquad_config bqConfig;
  40055. double w;
  40056. double s;
  40057. double c;
  40058. double A;
  40059. double S;
  40060. double a;
  40061. double sqrtA;
  40062. MA_ASSERT(pConfig != NULL);
  40063. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  40064. s = ma_sind(w);
  40065. c = ma_cosd(w);
  40066. A = ma_powd(10, (pConfig->gainDB / 40));
  40067. S = pConfig->shelfSlope;
  40068. a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2);
  40069. sqrtA = 2*ma_sqrtd(A)*a;
  40070. bqConfig.b0 = A * ((A + 1) - (A - 1)*c + sqrtA);
  40071. bqConfig.b1 = 2 * A * ((A - 1) - (A + 1)*c);
  40072. bqConfig.b2 = A * ((A + 1) - (A - 1)*c - sqrtA);
  40073. bqConfig.a0 = (A + 1) + (A - 1)*c + sqrtA;
  40074. bqConfig.a1 = -2 * ((A - 1) + (A + 1)*c);
  40075. bqConfig.a2 = (A + 1) + (A - 1)*c - sqrtA;
  40076. bqConfig.format = pConfig->format;
  40077. bqConfig.channels = pConfig->channels;
  40078. return bqConfig;
  40079. }
  40080. MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes)
  40081. {
  40082. ma_biquad_config bqConfig;
  40083. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  40084. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  40085. }
  40086. MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter)
  40087. {
  40088. ma_result result;
  40089. ma_biquad_config bqConfig;
  40090. if (pFilter == NULL) {
  40091. return MA_INVALID_ARGS;
  40092. }
  40093. MA_ZERO_OBJECT(pFilter);
  40094. if (pConfig == NULL) {
  40095. return MA_INVALID_ARGS;
  40096. }
  40097. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  40098. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  40099. if (result != MA_SUCCESS) {
  40100. return result;
  40101. }
  40102. return MA_SUCCESS;
  40103. }
  40104. MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter)
  40105. {
  40106. ma_result result;
  40107. size_t heapSizeInBytes;
  40108. void* pHeap;
  40109. result = ma_loshelf2_get_heap_size(pConfig, &heapSizeInBytes);
  40110. if (result != MA_SUCCESS) {
  40111. return result;
  40112. }
  40113. if (heapSizeInBytes > 0) {
  40114. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40115. if (pHeap == NULL) {
  40116. return MA_OUT_OF_MEMORY;
  40117. }
  40118. } else {
  40119. pHeap = NULL;
  40120. }
  40121. result = ma_loshelf2_init_preallocated(pConfig, pHeap, pFilter);
  40122. if (result != MA_SUCCESS) {
  40123. ma_free(pHeap, pAllocationCallbacks);
  40124. return result;
  40125. }
  40126. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  40127. return MA_SUCCESS;
  40128. }
  40129. MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  40130. {
  40131. if (pFilter == NULL) {
  40132. return;
  40133. }
  40134. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  40135. }
  40136. MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter)
  40137. {
  40138. ma_result result;
  40139. ma_biquad_config bqConfig;
  40140. if (pFilter == NULL || pConfig == NULL) {
  40141. return MA_INVALID_ARGS;
  40142. }
  40143. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  40144. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  40145. if (result != MA_SUCCESS) {
  40146. return result;
  40147. }
  40148. return MA_SUCCESS;
  40149. }
  40150. static MA_INLINE void ma_loshelf2_process_pcm_frame_s16(ma_loshelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  40151. {
  40152. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  40153. }
  40154. static MA_INLINE void ma_loshelf2_process_pcm_frame_f32(ma_loshelf2* pFilter, float* pFrameOut, const float* pFrameIn)
  40155. {
  40156. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  40157. }
  40158. MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40159. {
  40160. if (pFilter == NULL) {
  40161. return MA_INVALID_ARGS;
  40162. }
  40163. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  40164. }
  40165. MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter)
  40166. {
  40167. if (pFilter == NULL) {
  40168. return 0;
  40169. }
  40170. return ma_biquad_get_latency(&pFilter->bq);
  40171. }
  40172. /**************************************************************************************************************************************************************
  40173. High Shelf Filter
  40174. **************************************************************************************************************************************************************/
  40175. MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
  40176. {
  40177. ma_hishelf2_config config;
  40178. MA_ZERO_OBJECT(&config);
  40179. config.format = format;
  40180. config.channels = channels;
  40181. config.sampleRate = sampleRate;
  40182. config.gainDB = gainDB;
  40183. config.shelfSlope = shelfSlope;
  40184. config.frequency = frequency;
  40185. return config;
  40186. }
  40187. static MA_INLINE ma_biquad_config ma_hishelf2__get_biquad_config(const ma_hishelf2_config* pConfig)
  40188. {
  40189. ma_biquad_config bqConfig;
  40190. double w;
  40191. double s;
  40192. double c;
  40193. double A;
  40194. double S;
  40195. double a;
  40196. double sqrtA;
  40197. MA_ASSERT(pConfig != NULL);
  40198. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  40199. s = ma_sind(w);
  40200. c = ma_cosd(w);
  40201. A = ma_powd(10, (pConfig->gainDB / 40));
  40202. S = pConfig->shelfSlope;
  40203. a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2);
  40204. sqrtA = 2*ma_sqrtd(A)*a;
  40205. bqConfig.b0 = A * ((A + 1) + (A - 1)*c + sqrtA);
  40206. bqConfig.b1 = -2 * A * ((A - 1) + (A + 1)*c);
  40207. bqConfig.b2 = A * ((A + 1) + (A - 1)*c - sqrtA);
  40208. bqConfig.a0 = (A + 1) - (A - 1)*c + sqrtA;
  40209. bqConfig.a1 = 2 * ((A - 1) - (A + 1)*c);
  40210. bqConfig.a2 = (A + 1) - (A - 1)*c - sqrtA;
  40211. bqConfig.format = pConfig->format;
  40212. bqConfig.channels = pConfig->channels;
  40213. return bqConfig;
  40214. }
  40215. MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes)
  40216. {
  40217. ma_biquad_config bqConfig;
  40218. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  40219. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  40220. }
  40221. MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter)
  40222. {
  40223. ma_result result;
  40224. ma_biquad_config bqConfig;
  40225. if (pFilter == NULL) {
  40226. return MA_INVALID_ARGS;
  40227. }
  40228. MA_ZERO_OBJECT(pFilter);
  40229. if (pConfig == NULL) {
  40230. return MA_INVALID_ARGS;
  40231. }
  40232. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  40233. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  40234. if (result != MA_SUCCESS) {
  40235. return result;
  40236. }
  40237. return MA_SUCCESS;
  40238. }
  40239. MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter)
  40240. {
  40241. ma_result result;
  40242. size_t heapSizeInBytes;
  40243. void* pHeap;
  40244. result = ma_hishelf2_get_heap_size(pConfig, &heapSizeInBytes);
  40245. if (result != MA_SUCCESS) {
  40246. return result;
  40247. }
  40248. if (heapSizeInBytes > 0) {
  40249. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40250. if (pHeap == NULL) {
  40251. return MA_OUT_OF_MEMORY;
  40252. }
  40253. } else {
  40254. pHeap = NULL;
  40255. }
  40256. result = ma_hishelf2_init_preallocated(pConfig, pHeap, pFilter);
  40257. if (result != MA_SUCCESS) {
  40258. ma_free(pHeap, pAllocationCallbacks);
  40259. return result;
  40260. }
  40261. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  40262. return MA_SUCCESS;
  40263. }
  40264. MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  40265. {
  40266. if (pFilter == NULL) {
  40267. return;
  40268. }
  40269. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  40270. }
  40271. MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter)
  40272. {
  40273. ma_result result;
  40274. ma_biquad_config bqConfig;
  40275. if (pFilter == NULL || pConfig == NULL) {
  40276. return MA_INVALID_ARGS;
  40277. }
  40278. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  40279. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  40280. if (result != MA_SUCCESS) {
  40281. return result;
  40282. }
  40283. return MA_SUCCESS;
  40284. }
  40285. static MA_INLINE void ma_hishelf2_process_pcm_frame_s16(ma_hishelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  40286. {
  40287. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  40288. }
  40289. static MA_INLINE void ma_hishelf2_process_pcm_frame_f32(ma_hishelf2* pFilter, float* pFrameOut, const float* pFrameIn)
  40290. {
  40291. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  40292. }
  40293. MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40294. {
  40295. if (pFilter == NULL) {
  40296. return MA_INVALID_ARGS;
  40297. }
  40298. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  40299. }
  40300. MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter)
  40301. {
  40302. if (pFilter == NULL) {
  40303. return 0;
  40304. }
  40305. return ma_biquad_get_latency(&pFilter->bq);
  40306. }
  40307. /*
  40308. Delay
  40309. */
  40310. MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay)
  40311. {
  40312. ma_delay_config config;
  40313. MA_ZERO_OBJECT(&config);
  40314. config.channels = channels;
  40315. config.sampleRate = sampleRate;
  40316. config.delayInFrames = delayInFrames;
  40317. config.delayStart = (decay == 0) ? MA_TRUE : MA_FALSE; /* Delay the start if it looks like we're not configuring an echo. */
  40318. config.wet = 1;
  40319. config.dry = 1;
  40320. config.decay = decay;
  40321. return config;
  40322. }
  40323. MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay)
  40324. {
  40325. if (pDelay == NULL) {
  40326. return MA_INVALID_ARGS;
  40327. }
  40328. MA_ZERO_OBJECT(pDelay);
  40329. if (pConfig == NULL) {
  40330. return MA_INVALID_ARGS;
  40331. }
  40332. if (pConfig->decay < 0 || pConfig->decay > 1) {
  40333. return MA_INVALID_ARGS;
  40334. }
  40335. pDelay->config = *pConfig;
  40336. pDelay->bufferSizeInFrames = pConfig->delayInFrames;
  40337. pDelay->cursor = 0;
  40338. pDelay->pBuffer = (float*)ma_malloc((size_t)(pDelay->bufferSizeInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->channels)), pAllocationCallbacks);
  40339. if (pDelay->pBuffer == NULL) {
  40340. return MA_OUT_OF_MEMORY;
  40341. }
  40342. ma_silence_pcm_frames(pDelay->pBuffer, pDelay->bufferSizeInFrames, ma_format_f32, pConfig->channels);
  40343. return MA_SUCCESS;
  40344. }
  40345. MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks)
  40346. {
  40347. if (pDelay == NULL) {
  40348. return;
  40349. }
  40350. ma_free(pDelay->pBuffer, pAllocationCallbacks);
  40351. }
  40352. MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  40353. {
  40354. ma_uint32 iFrame;
  40355. ma_uint32 iChannel;
  40356. float* pFramesOutF32 = (float*)pFramesOut;
  40357. const float* pFramesInF32 = (const float*)pFramesIn;
  40358. if (pDelay == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  40359. return MA_INVALID_ARGS;
  40360. }
  40361. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40362. for (iChannel = 0; iChannel < pDelay->config.channels; iChannel += 1) {
  40363. ma_uint32 iBuffer = (pDelay->cursor * pDelay->config.channels) + iChannel;
  40364. if (pDelay->config.delayStart) {
  40365. /* Delayed start. */
  40366. /* Read */
  40367. pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet;
  40368. /* Feedback */
  40369. pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry);
  40370. } else {
  40371. /* Immediate start */
  40372. /* Feedback */
  40373. pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry);
  40374. /* Read */
  40375. pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet;
  40376. }
  40377. }
  40378. pDelay->cursor = (pDelay->cursor + 1) % pDelay->bufferSizeInFrames;
  40379. pFramesOutF32 += pDelay->config.channels;
  40380. pFramesInF32 += pDelay->config.channels;
  40381. }
  40382. return MA_SUCCESS;
  40383. }
  40384. MA_API void ma_delay_set_wet(ma_delay* pDelay, float value)
  40385. {
  40386. if (pDelay == NULL) {
  40387. return;
  40388. }
  40389. pDelay->config.wet = value;
  40390. }
  40391. MA_API float ma_delay_get_wet(const ma_delay* pDelay)
  40392. {
  40393. if (pDelay == NULL) {
  40394. return 0;
  40395. }
  40396. return pDelay->config.wet;
  40397. }
  40398. MA_API void ma_delay_set_dry(ma_delay* pDelay, float value)
  40399. {
  40400. if (pDelay == NULL) {
  40401. return;
  40402. }
  40403. pDelay->config.dry = value;
  40404. }
  40405. MA_API float ma_delay_get_dry(const ma_delay* pDelay)
  40406. {
  40407. if (pDelay == NULL) {
  40408. return 0;
  40409. }
  40410. return pDelay->config.dry;
  40411. }
  40412. MA_API void ma_delay_set_decay(ma_delay* pDelay, float value)
  40413. {
  40414. if (pDelay == NULL) {
  40415. return;
  40416. }
  40417. pDelay->config.decay = value;
  40418. }
  40419. MA_API float ma_delay_get_decay(const ma_delay* pDelay)
  40420. {
  40421. if (pDelay == NULL) {
  40422. return 0;
  40423. }
  40424. return pDelay->config.decay;
  40425. }
  40426. MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames)
  40427. {
  40428. ma_gainer_config config;
  40429. MA_ZERO_OBJECT(&config);
  40430. config.channels = channels;
  40431. config.smoothTimeInFrames = smoothTimeInFrames;
  40432. return config;
  40433. }
  40434. typedef struct
  40435. {
  40436. size_t sizeInBytes;
  40437. size_t oldGainsOffset;
  40438. size_t newGainsOffset;
  40439. } ma_gainer_heap_layout;
  40440. static ma_result ma_gainer_get_heap_layout(const ma_gainer_config* pConfig, ma_gainer_heap_layout* pHeapLayout)
  40441. {
  40442. MA_ASSERT(pHeapLayout != NULL);
  40443. MA_ZERO_OBJECT(pHeapLayout);
  40444. if (pConfig == NULL) {
  40445. return MA_INVALID_ARGS;
  40446. }
  40447. if (pConfig->channels == 0) {
  40448. return MA_INVALID_ARGS;
  40449. }
  40450. pHeapLayout->sizeInBytes = 0;
  40451. /* Old gains. */
  40452. pHeapLayout->oldGainsOffset = pHeapLayout->sizeInBytes;
  40453. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  40454. /* New gains. */
  40455. pHeapLayout->newGainsOffset = pHeapLayout->sizeInBytes;
  40456. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  40457. /* Alignment. */
  40458. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  40459. return MA_SUCCESS;
  40460. }
  40461. MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes)
  40462. {
  40463. ma_result result;
  40464. ma_gainer_heap_layout heapLayout;
  40465. if (pHeapSizeInBytes == NULL) {
  40466. return MA_INVALID_ARGS;
  40467. }
  40468. *pHeapSizeInBytes = 0;
  40469. result = ma_gainer_get_heap_layout(pConfig, &heapLayout);
  40470. if (result != MA_SUCCESS) {
  40471. return MA_INVALID_ARGS;
  40472. }
  40473. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  40474. return MA_SUCCESS;
  40475. }
  40476. MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer)
  40477. {
  40478. ma_result result;
  40479. ma_gainer_heap_layout heapLayout;
  40480. ma_uint32 iChannel;
  40481. if (pGainer == NULL) {
  40482. return MA_INVALID_ARGS;
  40483. }
  40484. MA_ZERO_OBJECT(pGainer);
  40485. if (pConfig == NULL || pHeap == NULL) {
  40486. return MA_INVALID_ARGS;
  40487. }
  40488. result = ma_gainer_get_heap_layout(pConfig, &heapLayout);
  40489. if (result != MA_SUCCESS) {
  40490. return result;
  40491. }
  40492. pGainer->_pHeap = pHeap;
  40493. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  40494. pGainer->pOldGains = (float*)ma_offset_ptr(pHeap, heapLayout.oldGainsOffset);
  40495. pGainer->pNewGains = (float*)ma_offset_ptr(pHeap, heapLayout.newGainsOffset);
  40496. pGainer->masterVolume = 1;
  40497. pGainer->config = *pConfig;
  40498. pGainer->t = (ma_uint32)-1; /* No interpolation by default. */
  40499. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  40500. pGainer->pOldGains[iChannel] = 1;
  40501. pGainer->pNewGains[iChannel] = 1;
  40502. }
  40503. return MA_SUCCESS;
  40504. }
  40505. MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer)
  40506. {
  40507. ma_result result;
  40508. size_t heapSizeInBytes;
  40509. void* pHeap;
  40510. result = ma_gainer_get_heap_size(pConfig, &heapSizeInBytes);
  40511. if (result != MA_SUCCESS) {
  40512. return result; /* Failed to retrieve the size of the heap allocation. */
  40513. }
  40514. if (heapSizeInBytes > 0) {
  40515. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40516. if (pHeap == NULL) {
  40517. return MA_OUT_OF_MEMORY;
  40518. }
  40519. } else {
  40520. pHeap = NULL;
  40521. }
  40522. result = ma_gainer_init_preallocated(pConfig, pHeap, pGainer);
  40523. if (result != MA_SUCCESS) {
  40524. ma_free(pHeap, pAllocationCallbacks);
  40525. return result;
  40526. }
  40527. pGainer->_ownsHeap = MA_TRUE;
  40528. return MA_SUCCESS;
  40529. }
  40530. MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks)
  40531. {
  40532. if (pGainer == NULL) {
  40533. return;
  40534. }
  40535. if (pGainer->_ownsHeap) {
  40536. ma_free(pGainer->_pHeap, pAllocationCallbacks);
  40537. }
  40538. }
  40539. static float ma_gainer_calculate_current_gain(const ma_gainer* pGainer, ma_uint32 channel)
  40540. {
  40541. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  40542. return ma_mix_f32_fast(pGainer->pOldGains[channel], pGainer->pNewGains[channel], a);
  40543. }
  40544. 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)
  40545. {
  40546. ma_uint64 iFrame;
  40547. ma_uint32 iChannel;
  40548. ma_uint64 interpolatedFrameCount;
  40549. MA_ASSERT(pGainer != NULL);
  40550. /*
  40551. We don't necessarily need to apply a linear interpolation for the entire frameCount frames. When
  40552. linear interpolation is not needed we can do a simple volume adjustment which will be more
  40553. efficient than a lerp with an alpha value of 1.
  40554. To do this, all we need to do is determine how many frames need to have a lerp applied. Then we
  40555. just process that number of frames with linear interpolation. After that we run on an optimized
  40556. path which just applies the new gains without a lerp.
  40557. */
  40558. if (pGainer->t >= pGainer->config.smoothTimeInFrames) {
  40559. interpolatedFrameCount = 0;
  40560. } else {
  40561. interpolatedFrameCount = pGainer->t - pGainer->config.smoothTimeInFrames;
  40562. if (interpolatedFrameCount > frameCount) {
  40563. interpolatedFrameCount = frameCount;
  40564. }
  40565. }
  40566. /*
  40567. Start off with our interpolated frames. When we do this, we'll adjust frameCount and our pointers
  40568. so that the fast path can work naturally without consideration of the interpolated path.
  40569. */
  40570. if (interpolatedFrameCount > 0) {
  40571. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  40572. if (pFramesOut != NULL && pFramesIn != NULL) {
  40573. /*
  40574. All we're really doing here is moving the old gains towards the new gains. We don't want to
  40575. be modifying the gains inside the ma_gainer object because that will break things. Instead
  40576. we can make a copy here on the stack. For extreme channel counts we can fall back to a slower
  40577. implementation which just uses a standard lerp.
  40578. */
  40579. float* pFramesOutF32 = (float*)pFramesOut;
  40580. const float* pFramesInF32 = (const float*)pFramesIn;
  40581. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  40582. float d = 1.0f / pGainer->config.smoothTimeInFrames;
  40583. if (pGainer->config.channels <= 32) {
  40584. float pRunningGain[32];
  40585. float pRunningGainDelta[32]; /* Could this be heap-allocated as part of the ma_gainer object? */
  40586. /* Initialize the running gain. */
  40587. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40588. float t = (pGainer->pNewGains[iChannel] - pGainer->pOldGains[iChannel]) * pGainer->masterVolume;
  40589. pRunningGainDelta[iChannel] = t * d;
  40590. pRunningGain[iChannel] = (pGainer->pOldGains[iChannel] * pGainer->masterVolume) + (t * a);
  40591. }
  40592. iFrame = 0;
  40593. /* Optimized paths for common channel counts. This is mostly just experimenting with some SIMD ideas. It's not necessarily final. */
  40594. if (pGainer->config.channels == 2) {
  40595. #if defined(MA_SUPPORT_SSE2)
  40596. if (ma_has_sse2()) {
  40597. ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1;
  40598. /* Expand some arrays so we can have a clean SIMD loop below. */
  40599. __m128 runningGainDelta0 = _mm_set_ps(pRunningGainDelta[1], pRunningGainDelta[0], pRunningGainDelta[1], pRunningGainDelta[0]);
  40600. __m128 runningGain0 = _mm_set_ps(pRunningGain[1] + pRunningGainDelta[1], pRunningGain[0] + pRunningGainDelta[0], pRunningGain[1], pRunningGain[0]);
  40601. for (; iFrame < unrolledLoopCount; iFrame += 1) {
  40602. _mm_storeu_ps(&pFramesOutF32[iFrame*4 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*4 + 0]), runningGain0));
  40603. runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0);
  40604. }
  40605. iFrame = unrolledLoopCount << 1;
  40606. } else
  40607. #endif
  40608. {
  40609. /*
  40610. Two different scalar implementations here. Clang (and I assume GCC) will vectorize
  40611. both of these, but the bottom version results in a nicer vectorization with less
  40612. instructions emitted. The problem, however, is that the bottom version runs slower
  40613. when compiled with MSVC. The top version will be partially vectorized by MSVC.
  40614. */
  40615. #if defined(_MSC_VER) && !defined(__clang__)
  40616. ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1;
  40617. /* Expand some arrays so we can have a clean 4x SIMD operation in the loop. */
  40618. pRunningGainDelta[2] = pRunningGainDelta[0];
  40619. pRunningGainDelta[3] = pRunningGainDelta[1];
  40620. pRunningGain[2] = pRunningGain[0] + pRunningGainDelta[0];
  40621. pRunningGain[3] = pRunningGain[1] + pRunningGainDelta[1];
  40622. for (; iFrame < unrolledLoopCount; iFrame += 1) {
  40623. pFramesOutF32[iFrame*4 + 0] = pFramesInF32[iFrame*4 + 0] * pRunningGain[0];
  40624. pFramesOutF32[iFrame*4 + 1] = pFramesInF32[iFrame*4 + 1] * pRunningGain[1];
  40625. pFramesOutF32[iFrame*4 + 2] = pFramesInF32[iFrame*4 + 2] * pRunningGain[2];
  40626. pFramesOutF32[iFrame*4 + 3] = pFramesInF32[iFrame*4 + 3] * pRunningGain[3];
  40627. /* Move the running gain forward towards the new gain. */
  40628. pRunningGain[0] += pRunningGainDelta[0];
  40629. pRunningGain[1] += pRunningGainDelta[1];
  40630. pRunningGain[2] += pRunningGainDelta[2];
  40631. pRunningGain[3] += pRunningGainDelta[3];
  40632. }
  40633. iFrame = unrolledLoopCount << 1;
  40634. #else
  40635. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40636. for (iChannel = 0; iChannel < 2; iChannel += 1) {
  40637. pFramesOutF32[iFrame*2 + iChannel] = pFramesInF32[iFrame*2 + iChannel] * pRunningGain[iChannel];
  40638. }
  40639. for (iChannel = 0; iChannel < 2; iChannel += 1) {
  40640. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40641. }
  40642. }
  40643. #endif
  40644. }
  40645. } else if (pGainer->config.channels == 6) {
  40646. #if defined(MA_SUPPORT_SSE2)
  40647. if (ma_has_sse2()) {
  40648. /*
  40649. For 6 channels things are a bit more complicated because 6 isn't cleanly divisible by 4. We need to do 2 frames
  40650. at a time, meaning we'll be doing 12 samples in a group. Like the stereo case we'll need to expand some arrays
  40651. so we can do clean 4x SIMD operations.
  40652. */
  40653. ma_uint64 unrolledLoopCount = interpolatedFrameCount >> 1;
  40654. /* Expand some arrays so we can have a clean SIMD loop below. */
  40655. __m128 runningGainDelta0 = _mm_set_ps(pRunningGainDelta[3], pRunningGainDelta[2], pRunningGainDelta[1], pRunningGainDelta[0]);
  40656. __m128 runningGainDelta1 = _mm_set_ps(pRunningGainDelta[1], pRunningGainDelta[0], pRunningGainDelta[5], pRunningGainDelta[4]);
  40657. __m128 runningGainDelta2 = _mm_set_ps(pRunningGainDelta[5], pRunningGainDelta[4], pRunningGainDelta[3], pRunningGainDelta[2]);
  40658. __m128 runningGain0 = _mm_set_ps(pRunningGain[3], pRunningGain[2], pRunningGain[1], pRunningGain[0]);
  40659. __m128 runningGain1 = _mm_set_ps(pRunningGain[1] + pRunningGainDelta[1], pRunningGain[0] + pRunningGainDelta[0], pRunningGain[5], pRunningGain[4]);
  40660. __m128 runningGain2 = _mm_set_ps(pRunningGain[5] + pRunningGainDelta[5], pRunningGain[4] + pRunningGainDelta[4], pRunningGain[3] + pRunningGainDelta[3], pRunningGain[2] + pRunningGainDelta[2]);
  40661. for (; iFrame < unrolledLoopCount; iFrame += 1) {
  40662. _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 0]), runningGain0));
  40663. _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 4], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 4]), runningGain1));
  40664. _mm_storeu_ps(&pFramesOutF32[iFrame*12 + 8], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*12 + 8]), runningGain2));
  40665. runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0);
  40666. runningGain1 = _mm_add_ps(runningGain1, runningGainDelta1);
  40667. runningGain2 = _mm_add_ps(runningGain2, runningGainDelta2);
  40668. }
  40669. iFrame = unrolledLoopCount << 1;
  40670. } else
  40671. #endif
  40672. {
  40673. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40674. for (iChannel = 0; iChannel < 6; iChannel += 1) {
  40675. pFramesOutF32[iFrame*6 + iChannel] = pFramesInF32[iFrame*6 + iChannel] * pRunningGain[iChannel];
  40676. }
  40677. /* Move the running gain forward towards the new gain. */
  40678. for (iChannel = 0; iChannel < 6; iChannel += 1) {
  40679. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40680. }
  40681. }
  40682. }
  40683. } else if (pGainer->config.channels == 8) {
  40684. /* For 8 channels we can just go over frame by frame and do all eight channels as 2 separate 4x SIMD operations. */
  40685. #if defined(MA_SUPPORT_SSE2)
  40686. if (ma_has_sse2()) {
  40687. __m128 runningGainDelta0 = _mm_loadu_ps(&pRunningGainDelta[0]);
  40688. __m128 runningGainDelta1 = _mm_loadu_ps(&pRunningGainDelta[4]);
  40689. __m128 runningGain0 = _mm_loadu_ps(&pRunningGain[0]);
  40690. __m128 runningGain1 = _mm_loadu_ps(&pRunningGain[4]);
  40691. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40692. _mm_storeu_ps(&pFramesOutF32[iFrame*8 + 0], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*8 + 0]), runningGain0));
  40693. _mm_storeu_ps(&pFramesOutF32[iFrame*8 + 4], _mm_mul_ps(_mm_loadu_ps(&pFramesInF32[iFrame*8 + 4]), runningGain1));
  40694. runningGain0 = _mm_add_ps(runningGain0, runningGainDelta0);
  40695. runningGain1 = _mm_add_ps(runningGain1, runningGainDelta1);
  40696. }
  40697. } else
  40698. #endif
  40699. {
  40700. /* This is crafted so that it auto-vectorizes when compiled with Clang. */
  40701. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40702. for (iChannel = 0; iChannel < 8; iChannel += 1) {
  40703. pFramesOutF32[iFrame*8 + iChannel] = pFramesInF32[iFrame*8 + iChannel] * pRunningGain[iChannel];
  40704. }
  40705. /* Move the running gain forward towards the new gain. */
  40706. for (iChannel = 0; iChannel < 8; iChannel += 1) {
  40707. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40708. }
  40709. }
  40710. }
  40711. }
  40712. for (; iFrame < interpolatedFrameCount; iFrame += 1) {
  40713. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40714. pFramesOutF32[iFrame*pGainer->config.channels + iChannel] = pFramesInF32[iFrame*pGainer->config.channels + iChannel] * pRunningGain[iChannel];
  40715. pRunningGain[iChannel] += pRunningGainDelta[iChannel];
  40716. }
  40717. }
  40718. } else {
  40719. /* 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. */
  40720. for (iFrame = 0; iFrame < interpolatedFrameCount; iFrame += 1) {
  40721. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40722. 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;
  40723. }
  40724. a += d;
  40725. }
  40726. }
  40727. }
  40728. /* Make sure the timer is updated. */
  40729. pGainer->t = (ma_uint32)ma_min(pGainer->t + interpolatedFrameCount, pGainer->config.smoothTimeInFrames);
  40730. /* Adjust our arguments so the next part can work normally. */
  40731. frameCount -= interpolatedFrameCount;
  40732. pFramesOut = ma_offset_ptr(pFramesOut, interpolatedFrameCount * sizeof(float));
  40733. pFramesIn = ma_offset_ptr(pFramesIn, interpolatedFrameCount * sizeof(float));
  40734. }
  40735. /* All we need to do here is apply the new gains using an optimized path. */
  40736. if (pFramesOut != NULL && pFramesIn != NULL) {
  40737. if (pGainer->config.channels <= 32) {
  40738. float gains[32];
  40739. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40740. gains[iChannel] = pGainer->pNewGains[iChannel] * pGainer->masterVolume;
  40741. }
  40742. ma_copy_and_apply_volume_factor_per_channel_f32((float*)pFramesOut, (const float*)pFramesIn, frameCount, pGainer->config.channels, gains);
  40743. } else {
  40744. /* Slow path. Too many channels to fit on the stack. Need to apply a master volume as a separate path. */
  40745. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40746. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40747. ((float*)pFramesOut)[iFrame*pGainer->config.channels + iChannel] = ((const float*)pFramesIn)[iFrame*pGainer->config.channels + iChannel] * pGainer->pNewGains[iChannel] * pGainer->masterVolume;
  40748. }
  40749. }
  40750. }
  40751. }
  40752. /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */
  40753. if (pGainer->t == (ma_uint32)-1) {
  40754. pGainer->t = (ma_uint32)ma_min(pGainer->config.smoothTimeInFrames, frameCount);
  40755. }
  40756. #if 0
  40757. if (pGainer->t >= pGainer->config.smoothTimeInFrames) {
  40758. /* Fast path. No gain calculation required. */
  40759. ma_copy_and_apply_volume_factor_per_channel_f32(pFramesOutF32, pFramesInF32, frameCount, pGainer->config.channels, pGainer->pNewGains);
  40760. ma_apply_volume_factor_f32(pFramesOutF32, frameCount * pGainer->config.channels, pGainer->masterVolume);
  40761. /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */
  40762. if (pGainer->t == (ma_uint32)-1) {
  40763. pGainer->t = pGainer->config.smoothTimeInFrames;
  40764. }
  40765. } else {
  40766. /* Slow path. Need to interpolate the gain for each channel individually. */
  40767. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  40768. if (pFramesOut != NULL && pFramesIn != NULL) {
  40769. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  40770. float d = 1.0f / pGainer->config.smoothTimeInFrames;
  40771. ma_uint32 channelCount = pGainer->config.channels;
  40772. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40773. for (iChannel = 0; iChannel < channelCount; iChannel += 1) {
  40774. pFramesOutF32[iChannel] = pFramesInF32[iChannel] * ma_mix_f32_fast(pGainer->pOldGains[iChannel], pGainer->pNewGains[iChannel], a) * pGainer->masterVolume;
  40775. }
  40776. pFramesOutF32 += channelCount;
  40777. pFramesInF32 += channelCount;
  40778. a += d;
  40779. if (a > 1) {
  40780. a = 1;
  40781. }
  40782. }
  40783. }
  40784. pGainer->t = (ma_uint32)ma_min(pGainer->t + frameCount, pGainer->config.smoothTimeInFrames);
  40785. #if 0 /* Reference implementation. */
  40786. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40787. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  40788. if (pFramesOut != NULL && pFramesIn != NULL) {
  40789. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40790. pFramesOutF32[iFrame * pGainer->config.channels + iChannel] = pFramesInF32[iFrame * pGainer->config.channels + iChannel] * ma_gainer_calculate_current_gain(pGainer, iChannel) * pGainer->masterVolume;
  40791. }
  40792. }
  40793. /* Move interpolation time forward, but don't go beyond our smoothing time. */
  40794. pGainer->t = ma_min(pGainer->t + 1, pGainer->config.smoothTimeInFrames);
  40795. }
  40796. #endif
  40797. }
  40798. #endif
  40799. return MA_SUCCESS;
  40800. }
  40801. MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40802. {
  40803. if (pGainer == NULL) {
  40804. return MA_INVALID_ARGS;
  40805. }
  40806. /*
  40807. ma_gainer_process_pcm_frames_internal() marks pFramesOut and pFramesIn with MA_RESTRICT which
  40808. helps with auto-vectorization.
  40809. */
  40810. return ma_gainer_process_pcm_frames_internal(pGainer, pFramesOut, pFramesIn, frameCount);
  40811. }
  40812. static void ma_gainer_set_gain_by_index(ma_gainer* pGainer, float newGain, ma_uint32 iChannel)
  40813. {
  40814. pGainer->pOldGains[iChannel] = ma_gainer_calculate_current_gain(pGainer, iChannel);
  40815. pGainer->pNewGains[iChannel] = newGain;
  40816. }
  40817. static void ma_gainer_reset_smoothing_time(ma_gainer* pGainer)
  40818. {
  40819. if (pGainer->t == (ma_uint32)-1) {
  40820. pGainer->t = pGainer->config.smoothTimeInFrames; /* No smoothing required for initial gains setting. */
  40821. } else {
  40822. pGainer->t = 0;
  40823. }
  40824. }
  40825. MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain)
  40826. {
  40827. ma_uint32 iChannel;
  40828. if (pGainer == NULL) {
  40829. return MA_INVALID_ARGS;
  40830. }
  40831. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40832. ma_gainer_set_gain_by_index(pGainer, newGain, iChannel);
  40833. }
  40834. /* 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. */
  40835. ma_gainer_reset_smoothing_time(pGainer);
  40836. return MA_SUCCESS;
  40837. }
  40838. MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains)
  40839. {
  40840. ma_uint32 iChannel;
  40841. if (pGainer == NULL || pNewGains == NULL) {
  40842. return MA_INVALID_ARGS;
  40843. }
  40844. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  40845. ma_gainer_set_gain_by_index(pGainer, pNewGains[iChannel], iChannel);
  40846. }
  40847. /* 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. */
  40848. ma_gainer_reset_smoothing_time(pGainer);
  40849. return MA_SUCCESS;
  40850. }
  40851. MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume)
  40852. {
  40853. if (pGainer == NULL) {
  40854. return MA_INVALID_ARGS;
  40855. }
  40856. pGainer->masterVolume = volume;
  40857. return MA_SUCCESS;
  40858. }
  40859. MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume)
  40860. {
  40861. if (pGainer == NULL || pVolume == NULL) {
  40862. return MA_INVALID_ARGS;
  40863. }
  40864. *pVolume = pGainer->masterVolume;
  40865. return MA_SUCCESS;
  40866. }
  40867. MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels)
  40868. {
  40869. ma_panner_config config;
  40870. MA_ZERO_OBJECT(&config);
  40871. config.format = format;
  40872. config.channels = channels;
  40873. 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. */
  40874. config.pan = 0;
  40875. return config;
  40876. }
  40877. MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner)
  40878. {
  40879. if (pPanner == NULL) {
  40880. return MA_INVALID_ARGS;
  40881. }
  40882. MA_ZERO_OBJECT(pPanner);
  40883. if (pConfig == NULL) {
  40884. return MA_INVALID_ARGS;
  40885. }
  40886. pPanner->format = pConfig->format;
  40887. pPanner->channels = pConfig->channels;
  40888. pPanner->mode = pConfig->mode;
  40889. pPanner->pan = pConfig->pan;
  40890. return MA_SUCCESS;
  40891. }
  40892. static void ma_stereo_balance_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan)
  40893. {
  40894. ma_uint64 iFrame;
  40895. if (pan > 0) {
  40896. float factor = 1.0f - pan;
  40897. if (pFramesOut == pFramesIn) {
  40898. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40899. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor;
  40900. }
  40901. } else {
  40902. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40903. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor;
  40904. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1];
  40905. }
  40906. }
  40907. } else {
  40908. float factor = 1.0f + pan;
  40909. if (pFramesOut == pFramesIn) {
  40910. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40911. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor;
  40912. }
  40913. } else {
  40914. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40915. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0];
  40916. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor;
  40917. }
  40918. }
  40919. }
  40920. }
  40921. static void ma_stereo_balance_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan)
  40922. {
  40923. if (pan == 0) {
  40924. /* Fast path. No panning required. */
  40925. if (pFramesOut == pFramesIn) {
  40926. /* No-op */
  40927. } else {
  40928. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40929. }
  40930. return;
  40931. }
  40932. switch (format) {
  40933. case ma_format_f32: ma_stereo_balance_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break;
  40934. /* Unknown format. Just copy. */
  40935. default:
  40936. {
  40937. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40938. } break;
  40939. }
  40940. }
  40941. static void ma_stereo_pan_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan)
  40942. {
  40943. ma_uint64 iFrame;
  40944. if (pan > 0) {
  40945. float factorL0 = 1.0f - pan;
  40946. float factorL1 = 0.0f + pan;
  40947. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40948. float sample0 = (pFramesIn[iFrame*2 + 0] * factorL0);
  40949. float sample1 = (pFramesIn[iFrame*2 + 0] * factorL1) + pFramesIn[iFrame*2 + 1];
  40950. pFramesOut[iFrame*2 + 0] = sample0;
  40951. pFramesOut[iFrame*2 + 1] = sample1;
  40952. }
  40953. } else {
  40954. float factorR0 = 0.0f - pan;
  40955. float factorR1 = 1.0f + pan;
  40956. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  40957. float sample0 = pFramesIn[iFrame*2 + 0] + (pFramesIn[iFrame*2 + 1] * factorR0);
  40958. float sample1 = (pFramesIn[iFrame*2 + 1] * factorR1);
  40959. pFramesOut[iFrame*2 + 0] = sample0;
  40960. pFramesOut[iFrame*2 + 1] = sample1;
  40961. }
  40962. }
  40963. }
  40964. static void ma_stereo_pan_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan)
  40965. {
  40966. if (pan == 0) {
  40967. /* Fast path. No panning required. */
  40968. if (pFramesOut == pFramesIn) {
  40969. /* No-op */
  40970. } else {
  40971. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40972. }
  40973. return;
  40974. }
  40975. switch (format) {
  40976. case ma_format_f32: ma_stereo_pan_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break;
  40977. /* Unknown format. Just copy. */
  40978. default:
  40979. {
  40980. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  40981. } break;
  40982. }
  40983. }
  40984. MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40985. {
  40986. if (pPanner == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  40987. return MA_INVALID_ARGS;
  40988. }
  40989. if (pPanner->channels == 2) {
  40990. /* Stereo case. For now assume channel 0 is left and channel right is 1, but should probably add support for a channel map. */
  40991. if (pPanner->mode == ma_pan_mode_balance) {
  40992. ma_stereo_balance_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan);
  40993. } else {
  40994. ma_stereo_pan_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan);
  40995. }
  40996. } else {
  40997. if (pPanner->channels == 1) {
  40998. /* Panning has no effect on mono streams. */
  40999. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels);
  41000. } else {
  41001. /* For now we're not going to support non-stereo set ups. Not sure how I want to handle this case just yet. */
  41002. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels);
  41003. }
  41004. }
  41005. return MA_SUCCESS;
  41006. }
  41007. MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode)
  41008. {
  41009. if (pPanner == NULL) {
  41010. return;
  41011. }
  41012. pPanner->mode = mode;
  41013. }
  41014. MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner)
  41015. {
  41016. if (pPanner == NULL) {
  41017. return ma_pan_mode_balance;
  41018. }
  41019. return pPanner->mode;
  41020. }
  41021. MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan)
  41022. {
  41023. if (pPanner == NULL) {
  41024. return;
  41025. }
  41026. pPanner->pan = ma_clamp(pan, -1.0f, 1.0f);
  41027. }
  41028. MA_API float ma_panner_get_pan(const ma_panner* pPanner)
  41029. {
  41030. if (pPanner == NULL) {
  41031. return 0;
  41032. }
  41033. return pPanner->pan;
  41034. }
  41035. MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  41036. {
  41037. ma_fader_config config;
  41038. MA_ZERO_OBJECT(&config);
  41039. config.format = format;
  41040. config.channels = channels;
  41041. config.sampleRate = sampleRate;
  41042. return config;
  41043. }
  41044. MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader)
  41045. {
  41046. if (pFader == NULL) {
  41047. return MA_INVALID_ARGS;
  41048. }
  41049. MA_ZERO_OBJECT(pFader);
  41050. if (pConfig == NULL) {
  41051. return MA_INVALID_ARGS;
  41052. }
  41053. /* Only f32 is supported for now. */
  41054. if (pConfig->format != ma_format_f32) {
  41055. return MA_INVALID_ARGS;
  41056. }
  41057. pFader->config = *pConfig;
  41058. pFader->volumeBeg = 1;
  41059. pFader->volumeEnd = 1;
  41060. pFader->lengthInFrames = 0;
  41061. pFader->cursorInFrames = 0;
  41062. return MA_SUCCESS;
  41063. }
  41064. MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  41065. {
  41066. if (pFader == NULL) {
  41067. return MA_INVALID_ARGS;
  41068. }
  41069. /* If the cursor is still negative we need to just copy the absolute number of those frames, but no more than frameCount. */
  41070. if (pFader->cursorInFrames < 0) {
  41071. ma_uint64 absCursorInFrames = (ma_uint64)0 - pFader->cursorInFrames;
  41072. if (absCursorInFrames > frameCount) {
  41073. absCursorInFrames = frameCount;
  41074. }
  41075. ma_copy_pcm_frames(pFramesOut, pFramesIn, absCursorInFrames, pFader->config.format, pFader->config.channels);
  41076. pFader->cursorInFrames += absCursorInFrames;
  41077. frameCount -= absCursorInFrames;
  41078. pFramesOut = ma_offset_ptr(pFramesOut, ma_get_bytes_per_frame(pFader->config.format, pFader->config.channels)*absCursorInFrames);
  41079. pFramesIn = ma_offset_ptr(pFramesIn, ma_get_bytes_per_frame(pFader->config.format, pFader->config.channels)*absCursorInFrames);
  41080. }
  41081. if (pFader->cursorInFrames >= 0) {
  41082. /*
  41083. For now we need to clamp frameCount so that the cursor never overflows 32-bits. This is required for
  41084. the conversion to a float which we use for the linear interpolation. This might be changed later.
  41085. */
  41086. if (frameCount + pFader->cursorInFrames > UINT_MAX) {
  41087. frameCount = UINT_MAX - pFader->cursorInFrames;
  41088. }
  41089. /* Optimized path if volumeBeg and volumeEnd are equal. */
  41090. if (pFader->volumeBeg == pFader->volumeEnd) {
  41091. if (pFader->volumeBeg == 1) {
  41092. /* Straight copy. */
  41093. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels);
  41094. } else {
  41095. /* Copy with volume. */
  41096. ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeBeg);
  41097. }
  41098. } else {
  41099. /* Slower path. Volumes are different, so may need to do an interpolation. */
  41100. if ((ma_uint64)pFader->cursorInFrames >= pFader->lengthInFrames) {
  41101. /* Fast path. We've gone past the end of the fade period so just apply the end volume to all samples. */
  41102. ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeEnd);
  41103. } else {
  41104. /* Slow path. This is where we do the actual fading. */
  41105. ma_uint64 iFrame;
  41106. ma_uint32 iChannel;
  41107. /* For now we only support f32. Support for other formats might be added later. */
  41108. if (pFader->config.format == ma_format_f32) {
  41109. const float* pFramesInF32 = (const float*)pFramesIn;
  41110. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  41111. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  41112. 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. */
  41113. float volume = ma_mix_f32_fast(pFader->volumeBeg, pFader->volumeEnd, a);
  41114. for (iChannel = 0; iChannel < pFader->config.channels; iChannel += 1) {
  41115. pFramesOutF32[iFrame*pFader->config.channels + iChannel] = pFramesInF32[iFrame*pFader->config.channels + iChannel] * volume;
  41116. }
  41117. }
  41118. } else {
  41119. return MA_NOT_IMPLEMENTED;
  41120. }
  41121. }
  41122. }
  41123. }
  41124. pFader->cursorInFrames += frameCount;
  41125. return MA_SUCCESS;
  41126. }
  41127. MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
  41128. {
  41129. if (pFader == NULL) {
  41130. return;
  41131. }
  41132. if (pFormat != NULL) {
  41133. *pFormat = pFader->config.format;
  41134. }
  41135. if (pChannels != NULL) {
  41136. *pChannels = pFader->config.channels;
  41137. }
  41138. if (pSampleRate != NULL) {
  41139. *pSampleRate = pFader->config.sampleRate;
  41140. }
  41141. }
  41142. MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames)
  41143. {
  41144. ma_fader_set_fade_ex(pFader, volumeBeg, volumeEnd, lengthInFrames, 0);
  41145. }
  41146. MA_API void ma_fader_set_fade_ex(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames, ma_int64 startOffsetInFrames)
  41147. {
  41148. if (pFader == NULL) {
  41149. return;
  41150. }
  41151. /* If the volume is negative, use current volume. */
  41152. if (volumeBeg < 0) {
  41153. volumeBeg = ma_fader_get_current_volume(pFader);
  41154. }
  41155. /*
  41156. The length needs to be clamped to 32-bits due to how we convert it to a float for linear
  41157. interpolation reasons. I might change this requirement later, but for now it's not important.
  41158. */
  41159. if (lengthInFrames > UINT_MAX) {
  41160. lengthInFrames = UINT_MAX;
  41161. }
  41162. /* The start offset needs to be clamped to ensure it doesn't overflow a signed number. */
  41163. if (startOffsetInFrames > INT_MAX) {
  41164. startOffsetInFrames = INT_MAX;
  41165. }
  41166. pFader->volumeBeg = volumeBeg;
  41167. pFader->volumeEnd = volumeEnd;
  41168. pFader->lengthInFrames = lengthInFrames;
  41169. pFader->cursorInFrames = -startOffsetInFrames;
  41170. }
  41171. MA_API float ma_fader_get_current_volume(const ma_fader* pFader)
  41172. {
  41173. if (pFader == NULL) {
  41174. return 0.0f;
  41175. }
  41176. /* Any frames prior to the start of the fade period will be at unfaded volume. */
  41177. if (pFader->cursorInFrames < 0) {
  41178. return 1.0f;
  41179. }
  41180. /* The current volume depends on the position of the cursor. */
  41181. if (pFader->cursorInFrames == 0) {
  41182. return pFader->volumeBeg;
  41183. } else if ((ma_uint64)pFader->cursorInFrames >= pFader->lengthInFrames) { /* Safe case because the < 0 case was checked above. */
  41184. return pFader->volumeEnd;
  41185. } else {
  41186. /* 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. */
  41187. 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(). */
  41188. }
  41189. }
  41190. MA_API ma_vec3f ma_vec3f_init_3f(float x, float y, float z)
  41191. {
  41192. ma_vec3f v;
  41193. v.x = x;
  41194. v.y = y;
  41195. v.z = z;
  41196. return v;
  41197. }
  41198. MA_API ma_vec3f ma_vec3f_sub(ma_vec3f a, ma_vec3f b)
  41199. {
  41200. return ma_vec3f_init_3f(
  41201. a.x - b.x,
  41202. a.y - b.y,
  41203. a.z - b.z
  41204. );
  41205. }
  41206. MA_API ma_vec3f ma_vec3f_neg(ma_vec3f a)
  41207. {
  41208. return ma_vec3f_init_3f(
  41209. -a.x,
  41210. -a.y,
  41211. -a.z
  41212. );
  41213. }
  41214. MA_API float ma_vec3f_dot(ma_vec3f a, ma_vec3f b)
  41215. {
  41216. return a.x*b.x + a.y*b.y + a.z*b.z;
  41217. }
  41218. MA_API float ma_vec3f_len2(ma_vec3f v)
  41219. {
  41220. return ma_vec3f_dot(v, v);
  41221. }
  41222. MA_API float ma_vec3f_len(ma_vec3f v)
  41223. {
  41224. return (float)ma_sqrtd(ma_vec3f_len2(v));
  41225. }
  41226. MA_API float ma_vec3f_dist(ma_vec3f a, ma_vec3f b)
  41227. {
  41228. return ma_vec3f_len(ma_vec3f_sub(a, b));
  41229. }
  41230. MA_API ma_vec3f ma_vec3f_normalize(ma_vec3f v)
  41231. {
  41232. float invLen;
  41233. float len2 = ma_vec3f_len2(v);
  41234. if (len2 == 0) {
  41235. return ma_vec3f_init_3f(0, 0, 0);
  41236. }
  41237. invLen = ma_rsqrtf(len2);
  41238. v.x *= invLen;
  41239. v.y *= invLen;
  41240. v.z *= invLen;
  41241. return v;
  41242. }
  41243. MA_API ma_vec3f ma_vec3f_cross(ma_vec3f a, ma_vec3f b)
  41244. {
  41245. return ma_vec3f_init_3f(
  41246. a.y*b.z - a.z*b.y,
  41247. a.z*b.x - a.x*b.z,
  41248. a.x*b.y - a.y*b.x
  41249. );
  41250. }
  41251. MA_API void ma_atomic_vec3f_init(ma_atomic_vec3f* v, ma_vec3f value)
  41252. {
  41253. v->v = value;
  41254. v->lock = 0; /* Important this is initialized to 0. */
  41255. }
  41256. MA_API void ma_atomic_vec3f_set(ma_atomic_vec3f* v, ma_vec3f value)
  41257. {
  41258. ma_spinlock_lock(&v->lock);
  41259. {
  41260. v->v = value;
  41261. }
  41262. ma_spinlock_unlock(&v->lock);
  41263. }
  41264. MA_API ma_vec3f ma_atomic_vec3f_get(ma_atomic_vec3f* v)
  41265. {
  41266. ma_vec3f r;
  41267. ma_spinlock_lock(&v->lock);
  41268. {
  41269. r = v->v;
  41270. }
  41271. ma_spinlock_unlock(&v->lock);
  41272. return r;
  41273. }
  41274. 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);
  41275. static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition);
  41276. #ifndef MA_DEFAULT_SPEED_OF_SOUND
  41277. #define MA_DEFAULT_SPEED_OF_SOUND 343.3f
  41278. #endif
  41279. /*
  41280. These vectors represent the direction that speakers are facing from the center point. They're used
  41281. for panning in the spatializer. Must be normalized.
  41282. */
  41283. static ma_vec3f g_maChannelDirections[MA_CHANNEL_POSITION_COUNT] = {
  41284. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_NONE */
  41285. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_MONO */
  41286. {-0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_LEFT */
  41287. {+0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_RIGHT */
  41288. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_FRONT_CENTER */
  41289. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_LFE */
  41290. {-0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_LEFT */
  41291. {+0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_RIGHT */
  41292. {-0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_LEFT_CENTER */
  41293. {+0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_RIGHT_CENTER */
  41294. { 0.0f, 0.0f, +1.0f }, /* MA_CHANNEL_BACK_CENTER */
  41295. {-1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_LEFT */
  41296. {+1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_RIGHT */
  41297. { 0.0f, +1.0f, 0.0f }, /* MA_CHANNEL_TOP_CENTER */
  41298. {-0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_LEFT */
  41299. { 0.0f, +0.7071f, -0.7071f }, /* MA_CHANNEL_TOP_FRONT_CENTER */
  41300. {+0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_RIGHT */
  41301. {-0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_LEFT */
  41302. { 0.0f, +0.7071f, +0.7071f }, /* MA_CHANNEL_TOP_BACK_CENTER */
  41303. {+0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_RIGHT */
  41304. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_0 */
  41305. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_1 */
  41306. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_2 */
  41307. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_3 */
  41308. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_4 */
  41309. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_5 */
  41310. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_6 */
  41311. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_7 */
  41312. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_8 */
  41313. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_9 */
  41314. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_10 */
  41315. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_11 */
  41316. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_12 */
  41317. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_13 */
  41318. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_14 */
  41319. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_15 */
  41320. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_16 */
  41321. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_17 */
  41322. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_18 */
  41323. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_19 */
  41324. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_20 */
  41325. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_21 */
  41326. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_22 */
  41327. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_23 */
  41328. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_24 */
  41329. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_25 */
  41330. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_26 */
  41331. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_27 */
  41332. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_28 */
  41333. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_29 */
  41334. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_30 */
  41335. { 0.0f, 0.0f, -1.0f } /* MA_CHANNEL_AUX_31 */
  41336. };
  41337. static ma_vec3f ma_get_channel_direction(ma_channel channel)
  41338. {
  41339. if (channel >= MA_CHANNEL_POSITION_COUNT) {
  41340. return ma_vec3f_init_3f(0, 0, -1);
  41341. } else {
  41342. return g_maChannelDirections[channel];
  41343. }
  41344. }
  41345. static float ma_attenuation_inverse(float distance, float minDistance, float maxDistance, float rolloff)
  41346. {
  41347. if (minDistance >= maxDistance) {
  41348. return 1; /* To avoid division by zero. Do not attenuate. */
  41349. }
  41350. return minDistance / (minDistance + rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance));
  41351. }
  41352. static float ma_attenuation_linear(float distance, float minDistance, float maxDistance, float rolloff)
  41353. {
  41354. if (minDistance >= maxDistance) {
  41355. return 1; /* To avoid division by zero. Do not attenuate. */
  41356. }
  41357. return 1 - rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance) / (maxDistance - minDistance);
  41358. }
  41359. static float ma_attenuation_exponential(float distance, float minDistance, float maxDistance, float rolloff)
  41360. {
  41361. if (minDistance >= maxDistance) {
  41362. return 1; /* To avoid division by zero. Do not attenuate. */
  41363. }
  41364. return (float)ma_powd(ma_clamp(distance, minDistance, maxDistance) / minDistance, -rolloff);
  41365. }
  41366. /*
  41367. Dopper Effect calculation taken from the OpenAL spec, with two main differences:
  41368. 1) The source to listener vector will have already been calcualted at an earlier step so we can
  41369. just use that directly. We need only the position of the source relative to the origin.
  41370. 2) We don't scale by a frequency because we actually just want the ratio which we'll plug straight
  41371. into the resampler directly.
  41372. */
  41373. static float ma_doppler_pitch(ma_vec3f relativePosition, ma_vec3f sourceVelocity, ma_vec3f listenVelocity, float speedOfSound, float dopplerFactor)
  41374. {
  41375. float len;
  41376. float vls;
  41377. float vss;
  41378. len = ma_vec3f_len(relativePosition);
  41379. /*
  41380. There's a case where the position of the source will be right on top of the listener in which
  41381. case the length will be 0 and we'll end up with a division by zero. We can just return a ratio
  41382. of 1.0 in this case. This is not considered in the OpenAL spec, but is necessary.
  41383. */
  41384. if (len == 0) {
  41385. return 1.0;
  41386. }
  41387. vls = ma_vec3f_dot(relativePosition, listenVelocity) / len;
  41388. vss = ma_vec3f_dot(relativePosition, sourceVelocity) / len;
  41389. vls = ma_min(vls, speedOfSound / dopplerFactor);
  41390. vss = ma_min(vss, speedOfSound / dopplerFactor);
  41391. return (speedOfSound - dopplerFactor*vls) / (speedOfSound - dopplerFactor*vss);
  41392. }
  41393. static void ma_get_default_channel_map_for_spatializer(ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channelCount)
  41394. {
  41395. /*
  41396. Special case for stereo. Want to default the left and right speakers to side left and side
  41397. right so that they're facing directly down the X axis rather than slightly forward. Not
  41398. doing this will result in sounds being quieter when behind the listener. This might
  41399. actually be good for some scenerios, but I don't think it's an appropriate default because
  41400. it can be a bit unexpected.
  41401. */
  41402. if (channelCount == 2) {
  41403. pChannelMap[0] = MA_CHANNEL_SIDE_LEFT;
  41404. pChannelMap[1] = MA_CHANNEL_SIDE_RIGHT;
  41405. } else {
  41406. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  41407. }
  41408. }
  41409. MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut)
  41410. {
  41411. ma_spatializer_listener_config config;
  41412. MA_ZERO_OBJECT(&config);
  41413. config.channelsOut = channelsOut;
  41414. config.pChannelMapOut = NULL;
  41415. config.handedness = ma_handedness_right;
  41416. config.worldUp = ma_vec3f_init_3f(0, 1, 0);
  41417. config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */
  41418. config.coneOuterAngleInRadians = 6.283185f; /* 360 degrees. */
  41419. config.coneOuterGain = 0;
  41420. config.speedOfSound = 343.3f; /* Same as OpenAL. Used for doppler effect. */
  41421. return config;
  41422. }
  41423. typedef struct
  41424. {
  41425. size_t sizeInBytes;
  41426. size_t channelMapOutOffset;
  41427. } ma_spatializer_listener_heap_layout;
  41428. static ma_result ma_spatializer_listener_get_heap_layout(const ma_spatializer_listener_config* pConfig, ma_spatializer_listener_heap_layout* pHeapLayout)
  41429. {
  41430. MA_ASSERT(pHeapLayout != NULL);
  41431. MA_ZERO_OBJECT(pHeapLayout);
  41432. if (pConfig == NULL) {
  41433. return MA_INVALID_ARGS;
  41434. }
  41435. if (pConfig->channelsOut == 0) {
  41436. return MA_INVALID_ARGS;
  41437. }
  41438. pHeapLayout->sizeInBytes = 0;
  41439. /* Channel map. We always need this, even for passthroughs. */
  41440. pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes;
  41441. pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapOut) * pConfig->channelsOut);
  41442. return MA_SUCCESS;
  41443. }
  41444. MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes)
  41445. {
  41446. ma_result result;
  41447. ma_spatializer_listener_heap_layout heapLayout;
  41448. if (pHeapSizeInBytes == NULL) {
  41449. return MA_INVALID_ARGS;
  41450. }
  41451. *pHeapSizeInBytes = 0;
  41452. result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout);
  41453. if (result != MA_SUCCESS) {
  41454. return result;
  41455. }
  41456. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  41457. return MA_SUCCESS;
  41458. }
  41459. MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener)
  41460. {
  41461. ma_result result;
  41462. ma_spatializer_listener_heap_layout heapLayout;
  41463. if (pListener == NULL) {
  41464. return MA_INVALID_ARGS;
  41465. }
  41466. MA_ZERO_OBJECT(pListener);
  41467. result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout);
  41468. if (result != MA_SUCCESS) {
  41469. return result;
  41470. }
  41471. pListener->_pHeap = pHeap;
  41472. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  41473. pListener->config = *pConfig;
  41474. ma_atomic_vec3f_init(&pListener->position, ma_vec3f_init_3f(0, 0, 0));
  41475. ma_atomic_vec3f_init(&pListener->direction, ma_vec3f_init_3f(0, 0, -1));
  41476. ma_atomic_vec3f_init(&pListener->velocity, ma_vec3f_init_3f(0, 0, 0));
  41477. pListener->isEnabled = MA_TRUE;
  41478. /* Swap the forward direction if we're left handed (it was initialized based on right handed). */
  41479. if (pListener->config.handedness == ma_handedness_left) {
  41480. ma_vec3f negDir = ma_vec3f_neg(ma_spatializer_listener_get_direction(pListener));
  41481. ma_spatializer_listener_set_direction(pListener, negDir.x, negDir.y, negDir.z);
  41482. }
  41483. /* We must always have a valid channel map. */
  41484. pListener->config.pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset);
  41485. /* Use a slightly different default channel map for stereo. */
  41486. if (pConfig->pChannelMapOut == NULL) {
  41487. ma_get_default_channel_map_for_spatializer(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->channelsOut);
  41488. } else {
  41489. ma_channel_map_copy_or_default(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut);
  41490. }
  41491. return MA_SUCCESS;
  41492. }
  41493. MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener)
  41494. {
  41495. ma_result result;
  41496. size_t heapSizeInBytes;
  41497. void* pHeap;
  41498. result = ma_spatializer_listener_get_heap_size(pConfig, &heapSizeInBytes);
  41499. if (result != MA_SUCCESS) {
  41500. return result;
  41501. }
  41502. if (heapSizeInBytes > 0) {
  41503. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  41504. if (pHeap == NULL) {
  41505. return MA_OUT_OF_MEMORY;
  41506. }
  41507. } else {
  41508. pHeap = NULL;
  41509. }
  41510. result = ma_spatializer_listener_init_preallocated(pConfig, pHeap, pListener);
  41511. if (result != MA_SUCCESS) {
  41512. ma_free(pHeap, pAllocationCallbacks);
  41513. return result;
  41514. }
  41515. pListener->_ownsHeap = MA_TRUE;
  41516. return MA_SUCCESS;
  41517. }
  41518. MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks)
  41519. {
  41520. if (pListener == NULL) {
  41521. return;
  41522. }
  41523. if (pListener->_ownsHeap) {
  41524. ma_free(pListener->_pHeap, pAllocationCallbacks);
  41525. }
  41526. }
  41527. MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener)
  41528. {
  41529. if (pListener == NULL) {
  41530. return NULL;
  41531. }
  41532. return pListener->config.pChannelMapOut;
  41533. }
  41534. MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  41535. {
  41536. if (pListener == NULL) {
  41537. return;
  41538. }
  41539. pListener->config.coneInnerAngleInRadians = innerAngleInRadians;
  41540. pListener->config.coneOuterAngleInRadians = outerAngleInRadians;
  41541. pListener->config.coneOuterGain = outerGain;
  41542. }
  41543. MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  41544. {
  41545. if (pListener == NULL) {
  41546. return;
  41547. }
  41548. if (pInnerAngleInRadians != NULL) {
  41549. *pInnerAngleInRadians = pListener->config.coneInnerAngleInRadians;
  41550. }
  41551. if (pOuterAngleInRadians != NULL) {
  41552. *pOuterAngleInRadians = pListener->config.coneOuterAngleInRadians;
  41553. }
  41554. if (pOuterGain != NULL) {
  41555. *pOuterGain = pListener->config.coneOuterGain;
  41556. }
  41557. }
  41558. MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z)
  41559. {
  41560. if (pListener == NULL) {
  41561. return;
  41562. }
  41563. ma_atomic_vec3f_set(&pListener->position, ma_vec3f_init_3f(x, y, z));
  41564. }
  41565. MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener)
  41566. {
  41567. if (pListener == NULL) {
  41568. return ma_vec3f_init_3f(0, 0, 0);
  41569. }
  41570. 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. */
  41571. }
  41572. MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z)
  41573. {
  41574. if (pListener == NULL) {
  41575. return;
  41576. }
  41577. ma_atomic_vec3f_set(&pListener->direction, ma_vec3f_init_3f(x, y, z));
  41578. }
  41579. MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener)
  41580. {
  41581. if (pListener == NULL) {
  41582. return ma_vec3f_init_3f(0, 0, -1);
  41583. }
  41584. 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. */
  41585. }
  41586. MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z)
  41587. {
  41588. if (pListener == NULL) {
  41589. return;
  41590. }
  41591. ma_atomic_vec3f_set(&pListener->velocity, ma_vec3f_init_3f(x, y, z));
  41592. }
  41593. MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener)
  41594. {
  41595. if (pListener == NULL) {
  41596. return ma_vec3f_init_3f(0, 0, 0);
  41597. }
  41598. 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. */
  41599. }
  41600. MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound)
  41601. {
  41602. if (pListener == NULL) {
  41603. return;
  41604. }
  41605. pListener->config.speedOfSound = speedOfSound;
  41606. }
  41607. MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener)
  41608. {
  41609. if (pListener == NULL) {
  41610. return 0;
  41611. }
  41612. return pListener->config.speedOfSound;
  41613. }
  41614. MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z)
  41615. {
  41616. if (pListener == NULL) {
  41617. return;
  41618. }
  41619. pListener->config.worldUp = ma_vec3f_init_3f(x, y, z);
  41620. }
  41621. MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener)
  41622. {
  41623. if (pListener == NULL) {
  41624. return ma_vec3f_init_3f(0, 1, 0);
  41625. }
  41626. return pListener->config.worldUp;
  41627. }
  41628. MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled)
  41629. {
  41630. if (pListener == NULL) {
  41631. return;
  41632. }
  41633. pListener->isEnabled = isEnabled;
  41634. }
  41635. MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener)
  41636. {
  41637. if (pListener == NULL) {
  41638. return MA_FALSE;
  41639. }
  41640. return pListener->isEnabled;
  41641. }
  41642. MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut)
  41643. {
  41644. ma_spatializer_config config;
  41645. MA_ZERO_OBJECT(&config);
  41646. config.channelsIn = channelsIn;
  41647. config.channelsOut = channelsOut;
  41648. config.pChannelMapIn = NULL;
  41649. config.attenuationModel = ma_attenuation_model_inverse;
  41650. config.positioning = ma_positioning_absolute;
  41651. config.handedness = ma_handedness_right;
  41652. config.minGain = 0;
  41653. config.maxGain = 1;
  41654. config.minDistance = 1;
  41655. config.maxDistance = MA_FLT_MAX;
  41656. config.rolloff = 1;
  41657. config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */
  41658. config.coneOuterAngleInRadians = 6.283185f; /* 360 degress. */
  41659. config.coneOuterGain = 0.0f;
  41660. config.dopplerFactor = 1;
  41661. config.directionalAttenuationFactor = 1;
  41662. config.minSpatializationChannelGain = 0.2f;
  41663. config.gainSmoothTimeInFrames = 360; /* 7.5ms @ 48K. */
  41664. return config;
  41665. }
  41666. static ma_gainer_config ma_spatializer_gainer_config_init(const ma_spatializer_config* pConfig)
  41667. {
  41668. MA_ASSERT(pConfig != NULL);
  41669. return ma_gainer_config_init(pConfig->channelsOut, pConfig->gainSmoothTimeInFrames);
  41670. }
  41671. static ma_result ma_spatializer_validate_config(const ma_spatializer_config* pConfig)
  41672. {
  41673. MA_ASSERT(pConfig != NULL);
  41674. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  41675. return MA_INVALID_ARGS;
  41676. }
  41677. return MA_SUCCESS;
  41678. }
  41679. typedef struct
  41680. {
  41681. size_t sizeInBytes;
  41682. size_t channelMapInOffset;
  41683. size_t newChannelGainsOffset;
  41684. size_t gainerOffset;
  41685. } ma_spatializer_heap_layout;
  41686. static ma_result ma_spatializer_get_heap_layout(const ma_spatializer_config* pConfig, ma_spatializer_heap_layout* pHeapLayout)
  41687. {
  41688. ma_result result;
  41689. MA_ASSERT(pHeapLayout != NULL);
  41690. MA_ZERO_OBJECT(pHeapLayout);
  41691. if (pConfig == NULL) {
  41692. return MA_INVALID_ARGS;
  41693. }
  41694. result = ma_spatializer_validate_config(pConfig);
  41695. if (result != MA_SUCCESS) {
  41696. return result;
  41697. }
  41698. pHeapLayout->sizeInBytes = 0;
  41699. /* Channel map. */
  41700. pHeapLayout->channelMapInOffset = MA_SIZE_MAX; /* <-- MA_SIZE_MAX indicates no allocation necessary. */
  41701. if (pConfig->pChannelMapIn != NULL) {
  41702. pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes;
  41703. pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapIn) * pConfig->channelsIn);
  41704. }
  41705. /* New channel gains for output. */
  41706. pHeapLayout->newChannelGainsOffset = pHeapLayout->sizeInBytes;
  41707. pHeapLayout->sizeInBytes += ma_align_64(sizeof(float) * pConfig->channelsOut);
  41708. /* Gainer. */
  41709. {
  41710. size_t gainerHeapSizeInBytes;
  41711. ma_gainer_config gainerConfig;
  41712. gainerConfig = ma_spatializer_gainer_config_init(pConfig);
  41713. result = ma_gainer_get_heap_size(&gainerConfig, &gainerHeapSizeInBytes);
  41714. if (result != MA_SUCCESS) {
  41715. return result;
  41716. }
  41717. pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes;
  41718. pHeapLayout->sizeInBytes += ma_align_64(gainerHeapSizeInBytes);
  41719. }
  41720. return MA_SUCCESS;
  41721. }
  41722. MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes)
  41723. {
  41724. ma_result result;
  41725. ma_spatializer_heap_layout heapLayout;
  41726. if (pHeapSizeInBytes == NULL) {
  41727. return MA_INVALID_ARGS;
  41728. }
  41729. *pHeapSizeInBytes = 0; /* Safety. */
  41730. result = ma_spatializer_get_heap_layout(pConfig, &heapLayout);
  41731. if (result != MA_SUCCESS) {
  41732. return result;
  41733. }
  41734. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  41735. return MA_SUCCESS;
  41736. }
  41737. MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer)
  41738. {
  41739. ma_result result;
  41740. ma_spatializer_heap_layout heapLayout;
  41741. ma_gainer_config gainerConfig;
  41742. if (pSpatializer == NULL) {
  41743. return MA_INVALID_ARGS;
  41744. }
  41745. MA_ZERO_OBJECT(pSpatializer);
  41746. if (pConfig == NULL || pHeap == NULL) {
  41747. return MA_INVALID_ARGS;
  41748. }
  41749. result = ma_spatializer_get_heap_layout(pConfig, &heapLayout);
  41750. if (result != MA_SUCCESS) {
  41751. return result;
  41752. }
  41753. pSpatializer->_pHeap = pHeap;
  41754. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  41755. pSpatializer->channelsIn = pConfig->channelsIn;
  41756. pSpatializer->channelsOut = pConfig->channelsOut;
  41757. pSpatializer->attenuationModel = pConfig->attenuationModel;
  41758. pSpatializer->positioning = pConfig->positioning;
  41759. pSpatializer->handedness = pConfig->handedness;
  41760. pSpatializer->minGain = pConfig->minGain;
  41761. pSpatializer->maxGain = pConfig->maxGain;
  41762. pSpatializer->minDistance = pConfig->minDistance;
  41763. pSpatializer->maxDistance = pConfig->maxDistance;
  41764. pSpatializer->rolloff = pConfig->rolloff;
  41765. pSpatializer->coneInnerAngleInRadians = pConfig->coneInnerAngleInRadians;
  41766. pSpatializer->coneOuterAngleInRadians = pConfig->coneOuterAngleInRadians;
  41767. pSpatializer->coneOuterGain = pConfig->coneOuterGain;
  41768. pSpatializer->dopplerFactor = pConfig->dopplerFactor;
  41769. pSpatializer->minSpatializationChannelGain = pConfig->minSpatializationChannelGain;
  41770. pSpatializer->directionalAttenuationFactor = pConfig->directionalAttenuationFactor;
  41771. pSpatializer->gainSmoothTimeInFrames = pConfig->gainSmoothTimeInFrames;
  41772. ma_atomic_vec3f_init(&pSpatializer->position, ma_vec3f_init_3f(0, 0, 0));
  41773. ma_atomic_vec3f_init(&pSpatializer->direction, ma_vec3f_init_3f(0, 0, -1));
  41774. ma_atomic_vec3f_init(&pSpatializer->velocity, ma_vec3f_init_3f(0, 0, 0));
  41775. pSpatializer->dopplerPitch = 1;
  41776. /* Swap the forward direction if we're left handed (it was initialized based on right handed). */
  41777. if (pSpatializer->handedness == ma_handedness_left) {
  41778. ma_vec3f negDir = ma_vec3f_neg(ma_spatializer_get_direction(pSpatializer));
  41779. ma_spatializer_set_direction(pSpatializer, negDir.x, negDir.y, negDir.z);
  41780. }
  41781. /* Channel map. This will be on the heap. */
  41782. if (pConfig->pChannelMapIn != NULL) {
  41783. pSpatializer->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset);
  41784. ma_channel_map_copy_or_default(pSpatializer->pChannelMapIn, pSpatializer->channelsIn, pConfig->pChannelMapIn, pSpatializer->channelsIn);
  41785. }
  41786. /* New channel gains for output channels. */
  41787. pSpatializer->pNewChannelGainsOut = (float*)ma_offset_ptr(pHeap, heapLayout.newChannelGainsOffset);
  41788. /* Gainer. */
  41789. gainerConfig = ma_spatializer_gainer_config_init(pConfig);
  41790. result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pSpatializer->gainer);
  41791. if (result != MA_SUCCESS) {
  41792. return result; /* Failed to initialize the gainer. */
  41793. }
  41794. return MA_SUCCESS;
  41795. }
  41796. MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer)
  41797. {
  41798. ma_result result;
  41799. size_t heapSizeInBytes;
  41800. void* pHeap;
  41801. /* We'll need a heap allocation to retrieve the size. */
  41802. result = ma_spatializer_get_heap_size(pConfig, &heapSizeInBytes);
  41803. if (result != MA_SUCCESS) {
  41804. return result;
  41805. }
  41806. if (heapSizeInBytes > 0) {
  41807. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  41808. if (pHeap == NULL) {
  41809. return MA_OUT_OF_MEMORY;
  41810. }
  41811. } else {
  41812. pHeap = NULL;
  41813. }
  41814. result = ma_spatializer_init_preallocated(pConfig, pHeap, pSpatializer);
  41815. if (result != MA_SUCCESS) {
  41816. ma_free(pHeap, pAllocationCallbacks);
  41817. return result;
  41818. }
  41819. pSpatializer->_ownsHeap = MA_TRUE;
  41820. return MA_SUCCESS;
  41821. }
  41822. MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks)
  41823. {
  41824. if (pSpatializer == NULL) {
  41825. return;
  41826. }
  41827. ma_gainer_uninit(&pSpatializer->gainer, pAllocationCallbacks);
  41828. if (pSpatializer->_ownsHeap) {
  41829. ma_free(pSpatializer->_pHeap, pAllocationCallbacks);
  41830. }
  41831. }
  41832. static float ma_calculate_angular_gain(ma_vec3f dirA, ma_vec3f dirB, float coneInnerAngleInRadians, float coneOuterAngleInRadians, float coneOuterGain)
  41833. {
  41834. /*
  41835. Angular attenuation.
  41836. Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure
  41837. this out for ourselves at the expense of possibly being inconsistent with other implementations.
  41838. To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We
  41839. just need to get the direction from the source to the listener and then do a dot product against that and the
  41840. direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer
  41841. angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than
  41842. the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain.
  41843. */
  41844. if (coneInnerAngleInRadians < 6.283185f) {
  41845. float angularGain = 1;
  41846. float cutoffInner = (float)ma_cosd(coneInnerAngleInRadians*0.5f);
  41847. float cutoffOuter = (float)ma_cosd(coneOuterAngleInRadians*0.5f);
  41848. float d;
  41849. d = ma_vec3f_dot(dirA, dirB);
  41850. if (d > cutoffInner) {
  41851. /* It's inside the inner angle. */
  41852. angularGain = 1;
  41853. } else {
  41854. /* It's outside the inner angle. */
  41855. if (d > cutoffOuter) {
  41856. /* It's between the inner and outer angle. We need to linearly interpolate between 1 and coneOuterGain. */
  41857. angularGain = ma_mix_f32(coneOuterGain, 1, (d - cutoffOuter) / (cutoffInner - cutoffOuter));
  41858. } else {
  41859. /* It's outside the outer angle. */
  41860. angularGain = coneOuterGain;
  41861. }
  41862. }
  41863. /*printf("d = %f; cutoffInner = %f; cutoffOuter = %f; angularGain = %f\n", d, cutoffInner, cutoffOuter, angularGain);*/
  41864. return angularGain;
  41865. } else {
  41866. /* Inner angle is 360 degrees so no need to do any attenuation. */
  41867. return 1;
  41868. }
  41869. }
  41870. MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  41871. {
  41872. ma_channel* pChannelMapIn = pSpatializer->pChannelMapIn;
  41873. ma_channel* pChannelMapOut = pListener->config.pChannelMapOut;
  41874. if (pSpatializer == NULL) {
  41875. return MA_INVALID_ARGS;
  41876. }
  41877. /* If we're not spatializing we need to run an optimized path. */
  41878. if (ma_atomic_load_i32(&pSpatializer->attenuationModel) == ma_attenuation_model_none) {
  41879. if (ma_spatializer_listener_is_enabled(pListener)) {
  41880. /* No attenuation is required, but we'll need to do some channel conversion. */
  41881. if (pSpatializer->channelsIn == pSpatializer->channelsOut) {
  41882. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, pSpatializer->channelsIn);
  41883. } else {
  41884. 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. */
  41885. }
  41886. } else {
  41887. /* The listener is disabled. Output silence. */
  41888. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut);
  41889. }
  41890. /*
  41891. We're not doing attenuation so don't bother with doppler for now. I'm not sure if this is
  41892. the correct thinking so might need to review this later.
  41893. */
  41894. pSpatializer->dopplerPitch = 1;
  41895. } else {
  41896. /*
  41897. Let's first determine which listener the sound is closest to. Need to keep in mind that we
  41898. might not have a world or any listeners, in which case we just spatializer based on the
  41899. listener being positioned at the origin (0, 0, 0).
  41900. */
  41901. ma_vec3f relativePosNormalized;
  41902. ma_vec3f relativePos; /* The position relative to the listener. */
  41903. ma_vec3f relativeDir; /* The direction of the sound, relative to the listener. */
  41904. ma_vec3f listenerVel; /* The volocity of the listener. For doppler pitch calculation. */
  41905. float speedOfSound;
  41906. float distance = 0;
  41907. float gain = 1;
  41908. ma_uint32 iChannel;
  41909. const ma_uint32 channelsOut = pSpatializer->channelsOut;
  41910. const ma_uint32 channelsIn = pSpatializer->channelsIn;
  41911. float minDistance = ma_spatializer_get_min_distance(pSpatializer);
  41912. float maxDistance = ma_spatializer_get_max_distance(pSpatializer);
  41913. float rolloff = ma_spatializer_get_rolloff(pSpatializer);
  41914. float dopplerFactor = ma_spatializer_get_doppler_factor(pSpatializer);
  41915. /*
  41916. We'll need the listener velocity for doppler pitch calculations. The speed of sound is
  41917. defined by the listener, so we'll grab that here too.
  41918. */
  41919. if (pListener != NULL) {
  41920. listenerVel = ma_spatializer_listener_get_velocity(pListener);
  41921. speedOfSound = pListener->config.speedOfSound;
  41922. } else {
  41923. listenerVel = ma_vec3f_init_3f(0, 0, 0);
  41924. speedOfSound = MA_DEFAULT_SPEED_OF_SOUND;
  41925. }
  41926. if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) {
  41927. /* There's no listener or we're using relative positioning. */
  41928. relativePos = ma_spatializer_get_position(pSpatializer);
  41929. relativeDir = ma_spatializer_get_direction(pSpatializer);
  41930. } else {
  41931. /*
  41932. We've found a listener and we're using absolute positioning. We need to transform the
  41933. sound's position and direction so that it's relative to listener. Later on we'll use
  41934. this for determining the factors to apply to each channel to apply the panning effect.
  41935. */
  41936. ma_spatializer_get_relative_position_and_direction(pSpatializer, pListener, &relativePos, &relativeDir);
  41937. }
  41938. distance = ma_vec3f_len(relativePos);
  41939. /* We've gathered the data, so now we can apply some spatialization. */
  41940. switch (ma_spatializer_get_attenuation_model(pSpatializer)) {
  41941. case ma_attenuation_model_inverse:
  41942. {
  41943. gain = ma_attenuation_inverse(distance, minDistance, maxDistance, rolloff);
  41944. } break;
  41945. case ma_attenuation_model_linear:
  41946. {
  41947. gain = ma_attenuation_linear(distance, minDistance, maxDistance, rolloff);
  41948. } break;
  41949. case ma_attenuation_model_exponential:
  41950. {
  41951. gain = ma_attenuation_exponential(distance, minDistance, maxDistance, rolloff);
  41952. } break;
  41953. case ma_attenuation_model_none:
  41954. default:
  41955. {
  41956. gain = 1;
  41957. } break;
  41958. }
  41959. /* Normalize the position. */
  41960. if (distance > 0.001f) {
  41961. float distanceInv = 1/distance;
  41962. relativePosNormalized = relativePos;
  41963. relativePosNormalized.x *= distanceInv;
  41964. relativePosNormalized.y *= distanceInv;
  41965. relativePosNormalized.z *= distanceInv;
  41966. } else {
  41967. distance = 0;
  41968. relativePosNormalized = ma_vec3f_init_3f(0, 0, 0);
  41969. }
  41970. /*
  41971. Angular attenuation.
  41972. Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure
  41973. this out for ourselves at the expense of possibly being inconsistent with other implementations.
  41974. To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We
  41975. just need to get the direction from the source to the listener and then do a dot product against that and the
  41976. direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer
  41977. angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than
  41978. the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain.
  41979. */
  41980. if (distance > 0) {
  41981. /* Source anglular gain. */
  41982. float spatializerConeInnerAngle;
  41983. float spatializerConeOuterAngle;
  41984. float spatializerConeOuterGain;
  41985. ma_spatializer_get_cone(pSpatializer, &spatializerConeInnerAngle, &spatializerConeOuterAngle, &spatializerConeOuterGain);
  41986. gain *= ma_calculate_angular_gain(relativeDir, ma_vec3f_neg(relativePosNormalized), spatializerConeInnerAngle, spatializerConeOuterAngle, spatializerConeOuterGain);
  41987. /*
  41988. We're supporting angular gain on the listener as well for those who want to reduce the volume of sounds that
  41989. are positioned behind the listener. On default settings, this will have no effect.
  41990. */
  41991. if (pListener != NULL && pListener->config.coneInnerAngleInRadians < 6.283185f) {
  41992. ma_vec3f listenerDirection;
  41993. float listenerInnerAngle;
  41994. float listenerOuterAngle;
  41995. float listenerOuterGain;
  41996. if (pListener->config.handedness == ma_handedness_right) {
  41997. listenerDirection = ma_vec3f_init_3f(0, 0, -1);
  41998. } else {
  41999. listenerDirection = ma_vec3f_init_3f(0, 0, +1);
  42000. }
  42001. listenerInnerAngle = pListener->config.coneInnerAngleInRadians;
  42002. listenerOuterAngle = pListener->config.coneOuterAngleInRadians;
  42003. listenerOuterGain = pListener->config.coneOuterGain;
  42004. gain *= ma_calculate_angular_gain(listenerDirection, relativePosNormalized, listenerInnerAngle, listenerOuterAngle, listenerOuterGain);
  42005. }
  42006. } else {
  42007. /* The sound is right on top of the listener. Don't do any angular attenuation. */
  42008. }
  42009. /* Clamp the gain. */
  42010. gain = ma_clamp(gain, ma_spatializer_get_min_gain(pSpatializer), ma_spatializer_get_max_gain(pSpatializer));
  42011. /*
  42012. The gain needs to be applied per-channel here. The spatialization code below will be changing the per-channel
  42013. gains which will then eventually be passed into the gainer which will deal with smoothing the gain transitions
  42014. to avoid harsh changes in gain.
  42015. */
  42016. for (iChannel = 0; iChannel < channelsOut; iChannel += 1) {
  42017. pSpatializer->pNewChannelGainsOut[iChannel] = gain;
  42018. }
  42019. /*
  42020. Convert to our output channel count. If the listener is disabled we just output silence here. We cannot ignore
  42021. the whole section of code here because we need to update some internal spatialization state.
  42022. */
  42023. if (ma_spatializer_listener_is_enabled(pListener)) {
  42024. 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);
  42025. } else {
  42026. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut);
  42027. }
  42028. /*
  42029. Panning. This is where we'll apply the gain and convert to the output channel count. We have an optimized path for
  42030. when we're converting to a mono stream. In that case we don't really need to do any panning - we just apply the
  42031. gain to the final output.
  42032. */
  42033. /*printf("distance=%f; gain=%f\n", distance, gain);*/
  42034. /* We must have a valid channel map here to ensure we spatialize properly. */
  42035. MA_ASSERT(pChannelMapOut != NULL);
  42036. /*
  42037. We're not converting to mono so we'll want to apply some panning. This is where the feeling of something being
  42038. to the left, right, infront or behind the listener is calculated. I'm just using a basic model here. Note that
  42039. the code below is not based on any specific algorithm. I'm just implementing this off the top of my head and
  42040. seeing how it goes. There might be better ways to do this.
  42041. To determine the direction of the sound relative to a speaker I'm using dot products. Each speaker is given a
  42042. direction. For example, the left channel in a stereo system will be -1 on the X axis and the right channel will
  42043. be +1 on the X axis. A dot product is performed against the direction vector of the channel and the normalized
  42044. position of the sound.
  42045. */
  42046. /*
  42047. Calculate our per-channel gains. We do this based on the normalized relative position of the sound and it's
  42048. relation to the direction of the channel.
  42049. */
  42050. if (distance > 0) {
  42051. ma_vec3f unitPos = relativePos;
  42052. float distanceInv = 1/distance;
  42053. unitPos.x *= distanceInv;
  42054. unitPos.y *= distanceInv;
  42055. unitPos.z *= distanceInv;
  42056. for (iChannel = 0; iChannel < channelsOut; iChannel += 1) {
  42057. ma_channel channelOut;
  42058. float d;
  42059. float dMin;
  42060. channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannel);
  42061. if (ma_is_spatial_channel_position(channelOut)) {
  42062. d = ma_mix_f32_fast(1, ma_vec3f_dot(unitPos, ma_get_channel_direction(channelOut)), ma_spatializer_get_directional_attenuation_factor(pSpatializer));
  42063. } else {
  42064. d = 1; /* It's not a spatial channel so there's no real notion of direction. */
  42065. }
  42066. /*
  42067. In my testing, if the panning effect is too aggressive it makes spatialization feel uncomfortable.
  42068. The "dMin" variable below is used to control the aggressiveness of the panning effect. When set to
  42069. 0, panning will be most extreme and any sounds that are positioned on the opposite side of the
  42070. speaker will be completely silent from that speaker. Not only does this feel uncomfortable, it
  42071. doesn't even remotely represent the real world at all because sounds that come from your right side
  42072. are still clearly audible from your left side. Setting "dMin" to 1 will result in no panning at
  42073. all, which is also not ideal. By setting it to something greater than 0, the spatialization effect
  42074. becomes much less dramatic and a lot more bearable.
  42075. Summary: 0 = more extreme panning; 1 = no panning.
  42076. */
  42077. dMin = pSpatializer->minSpatializationChannelGain;
  42078. /*
  42079. At this point, "d" will be positive if the sound is on the same side as the channel and negative if
  42080. it's on the opposite side. It will be in the range of -1..1. There's two ways I can think of to
  42081. calculate a panning value. The first is to simply convert it to 0..1, however this has a problem
  42082. which I'm not entirely happy with. Considering a stereo system, when a sound is positioned right
  42083. in front of the listener it'll result in each speaker getting a gain of 0.5. I don't know if I like
  42084. the idea of having a scaling factor of 0.5 being applied to a sound when it's sitting right in front
  42085. of the listener. I would intuitively expect that to be played at full volume, or close to it.
  42086. The second idea I think of is to only apply a reduction in gain when the sound is on the opposite
  42087. side of the speaker. That is, reduce the gain only when the dot product is negative. The problem
  42088. with this is that there will not be any attenuation as the sound sweeps around the 180 degrees
  42089. where the dot product is positive. The idea with this option is that you leave the gain at 1 when
  42090. the sound is being played on the same side as the speaker and then you just reduce the volume when
  42091. the sound is on the other side.
  42092. The summarize, I think the first option should give a better sense of spatialization, but the second
  42093. option is better for preserving the sound's power.
  42094. UPDATE: In my testing, I find the first option to sound better. You can feel the sense of space a
  42095. bit better, but you can also hear the reduction in volume when it's right in front.
  42096. */
  42097. #if 1
  42098. {
  42099. /*
  42100. Scale the dot product from -1..1 to 0..1. Will result in a sound directly in front losing power
  42101. by being played at 0.5 gain.
  42102. */
  42103. d = (d + 1) * 0.5f; /* -1..1 to 0..1 */
  42104. d = ma_max(d, dMin);
  42105. pSpatializer->pNewChannelGainsOut[iChannel] *= d;
  42106. }
  42107. #else
  42108. {
  42109. /*
  42110. Only reduce the volume of the sound if it's on the opposite side. This path keeps the volume more
  42111. consistent, but comes at the expense of a worse sense of space and positioning.
  42112. */
  42113. if (d < 0) {
  42114. d += 1; /* Move into the positive range. */
  42115. d = ma_max(d, dMin);
  42116. channelGainsOut[iChannel] *= d;
  42117. }
  42118. }
  42119. #endif
  42120. }
  42121. } else {
  42122. /* Assume the sound is right on top of us. Don't do any panning. */
  42123. }
  42124. /* 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. */
  42125. ma_gainer_set_gains(&pSpatializer->gainer, pSpatializer->pNewChannelGainsOut);
  42126. ma_gainer_process_pcm_frames(&pSpatializer->gainer, pFramesOut, pFramesOut, frameCount);
  42127. /*
  42128. Before leaving we'll want to update our doppler pitch so that the caller can apply some
  42129. pitch shifting if they desire. Note that we need to negate the relative position here
  42130. because the doppler calculation needs to be source-to-listener, but ours is listener-to-
  42131. source.
  42132. */
  42133. if (dopplerFactor > 0) {
  42134. 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);
  42135. } else {
  42136. pSpatializer->dopplerPitch = 1;
  42137. }
  42138. }
  42139. return MA_SUCCESS;
  42140. }
  42141. MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume)
  42142. {
  42143. if (pSpatializer == NULL) {
  42144. return MA_INVALID_ARGS;
  42145. }
  42146. return ma_gainer_set_master_volume(&pSpatializer->gainer, volume);
  42147. }
  42148. MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume)
  42149. {
  42150. if (pSpatializer == NULL) {
  42151. return MA_INVALID_ARGS;
  42152. }
  42153. return ma_gainer_get_master_volume(&pSpatializer->gainer, pVolume);
  42154. }
  42155. MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer)
  42156. {
  42157. if (pSpatializer == NULL) {
  42158. return 0;
  42159. }
  42160. return pSpatializer->channelsIn;
  42161. }
  42162. MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer)
  42163. {
  42164. if (pSpatializer == NULL) {
  42165. return 0;
  42166. }
  42167. return pSpatializer->channelsOut;
  42168. }
  42169. MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel)
  42170. {
  42171. if (pSpatializer == NULL) {
  42172. return;
  42173. }
  42174. ma_atomic_exchange_i32(&pSpatializer->attenuationModel, attenuationModel);
  42175. }
  42176. MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer)
  42177. {
  42178. if (pSpatializer == NULL) {
  42179. return ma_attenuation_model_none;
  42180. }
  42181. return (ma_attenuation_model)ma_atomic_load_i32(&pSpatializer->attenuationModel);
  42182. }
  42183. MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning)
  42184. {
  42185. if (pSpatializer == NULL) {
  42186. return;
  42187. }
  42188. ma_atomic_exchange_i32(&pSpatializer->positioning, positioning);
  42189. }
  42190. MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer)
  42191. {
  42192. if (pSpatializer == NULL) {
  42193. return ma_positioning_absolute;
  42194. }
  42195. return (ma_positioning)ma_atomic_load_i32(&pSpatializer->positioning);
  42196. }
  42197. MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff)
  42198. {
  42199. if (pSpatializer == NULL) {
  42200. return;
  42201. }
  42202. ma_atomic_exchange_f32(&pSpatializer->rolloff, rolloff);
  42203. }
  42204. MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer)
  42205. {
  42206. if (pSpatializer == NULL) {
  42207. return 0;
  42208. }
  42209. return ma_atomic_load_f32(&pSpatializer->rolloff);
  42210. }
  42211. MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain)
  42212. {
  42213. if (pSpatializer == NULL) {
  42214. return;
  42215. }
  42216. ma_atomic_exchange_f32(&pSpatializer->minGain, minGain);
  42217. }
  42218. MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer)
  42219. {
  42220. if (pSpatializer == NULL) {
  42221. return 0;
  42222. }
  42223. return ma_atomic_load_f32(&pSpatializer->minGain);
  42224. }
  42225. MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain)
  42226. {
  42227. if (pSpatializer == NULL) {
  42228. return;
  42229. }
  42230. ma_atomic_exchange_f32(&pSpatializer->maxGain, maxGain);
  42231. }
  42232. MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer)
  42233. {
  42234. if (pSpatializer == NULL) {
  42235. return 0;
  42236. }
  42237. return ma_atomic_load_f32(&pSpatializer->maxGain);
  42238. }
  42239. MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance)
  42240. {
  42241. if (pSpatializer == NULL) {
  42242. return;
  42243. }
  42244. ma_atomic_exchange_f32(&pSpatializer->minDistance, minDistance);
  42245. }
  42246. MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer)
  42247. {
  42248. if (pSpatializer == NULL) {
  42249. return 0;
  42250. }
  42251. return ma_atomic_load_f32(&pSpatializer->minDistance);
  42252. }
  42253. MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance)
  42254. {
  42255. if (pSpatializer == NULL) {
  42256. return;
  42257. }
  42258. ma_atomic_exchange_f32(&pSpatializer->maxDistance, maxDistance);
  42259. }
  42260. MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer)
  42261. {
  42262. if (pSpatializer == NULL) {
  42263. return 0;
  42264. }
  42265. return ma_atomic_load_f32(&pSpatializer->maxDistance);
  42266. }
  42267. MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  42268. {
  42269. if (pSpatializer == NULL) {
  42270. return;
  42271. }
  42272. ma_atomic_exchange_f32(&pSpatializer->coneInnerAngleInRadians, innerAngleInRadians);
  42273. ma_atomic_exchange_f32(&pSpatializer->coneOuterAngleInRadians, outerAngleInRadians);
  42274. ma_atomic_exchange_f32(&pSpatializer->coneOuterGain, outerGain);
  42275. }
  42276. MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  42277. {
  42278. if (pSpatializer == NULL) {
  42279. return;
  42280. }
  42281. if (pInnerAngleInRadians != NULL) {
  42282. *pInnerAngleInRadians = ma_atomic_load_f32(&pSpatializer->coneInnerAngleInRadians);
  42283. }
  42284. if (pOuterAngleInRadians != NULL) {
  42285. *pOuterAngleInRadians = ma_atomic_load_f32(&pSpatializer->coneOuterAngleInRadians);
  42286. }
  42287. if (pOuterGain != NULL) {
  42288. *pOuterGain = ma_atomic_load_f32(&pSpatializer->coneOuterGain);
  42289. }
  42290. }
  42291. MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor)
  42292. {
  42293. if (pSpatializer == NULL) {
  42294. return;
  42295. }
  42296. ma_atomic_exchange_f32(&pSpatializer->dopplerFactor, dopplerFactor);
  42297. }
  42298. MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer)
  42299. {
  42300. if (pSpatializer == NULL) {
  42301. return 1;
  42302. }
  42303. return ma_atomic_load_f32(&pSpatializer->dopplerFactor);
  42304. }
  42305. MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor)
  42306. {
  42307. if (pSpatializer == NULL) {
  42308. return;
  42309. }
  42310. ma_atomic_exchange_f32(&pSpatializer->directionalAttenuationFactor, directionalAttenuationFactor);
  42311. }
  42312. MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer)
  42313. {
  42314. if (pSpatializer == NULL) {
  42315. return 1;
  42316. }
  42317. return ma_atomic_load_f32(&pSpatializer->directionalAttenuationFactor);
  42318. }
  42319. MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z)
  42320. {
  42321. if (pSpatializer == NULL) {
  42322. return;
  42323. }
  42324. ma_atomic_vec3f_set(&pSpatializer->position, ma_vec3f_init_3f(x, y, z));
  42325. }
  42326. MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer)
  42327. {
  42328. if (pSpatializer == NULL) {
  42329. return ma_vec3f_init_3f(0, 0, 0);
  42330. }
  42331. 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. */
  42332. }
  42333. MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z)
  42334. {
  42335. if (pSpatializer == NULL) {
  42336. return;
  42337. }
  42338. ma_atomic_vec3f_set(&pSpatializer->direction, ma_vec3f_init_3f(x, y, z));
  42339. }
  42340. MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer)
  42341. {
  42342. if (pSpatializer == NULL) {
  42343. return ma_vec3f_init_3f(0, 0, -1);
  42344. }
  42345. 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. */
  42346. }
  42347. MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z)
  42348. {
  42349. if (pSpatializer == NULL) {
  42350. return;
  42351. }
  42352. ma_atomic_vec3f_set(&pSpatializer->velocity, ma_vec3f_init_3f(x, y, z));
  42353. }
  42354. MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer)
  42355. {
  42356. if (pSpatializer == NULL) {
  42357. return ma_vec3f_init_3f(0, 0, 0);
  42358. }
  42359. 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. */
  42360. }
  42361. 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)
  42362. {
  42363. if (pRelativePos != NULL) {
  42364. pRelativePos->x = 0;
  42365. pRelativePos->y = 0;
  42366. pRelativePos->z = 0;
  42367. }
  42368. if (pRelativeDir != NULL) {
  42369. pRelativeDir->x = 0;
  42370. pRelativeDir->y = 0;
  42371. pRelativeDir->z = -1;
  42372. }
  42373. if (pSpatializer == NULL) {
  42374. return;
  42375. }
  42376. if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) {
  42377. /* There's no listener or we're using relative positioning. */
  42378. if (pRelativePos != NULL) {
  42379. *pRelativePos = ma_spatializer_get_position(pSpatializer);
  42380. }
  42381. if (pRelativeDir != NULL) {
  42382. *pRelativeDir = ma_spatializer_get_direction(pSpatializer);
  42383. }
  42384. } else {
  42385. ma_vec3f spatializerPosition;
  42386. ma_vec3f spatializerDirection;
  42387. ma_vec3f listenerPosition;
  42388. ma_vec3f listenerDirection;
  42389. ma_vec3f v;
  42390. ma_vec3f axisX;
  42391. ma_vec3f axisY;
  42392. ma_vec3f axisZ;
  42393. float m[4][4];
  42394. spatializerPosition = ma_spatializer_get_position(pSpatializer);
  42395. spatializerDirection = ma_spatializer_get_direction(pSpatializer);
  42396. listenerPosition = ma_spatializer_listener_get_position(pListener);
  42397. listenerDirection = ma_spatializer_listener_get_direction(pListener);
  42398. /*
  42399. We need to calcualte the right vector from our forward and up vectors. This is done with
  42400. a cross product.
  42401. */
  42402. axisZ = ma_vec3f_normalize(listenerDirection); /* Normalization required here because we can't trust the caller. */
  42403. 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. */
  42404. /*
  42405. The calculation of axisX above can result in a zero-length vector if the listener is
  42406. looking straight up on the Y axis. We'll need to fall back to a +X in this case so that
  42407. the calculations below don't fall apart. This is where a quaternion based listener and
  42408. sound orientation would come in handy.
  42409. */
  42410. if (ma_vec3f_len2(axisX) == 0) {
  42411. axisX = ma_vec3f_init_3f(1, 0, 0);
  42412. }
  42413. axisY = ma_vec3f_cross(axisX, axisZ); /* No normalization is required here because axisX and axisZ are unit length and perpendicular. */
  42414. /*
  42415. We need to swap the X axis if we're left handed because otherwise the cross product above
  42416. will have resulted in it pointing in the wrong direction (right handed was assumed in the
  42417. cross products above).
  42418. */
  42419. if (pListener->config.handedness == ma_handedness_left) {
  42420. axisX = ma_vec3f_neg(axisX);
  42421. }
  42422. /* Lookat. */
  42423. m[0][0] = axisX.x; m[1][0] = axisX.y; m[2][0] = axisX.z; m[3][0] = -ma_vec3f_dot(axisX, listenerPosition);
  42424. m[0][1] = axisY.x; m[1][1] = axisY.y; m[2][1] = axisY.z; m[3][1] = -ma_vec3f_dot(axisY, listenerPosition);
  42425. 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);
  42426. m[0][3] = 0; m[1][3] = 0; m[2][3] = 0; m[3][3] = 1;
  42427. /*
  42428. Multiply the lookat matrix by the spatializer position to transform it to listener
  42429. space. This allows calculations to work based on the sound being relative to the
  42430. origin which makes things simpler.
  42431. */
  42432. if (pRelativePos != NULL) {
  42433. v = spatializerPosition;
  42434. pRelativePos->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z + m[3][0] * 1;
  42435. pRelativePos->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z + m[3][1] * 1;
  42436. pRelativePos->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z + m[3][2] * 1;
  42437. }
  42438. /*
  42439. The direction of the sound needs to also be transformed so that it's relative to the
  42440. rotation of the listener.
  42441. */
  42442. if (pRelativeDir != NULL) {
  42443. v = spatializerDirection;
  42444. pRelativeDir->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z;
  42445. pRelativeDir->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z;
  42446. pRelativeDir->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z;
  42447. }
  42448. }
  42449. }
  42450. /**************************************************************************************************************************************************************
  42451. Resampling
  42452. **************************************************************************************************************************************************************/
  42453. MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  42454. {
  42455. ma_linear_resampler_config config;
  42456. MA_ZERO_OBJECT(&config);
  42457. config.format = format;
  42458. config.channels = channels;
  42459. config.sampleRateIn = sampleRateIn;
  42460. config.sampleRateOut = sampleRateOut;
  42461. config.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  42462. config.lpfNyquistFactor = 1;
  42463. return config;
  42464. }
  42465. typedef struct
  42466. {
  42467. size_t sizeInBytes;
  42468. size_t x0Offset;
  42469. size_t x1Offset;
  42470. size_t lpfOffset;
  42471. } ma_linear_resampler_heap_layout;
  42472. static void ma_linear_resampler_adjust_timer_for_new_rate(ma_linear_resampler* pResampler, ma_uint32 oldSampleRateOut, ma_uint32 newSampleRateOut)
  42473. {
  42474. /*
  42475. 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
  42476. be based on the old sample rate, but we are needing to adjust it to that it's based on the new sample rate.
  42477. */
  42478. 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. */
  42479. ma_uint32 oldRateTimeFract = pResampler->inTimeFrac % oldSampleRateOut;
  42480. pResampler->inTimeFrac =
  42481. (oldRateTimeWhole * newSampleRateOut) +
  42482. ((oldRateTimeFract * newSampleRateOut) / oldSampleRateOut);
  42483. /* Make sure the fractional part is less than the output sample rate. */
  42484. pResampler->inTimeInt += pResampler->inTimeFrac / pResampler->config.sampleRateOut;
  42485. pResampler->inTimeFrac = pResampler->inTimeFrac % pResampler->config.sampleRateOut;
  42486. }
  42487. 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)
  42488. {
  42489. ma_result result;
  42490. ma_uint32 gcf;
  42491. ma_uint32 lpfSampleRate;
  42492. double lpfCutoffFrequency;
  42493. ma_lpf_config lpfConfig;
  42494. ma_uint32 oldSampleRateOut; /* Required for adjusting time advance down the bottom. */
  42495. if (pResampler == NULL) {
  42496. return MA_INVALID_ARGS;
  42497. }
  42498. if (sampleRateIn == 0 || sampleRateOut == 0) {
  42499. return MA_INVALID_ARGS;
  42500. }
  42501. oldSampleRateOut = pResampler->config.sampleRateOut;
  42502. pResampler->config.sampleRateIn = sampleRateIn;
  42503. pResampler->config.sampleRateOut = sampleRateOut;
  42504. /* Simplify the sample rate. */
  42505. gcf = ma_gcf_u32(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut);
  42506. pResampler->config.sampleRateIn /= gcf;
  42507. pResampler->config.sampleRateOut /= gcf;
  42508. /* Always initialize the low-pass filter, even when the order is 0. */
  42509. if (pResampler->config.lpfOrder > MA_MAX_FILTER_ORDER) {
  42510. return MA_INVALID_ARGS;
  42511. }
  42512. lpfSampleRate = (ma_uint32)(ma_max(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut));
  42513. lpfCutoffFrequency = ( double)(ma_min(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut) * 0.5 * pResampler->config.lpfNyquistFactor);
  42514. lpfConfig = ma_lpf_config_init(pResampler->config.format, pResampler->config.channels, lpfSampleRate, lpfCutoffFrequency, pResampler->config.lpfOrder);
  42515. /*
  42516. 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
  42517. getting cleared. Instead we re-initialize the filter which will maintain any cached frames.
  42518. */
  42519. if (isResamplerAlreadyInitialized) {
  42520. result = ma_lpf_reinit(&lpfConfig, &pResampler->lpf);
  42521. } else {
  42522. result = ma_lpf_init_preallocated(&lpfConfig, ma_offset_ptr(pHeap, pHeapLayout->lpfOffset), &pResampler->lpf);
  42523. }
  42524. if (result != MA_SUCCESS) {
  42525. return result;
  42526. }
  42527. pResampler->inAdvanceInt = pResampler->config.sampleRateIn / pResampler->config.sampleRateOut;
  42528. pResampler->inAdvanceFrac = pResampler->config.sampleRateIn % pResampler->config.sampleRateOut;
  42529. /* Our timer was based on the old rate. We need to adjust it so that it's based on the new rate. */
  42530. ma_linear_resampler_adjust_timer_for_new_rate(pResampler, oldSampleRateOut, pResampler->config.sampleRateOut);
  42531. return MA_SUCCESS;
  42532. }
  42533. static ma_result ma_linear_resampler_get_heap_layout(const ma_linear_resampler_config* pConfig, ma_linear_resampler_heap_layout* pHeapLayout)
  42534. {
  42535. MA_ASSERT(pHeapLayout != NULL);
  42536. MA_ZERO_OBJECT(pHeapLayout);
  42537. if (pConfig == NULL) {
  42538. return MA_INVALID_ARGS;
  42539. }
  42540. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  42541. return MA_INVALID_ARGS;
  42542. }
  42543. if (pConfig->channels == 0) {
  42544. return MA_INVALID_ARGS;
  42545. }
  42546. pHeapLayout->sizeInBytes = 0;
  42547. /* x0 */
  42548. pHeapLayout->x0Offset = pHeapLayout->sizeInBytes;
  42549. if (pConfig->format == ma_format_f32) {
  42550. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  42551. } else {
  42552. pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels;
  42553. }
  42554. /* x1 */
  42555. pHeapLayout->x1Offset = pHeapLayout->sizeInBytes;
  42556. if (pConfig->format == ma_format_f32) {
  42557. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  42558. } else {
  42559. pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels;
  42560. }
  42561. /* LPF */
  42562. pHeapLayout->lpfOffset = ma_align_64(pHeapLayout->sizeInBytes);
  42563. {
  42564. ma_result result;
  42565. size_t lpfHeapSizeInBytes;
  42566. ma_lpf_config lpfConfig = ma_lpf_config_init(pConfig->format, pConfig->channels, 1, 1, pConfig->lpfOrder); /* Sample rate and cutoff frequency do not matter. */
  42567. result = ma_lpf_get_heap_size(&lpfConfig, &lpfHeapSizeInBytes);
  42568. if (result != MA_SUCCESS) {
  42569. return result;
  42570. }
  42571. pHeapLayout->sizeInBytes += lpfHeapSizeInBytes;
  42572. }
  42573. /* Make sure allocation size is aligned. */
  42574. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  42575. return MA_SUCCESS;
  42576. }
  42577. MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  42578. {
  42579. ma_result result;
  42580. ma_linear_resampler_heap_layout heapLayout;
  42581. if (pHeapSizeInBytes == NULL) {
  42582. return MA_INVALID_ARGS;
  42583. }
  42584. *pHeapSizeInBytes = 0;
  42585. result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout);
  42586. if (result != MA_SUCCESS) {
  42587. return result;
  42588. }
  42589. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  42590. return MA_SUCCESS;
  42591. }
  42592. MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler)
  42593. {
  42594. ma_result result;
  42595. ma_linear_resampler_heap_layout heapLayout;
  42596. if (pResampler == NULL) {
  42597. return MA_INVALID_ARGS;
  42598. }
  42599. MA_ZERO_OBJECT(pResampler);
  42600. result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout);
  42601. if (result != MA_SUCCESS) {
  42602. return result;
  42603. }
  42604. pResampler->config = *pConfig;
  42605. pResampler->_pHeap = pHeap;
  42606. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  42607. if (pConfig->format == ma_format_f32) {
  42608. pResampler->x0.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x0Offset);
  42609. pResampler->x1.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x1Offset);
  42610. } else {
  42611. pResampler->x0.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x0Offset);
  42612. pResampler->x1.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x1Offset);
  42613. }
  42614. /* Setting the rate will set up the filter and time advances for us. */
  42615. result = ma_linear_resampler_set_rate_internal(pResampler, pHeap, &heapLayout, pConfig->sampleRateIn, pConfig->sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_FALSE);
  42616. if (result != MA_SUCCESS) {
  42617. return result;
  42618. }
  42619. pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
  42620. pResampler->inTimeFrac = 0;
  42621. return MA_SUCCESS;
  42622. }
  42623. MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler)
  42624. {
  42625. ma_result result;
  42626. size_t heapSizeInBytes;
  42627. void* pHeap;
  42628. result = ma_linear_resampler_get_heap_size(pConfig, &heapSizeInBytes);
  42629. if (result != MA_SUCCESS) {
  42630. return result;
  42631. }
  42632. if (heapSizeInBytes > 0) {
  42633. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  42634. if (pHeap == NULL) {
  42635. return MA_OUT_OF_MEMORY;
  42636. }
  42637. } else {
  42638. pHeap = NULL;
  42639. }
  42640. result = ma_linear_resampler_init_preallocated(pConfig, pHeap, pResampler);
  42641. if (result != MA_SUCCESS) {
  42642. ma_free(pHeap, pAllocationCallbacks);
  42643. return result;
  42644. }
  42645. pResampler->_ownsHeap = MA_TRUE;
  42646. return MA_SUCCESS;
  42647. }
  42648. MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks)
  42649. {
  42650. if (pResampler == NULL) {
  42651. return;
  42652. }
  42653. ma_lpf_uninit(&pResampler->lpf, pAllocationCallbacks);
  42654. if (pResampler->_ownsHeap) {
  42655. ma_free(pResampler->_pHeap, pAllocationCallbacks);
  42656. }
  42657. }
  42658. static MA_INLINE ma_int16 ma_linear_resampler_mix_s16(ma_int16 x, ma_int16 y, ma_int32 a, const ma_int32 shift)
  42659. {
  42660. ma_int32 b;
  42661. ma_int32 c;
  42662. ma_int32 r;
  42663. MA_ASSERT(a <= (1<<shift));
  42664. b = x * ((1<<shift) - a);
  42665. c = y * a;
  42666. r = b + c;
  42667. return (ma_int16)(r >> shift);
  42668. }
  42669. static void ma_linear_resampler_interpolate_frame_s16(ma_linear_resampler* pResampler, ma_int16* MA_RESTRICT pFrameOut)
  42670. {
  42671. ma_uint32 c;
  42672. ma_uint32 a;
  42673. const ma_uint32 channels = pResampler->config.channels;
  42674. const ma_uint32 shift = 12;
  42675. MA_ASSERT(pResampler != NULL);
  42676. MA_ASSERT(pFrameOut != NULL);
  42677. a = (pResampler->inTimeFrac << shift) / pResampler->config.sampleRateOut;
  42678. MA_ASSUME(channels > 0);
  42679. for (c = 0; c < channels; c += 1) {
  42680. ma_int16 s = ma_linear_resampler_mix_s16(pResampler->x0.s16[c], pResampler->x1.s16[c], a, shift);
  42681. pFrameOut[c] = s;
  42682. }
  42683. }
  42684. static void ma_linear_resampler_interpolate_frame_f32(ma_linear_resampler* pResampler, float* MA_RESTRICT pFrameOut)
  42685. {
  42686. ma_uint32 c;
  42687. float a;
  42688. const ma_uint32 channels = pResampler->config.channels;
  42689. MA_ASSERT(pResampler != NULL);
  42690. MA_ASSERT(pFrameOut != NULL);
  42691. a = (float)pResampler->inTimeFrac / pResampler->config.sampleRateOut;
  42692. MA_ASSUME(channels > 0);
  42693. for (c = 0; c < channels; c += 1) {
  42694. float s = ma_mix_f32_fast(pResampler->x0.f32[c], pResampler->x1.f32[c], a);
  42695. pFrameOut[c] = s;
  42696. }
  42697. }
  42698. 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)
  42699. {
  42700. const ma_int16* pFramesInS16;
  42701. /* */ ma_int16* pFramesOutS16;
  42702. ma_uint64 frameCountIn;
  42703. ma_uint64 frameCountOut;
  42704. ma_uint64 framesProcessedIn;
  42705. ma_uint64 framesProcessedOut;
  42706. MA_ASSERT(pResampler != NULL);
  42707. MA_ASSERT(pFrameCountIn != NULL);
  42708. MA_ASSERT(pFrameCountOut != NULL);
  42709. pFramesInS16 = (const ma_int16*)pFramesIn;
  42710. pFramesOutS16 = ( ma_int16*)pFramesOut;
  42711. frameCountIn = *pFrameCountIn;
  42712. frameCountOut = *pFrameCountOut;
  42713. framesProcessedIn = 0;
  42714. framesProcessedOut = 0;
  42715. while (framesProcessedOut < frameCountOut) {
  42716. /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
  42717. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42718. ma_uint32 iChannel;
  42719. if (pFramesInS16 != NULL) {
  42720. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42721. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42722. pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
  42723. }
  42724. pFramesInS16 += pResampler->config.channels;
  42725. } else {
  42726. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42727. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42728. pResampler->x1.s16[iChannel] = 0;
  42729. }
  42730. }
  42731. /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */
  42732. if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) {
  42733. ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pResampler->x1.s16, pResampler->x1.s16);
  42734. }
  42735. framesProcessedIn += 1;
  42736. pResampler->inTimeInt -= 1;
  42737. }
  42738. if (pResampler->inTimeInt > 0) {
  42739. break; /* Ran out of input data. */
  42740. }
  42741. /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
  42742. if (pFramesOutS16 != NULL) {
  42743. MA_ASSERT(pResampler->inTimeInt == 0);
  42744. ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
  42745. pFramesOutS16 += pResampler->config.channels;
  42746. }
  42747. framesProcessedOut += 1;
  42748. /* Advance time forward. */
  42749. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42750. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42751. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42752. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42753. pResampler->inTimeInt += 1;
  42754. }
  42755. }
  42756. *pFrameCountIn = framesProcessedIn;
  42757. *pFrameCountOut = framesProcessedOut;
  42758. return MA_SUCCESS;
  42759. }
  42760. 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)
  42761. {
  42762. const ma_int16* pFramesInS16;
  42763. /* */ ma_int16* pFramesOutS16;
  42764. ma_uint64 frameCountIn;
  42765. ma_uint64 frameCountOut;
  42766. ma_uint64 framesProcessedIn;
  42767. ma_uint64 framesProcessedOut;
  42768. MA_ASSERT(pResampler != NULL);
  42769. MA_ASSERT(pFrameCountIn != NULL);
  42770. MA_ASSERT(pFrameCountOut != NULL);
  42771. pFramesInS16 = (const ma_int16*)pFramesIn;
  42772. pFramesOutS16 = ( ma_int16*)pFramesOut;
  42773. frameCountIn = *pFrameCountIn;
  42774. frameCountOut = *pFrameCountOut;
  42775. framesProcessedIn = 0;
  42776. framesProcessedOut = 0;
  42777. while (framesProcessedOut < frameCountOut) {
  42778. /* Before interpolating we need to load the buffers. */
  42779. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42780. ma_uint32 iChannel;
  42781. if (pFramesInS16 != NULL) {
  42782. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42783. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42784. pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
  42785. }
  42786. pFramesInS16 += pResampler->config.channels;
  42787. } else {
  42788. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42789. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  42790. pResampler->x1.s16[iChannel] = 0;
  42791. }
  42792. }
  42793. framesProcessedIn += 1;
  42794. pResampler->inTimeInt -= 1;
  42795. }
  42796. if (pResampler->inTimeInt > 0) {
  42797. break; /* Ran out of input data. */
  42798. }
  42799. /* Getting here means the frames have been loaded and we can generate the next output frame. */
  42800. if (pFramesOutS16 != NULL) {
  42801. MA_ASSERT(pResampler->inTimeInt == 0);
  42802. ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
  42803. /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */
  42804. if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) {
  42805. ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pFramesOutS16, pFramesOutS16);
  42806. }
  42807. pFramesOutS16 += pResampler->config.channels;
  42808. }
  42809. framesProcessedOut += 1;
  42810. /* Advance time forward. */
  42811. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42812. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42813. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42814. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42815. pResampler->inTimeInt += 1;
  42816. }
  42817. }
  42818. *pFrameCountIn = framesProcessedIn;
  42819. *pFrameCountOut = framesProcessedOut;
  42820. return MA_SUCCESS;
  42821. }
  42822. 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)
  42823. {
  42824. MA_ASSERT(pResampler != NULL);
  42825. if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
  42826. return ma_linear_resampler_process_pcm_frames_s16_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42827. } else {
  42828. return ma_linear_resampler_process_pcm_frames_s16_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42829. }
  42830. }
  42831. 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)
  42832. {
  42833. const float* pFramesInF32;
  42834. /* */ float* pFramesOutF32;
  42835. ma_uint64 frameCountIn;
  42836. ma_uint64 frameCountOut;
  42837. ma_uint64 framesProcessedIn;
  42838. ma_uint64 framesProcessedOut;
  42839. MA_ASSERT(pResampler != NULL);
  42840. MA_ASSERT(pFrameCountIn != NULL);
  42841. MA_ASSERT(pFrameCountOut != NULL);
  42842. pFramesInF32 = (const float*)pFramesIn;
  42843. pFramesOutF32 = ( float*)pFramesOut;
  42844. frameCountIn = *pFrameCountIn;
  42845. frameCountOut = *pFrameCountOut;
  42846. framesProcessedIn = 0;
  42847. framesProcessedOut = 0;
  42848. while (framesProcessedOut < frameCountOut) {
  42849. /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
  42850. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42851. ma_uint32 iChannel;
  42852. if (pFramesInF32 != NULL) {
  42853. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42854. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42855. pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
  42856. }
  42857. pFramesInF32 += pResampler->config.channels;
  42858. } else {
  42859. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42860. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42861. pResampler->x1.f32[iChannel] = 0;
  42862. }
  42863. }
  42864. /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */
  42865. if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) {
  42866. ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pResampler->x1.f32, pResampler->x1.f32);
  42867. }
  42868. framesProcessedIn += 1;
  42869. pResampler->inTimeInt -= 1;
  42870. }
  42871. if (pResampler->inTimeInt > 0) {
  42872. break; /* Ran out of input data. */
  42873. }
  42874. /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
  42875. if (pFramesOutF32 != NULL) {
  42876. MA_ASSERT(pResampler->inTimeInt == 0);
  42877. ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
  42878. pFramesOutF32 += pResampler->config.channels;
  42879. }
  42880. framesProcessedOut += 1;
  42881. /* Advance time forward. */
  42882. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42883. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42884. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42885. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42886. pResampler->inTimeInt += 1;
  42887. }
  42888. }
  42889. *pFrameCountIn = framesProcessedIn;
  42890. *pFrameCountOut = framesProcessedOut;
  42891. return MA_SUCCESS;
  42892. }
  42893. 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)
  42894. {
  42895. const float* pFramesInF32;
  42896. /* */ float* pFramesOutF32;
  42897. ma_uint64 frameCountIn;
  42898. ma_uint64 frameCountOut;
  42899. ma_uint64 framesProcessedIn;
  42900. ma_uint64 framesProcessedOut;
  42901. MA_ASSERT(pResampler != NULL);
  42902. MA_ASSERT(pFrameCountIn != NULL);
  42903. MA_ASSERT(pFrameCountOut != NULL);
  42904. pFramesInF32 = (const float*)pFramesIn;
  42905. pFramesOutF32 = ( float*)pFramesOut;
  42906. frameCountIn = *pFrameCountIn;
  42907. frameCountOut = *pFrameCountOut;
  42908. framesProcessedIn = 0;
  42909. framesProcessedOut = 0;
  42910. while (framesProcessedOut < frameCountOut) {
  42911. /* Before interpolating we need to load the buffers. */
  42912. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  42913. ma_uint32 iChannel;
  42914. if (pFramesInF32 != NULL) {
  42915. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42916. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42917. pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
  42918. }
  42919. pFramesInF32 += pResampler->config.channels;
  42920. } else {
  42921. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  42922. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  42923. pResampler->x1.f32[iChannel] = 0;
  42924. }
  42925. }
  42926. framesProcessedIn += 1;
  42927. pResampler->inTimeInt -= 1;
  42928. }
  42929. if (pResampler->inTimeInt > 0) {
  42930. break; /* Ran out of input data. */
  42931. }
  42932. /* Getting here means the frames have been loaded and we can generate the next output frame. */
  42933. if (pFramesOutF32 != NULL) {
  42934. MA_ASSERT(pResampler->inTimeInt == 0);
  42935. ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
  42936. /* Filter. Do not apply filtering if sample rates are the same or else you'll get dangerous glitching. */
  42937. if (pResampler->config.sampleRateIn != pResampler->config.sampleRateOut) {
  42938. ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pFramesOutF32, pFramesOutF32);
  42939. }
  42940. pFramesOutF32 += pResampler->config.channels;
  42941. }
  42942. framesProcessedOut += 1;
  42943. /* Advance time forward. */
  42944. pResampler->inTimeInt += pResampler->inAdvanceInt;
  42945. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  42946. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  42947. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  42948. pResampler->inTimeInt += 1;
  42949. }
  42950. }
  42951. *pFrameCountIn = framesProcessedIn;
  42952. *pFrameCountOut = framesProcessedOut;
  42953. return MA_SUCCESS;
  42954. }
  42955. 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)
  42956. {
  42957. MA_ASSERT(pResampler != NULL);
  42958. if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
  42959. return ma_linear_resampler_process_pcm_frames_f32_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42960. } else {
  42961. return ma_linear_resampler_process_pcm_frames_f32_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42962. }
  42963. }
  42964. 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)
  42965. {
  42966. if (pResampler == NULL) {
  42967. return MA_INVALID_ARGS;
  42968. }
  42969. /* */ if (pResampler->config.format == ma_format_s16) {
  42970. return ma_linear_resampler_process_pcm_frames_s16(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42971. } else if (pResampler->config.format == ma_format_f32) {
  42972. return ma_linear_resampler_process_pcm_frames_f32(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42973. } else {
  42974. /* 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(). */
  42975. MA_ASSERT(MA_FALSE);
  42976. return MA_INVALID_ARGS;
  42977. }
  42978. }
  42979. MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  42980. {
  42981. return ma_linear_resampler_set_rate_internal(pResampler, NULL, NULL, sampleRateIn, sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_TRUE);
  42982. }
  42983. MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut)
  42984. {
  42985. ma_uint32 n;
  42986. ma_uint32 d;
  42987. if (pResampler == NULL) {
  42988. return MA_INVALID_ARGS;
  42989. }
  42990. if (ratioInOut <= 0) {
  42991. return MA_INVALID_ARGS;
  42992. }
  42993. d = 1000000;
  42994. n = (ma_uint32)(ratioInOut * d);
  42995. if (n == 0) {
  42996. return MA_INVALID_ARGS; /* Ratio too small. */
  42997. }
  42998. MA_ASSERT(n != 0);
  42999. return ma_linear_resampler_set_rate(pResampler, n, d);
  43000. }
  43001. MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler)
  43002. {
  43003. if (pResampler == NULL) {
  43004. return 0;
  43005. }
  43006. return 1 + ma_lpf_get_latency(&pResampler->lpf);
  43007. }
  43008. MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler)
  43009. {
  43010. if (pResampler == NULL) {
  43011. return 0;
  43012. }
  43013. return ma_linear_resampler_get_input_latency(pResampler) * pResampler->config.sampleRateOut / pResampler->config.sampleRateIn;
  43014. }
  43015. MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  43016. {
  43017. ma_uint64 inputFrameCount;
  43018. if (pInputFrameCount == NULL) {
  43019. return MA_INVALID_ARGS;
  43020. }
  43021. *pInputFrameCount = 0;
  43022. if (pResampler == NULL) {
  43023. return MA_INVALID_ARGS;
  43024. }
  43025. if (outputFrameCount == 0) {
  43026. return MA_SUCCESS;
  43027. }
  43028. /* Any whole input frames are consumed before the first output frame is generated. */
  43029. inputFrameCount = pResampler->inTimeInt;
  43030. outputFrameCount -= 1;
  43031. /* The rest of the output frames can be calculated in constant time. */
  43032. inputFrameCount += outputFrameCount * pResampler->inAdvanceInt;
  43033. inputFrameCount += (pResampler->inTimeFrac + (outputFrameCount * pResampler->inAdvanceFrac)) / pResampler->config.sampleRateOut;
  43034. *pInputFrameCount = inputFrameCount;
  43035. return MA_SUCCESS;
  43036. }
  43037. MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  43038. {
  43039. ma_uint64 outputFrameCount;
  43040. ma_uint64 preliminaryInputFrameCountFromFrac;
  43041. ma_uint64 preliminaryInputFrameCount;
  43042. if (pOutputFrameCount == NULL) {
  43043. return MA_INVALID_ARGS;
  43044. }
  43045. *pOutputFrameCount = 0;
  43046. if (pResampler == NULL) {
  43047. return MA_INVALID_ARGS;
  43048. }
  43049. /*
  43050. 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
  43051. 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
  43052. 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
  43053. of an extra output frame. This add-by-one logic is necessary due to how the data loading logic works when processing frames.
  43054. */
  43055. outputFrameCount = (inputFrameCount * pResampler->config.sampleRateOut) / pResampler->config.sampleRateIn;
  43056. /*
  43057. We need to determine how many *whole* input frames will have been processed to generate our preliminary output frame count. This is
  43058. used in the logic below to determine whether or not we need to add an extra output frame.
  43059. */
  43060. preliminaryInputFrameCountFromFrac = (pResampler->inTimeFrac + outputFrameCount*pResampler->inAdvanceFrac) / pResampler->config.sampleRateOut;
  43061. preliminaryInputFrameCount = (pResampler->inTimeInt + outputFrameCount*pResampler->inAdvanceInt ) + preliminaryInputFrameCountFromFrac;
  43062. /*
  43063. If the total number of *whole* input frames that would be required to generate our preliminary output frame count is greather than
  43064. 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
  43065. to actually process. Otherwise we need to add the extra output frame.
  43066. */
  43067. if (preliminaryInputFrameCount <= inputFrameCount) {
  43068. outputFrameCount += 1;
  43069. }
  43070. *pOutputFrameCount = outputFrameCount;
  43071. return MA_SUCCESS;
  43072. }
  43073. MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler)
  43074. {
  43075. ma_uint32 iChannel;
  43076. if (pResampler == NULL) {
  43077. return MA_INVALID_ARGS;
  43078. }
  43079. /* Timers need to be cleared back to zero. */
  43080. pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
  43081. pResampler->inTimeFrac = 0;
  43082. /* Cached samples need to be cleared. */
  43083. if (pResampler->config.format == ma_format_f32) {
  43084. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  43085. pResampler->x0.f32[iChannel] = 0;
  43086. pResampler->x1.f32[iChannel] = 0;
  43087. }
  43088. } else {
  43089. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  43090. pResampler->x0.s16[iChannel] = 0;
  43091. pResampler->x1.s16[iChannel] = 0;
  43092. }
  43093. }
  43094. /* The low pass filter needs to have it's cache reset. */
  43095. ma_lpf_clear_cache(&pResampler->lpf);
  43096. return MA_SUCCESS;
  43097. }
  43098. /* Linear resampler backend vtable. */
  43099. static ma_linear_resampler_config ma_resampling_backend_get_config__linear(const ma_resampler_config* pConfig)
  43100. {
  43101. ma_linear_resampler_config linearConfig;
  43102. linearConfig = ma_linear_resampler_config_init(pConfig->format, pConfig->channels, pConfig->sampleRateIn, pConfig->sampleRateOut);
  43103. linearConfig.lpfOrder = pConfig->linear.lpfOrder;
  43104. return linearConfig;
  43105. }
  43106. static ma_result ma_resampling_backend_get_heap_size__linear(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  43107. {
  43108. ma_linear_resampler_config linearConfig;
  43109. (void)pUserData;
  43110. linearConfig = ma_resampling_backend_get_config__linear(pConfig);
  43111. return ma_linear_resampler_get_heap_size(&linearConfig, pHeapSizeInBytes);
  43112. }
  43113. static ma_result ma_resampling_backend_init__linear(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend)
  43114. {
  43115. ma_resampler* pResampler = (ma_resampler*)pUserData;
  43116. ma_result result;
  43117. ma_linear_resampler_config linearConfig;
  43118. (void)pUserData;
  43119. linearConfig = ma_resampling_backend_get_config__linear(pConfig);
  43120. result = ma_linear_resampler_init_preallocated(&linearConfig, pHeap, &pResampler->state.linear);
  43121. if (result != MA_SUCCESS) {
  43122. return result;
  43123. }
  43124. *ppBackend = &pResampler->state.linear;
  43125. return MA_SUCCESS;
  43126. }
  43127. static void ma_resampling_backend_uninit__linear(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  43128. {
  43129. (void)pUserData;
  43130. ma_linear_resampler_uninit((ma_linear_resampler*)pBackend, pAllocationCallbacks);
  43131. }
  43132. 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)
  43133. {
  43134. (void)pUserData;
  43135. return ma_linear_resampler_process_pcm_frames((ma_linear_resampler*)pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  43136. }
  43137. static ma_result ma_resampling_backend_set_rate__linear(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  43138. {
  43139. (void)pUserData;
  43140. return ma_linear_resampler_set_rate((ma_linear_resampler*)pBackend, sampleRateIn, sampleRateOut);
  43141. }
  43142. static ma_uint64 ma_resampling_backend_get_input_latency__linear(void* pUserData, const ma_resampling_backend* pBackend)
  43143. {
  43144. (void)pUserData;
  43145. return ma_linear_resampler_get_input_latency((const ma_linear_resampler*)pBackend);
  43146. }
  43147. static ma_uint64 ma_resampling_backend_get_output_latency__linear(void* pUserData, const ma_resampling_backend* pBackend)
  43148. {
  43149. (void)pUserData;
  43150. return ma_linear_resampler_get_output_latency((const ma_linear_resampler*)pBackend);
  43151. }
  43152. 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)
  43153. {
  43154. (void)pUserData;
  43155. return ma_linear_resampler_get_required_input_frame_count((const ma_linear_resampler*)pBackend, outputFrameCount, pInputFrameCount);
  43156. }
  43157. 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)
  43158. {
  43159. (void)pUserData;
  43160. return ma_linear_resampler_get_expected_output_frame_count((const ma_linear_resampler*)pBackend, inputFrameCount, pOutputFrameCount);
  43161. }
  43162. static ma_result ma_resampling_backend_reset__linear(void* pUserData, ma_resampling_backend* pBackend)
  43163. {
  43164. (void)pUserData;
  43165. return ma_linear_resampler_reset((ma_linear_resampler*)pBackend);
  43166. }
  43167. static ma_resampling_backend_vtable g_ma_linear_resampler_vtable =
  43168. {
  43169. ma_resampling_backend_get_heap_size__linear,
  43170. ma_resampling_backend_init__linear,
  43171. ma_resampling_backend_uninit__linear,
  43172. ma_resampling_backend_process__linear,
  43173. ma_resampling_backend_set_rate__linear,
  43174. ma_resampling_backend_get_input_latency__linear,
  43175. ma_resampling_backend_get_output_latency__linear,
  43176. ma_resampling_backend_get_required_input_frame_count__linear,
  43177. ma_resampling_backend_get_expected_output_frame_count__linear,
  43178. ma_resampling_backend_reset__linear
  43179. };
  43180. 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)
  43181. {
  43182. ma_resampler_config config;
  43183. MA_ZERO_OBJECT(&config);
  43184. config.format = format;
  43185. config.channels = channels;
  43186. config.sampleRateIn = sampleRateIn;
  43187. config.sampleRateOut = sampleRateOut;
  43188. config.algorithm = algorithm;
  43189. /* Linear. */
  43190. config.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  43191. return config;
  43192. }
  43193. static ma_result ma_resampler_get_vtable(const ma_resampler_config* pConfig, ma_resampler* pResampler, ma_resampling_backend_vtable** ppVTable, void** ppUserData)
  43194. {
  43195. MA_ASSERT(pConfig != NULL);
  43196. MA_ASSERT(ppVTable != NULL);
  43197. MA_ASSERT(ppUserData != NULL);
  43198. /* Safety. */
  43199. *ppVTable = NULL;
  43200. *ppUserData = NULL;
  43201. switch (pConfig->algorithm)
  43202. {
  43203. case ma_resample_algorithm_linear:
  43204. {
  43205. *ppVTable = &g_ma_linear_resampler_vtable;
  43206. *ppUserData = pResampler;
  43207. } break;
  43208. case ma_resample_algorithm_custom:
  43209. {
  43210. *ppVTable = pConfig->pBackendVTable;
  43211. *ppUserData = pConfig->pBackendUserData;
  43212. } break;
  43213. default: return MA_INVALID_ARGS;
  43214. }
  43215. return MA_SUCCESS;
  43216. }
  43217. MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  43218. {
  43219. ma_result result;
  43220. ma_resampling_backend_vtable* pVTable;
  43221. void* pVTableUserData;
  43222. if (pHeapSizeInBytes == NULL) {
  43223. return MA_INVALID_ARGS;
  43224. }
  43225. *pHeapSizeInBytes = 0;
  43226. if (pConfig == NULL) {
  43227. return MA_INVALID_ARGS;
  43228. }
  43229. result = ma_resampler_get_vtable(pConfig, NULL, &pVTable, &pVTableUserData);
  43230. if (result != MA_SUCCESS) {
  43231. return result;
  43232. }
  43233. if (pVTable == NULL || pVTable->onGetHeapSize == NULL) {
  43234. return MA_NOT_IMPLEMENTED;
  43235. }
  43236. result = pVTable->onGetHeapSize(pVTableUserData, pConfig, pHeapSizeInBytes);
  43237. if (result != MA_SUCCESS) {
  43238. return result;
  43239. }
  43240. return MA_SUCCESS;
  43241. }
  43242. MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler)
  43243. {
  43244. ma_result result;
  43245. if (pResampler == NULL) {
  43246. return MA_INVALID_ARGS;
  43247. }
  43248. MA_ZERO_OBJECT(pResampler);
  43249. if (pConfig == NULL) {
  43250. return MA_INVALID_ARGS;
  43251. }
  43252. pResampler->_pHeap = pHeap;
  43253. pResampler->format = pConfig->format;
  43254. pResampler->channels = pConfig->channels;
  43255. pResampler->sampleRateIn = pConfig->sampleRateIn;
  43256. pResampler->sampleRateOut = pConfig->sampleRateOut;
  43257. result = ma_resampler_get_vtable(pConfig, pResampler, &pResampler->pBackendVTable, &pResampler->pBackendUserData);
  43258. if (result != MA_SUCCESS) {
  43259. return result;
  43260. }
  43261. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onInit == NULL) {
  43262. return MA_NOT_IMPLEMENTED; /* onInit not implemented. */
  43263. }
  43264. result = pResampler->pBackendVTable->onInit(pResampler->pBackendUserData, pConfig, pHeap, &pResampler->pBackend);
  43265. if (result != MA_SUCCESS) {
  43266. return result;
  43267. }
  43268. return MA_SUCCESS;
  43269. }
  43270. MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler)
  43271. {
  43272. ma_result result;
  43273. size_t heapSizeInBytes;
  43274. void* pHeap;
  43275. result = ma_resampler_get_heap_size(pConfig, &heapSizeInBytes);
  43276. if (result != MA_SUCCESS) {
  43277. return result;
  43278. }
  43279. if (heapSizeInBytes > 0) {
  43280. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  43281. if (pHeap == NULL) {
  43282. return MA_OUT_OF_MEMORY;
  43283. }
  43284. } else {
  43285. pHeap = NULL;
  43286. }
  43287. result = ma_resampler_init_preallocated(pConfig, pHeap, pResampler);
  43288. if (result != MA_SUCCESS) {
  43289. ma_free(pHeap, pAllocationCallbacks);
  43290. return result;
  43291. }
  43292. pResampler->_ownsHeap = MA_TRUE;
  43293. return MA_SUCCESS;
  43294. }
  43295. MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks)
  43296. {
  43297. if (pResampler == NULL) {
  43298. return;
  43299. }
  43300. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onUninit == NULL) {
  43301. return;
  43302. }
  43303. pResampler->pBackendVTable->onUninit(pResampler->pBackendUserData, pResampler->pBackend, pAllocationCallbacks);
  43304. if (pResampler->_ownsHeap) {
  43305. ma_free(pResampler->_pHeap, pAllocationCallbacks);
  43306. }
  43307. }
  43308. MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  43309. {
  43310. if (pResampler == NULL) {
  43311. return MA_INVALID_ARGS;
  43312. }
  43313. if (pFrameCountOut == NULL && pFrameCountIn == NULL) {
  43314. return MA_INVALID_ARGS;
  43315. }
  43316. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onProcess == NULL) {
  43317. return MA_NOT_IMPLEMENTED;
  43318. }
  43319. return pResampler->pBackendVTable->onProcess(pResampler->pBackendUserData, pResampler->pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  43320. }
  43321. MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  43322. {
  43323. ma_result result;
  43324. if (pResampler == NULL) {
  43325. return MA_INVALID_ARGS;
  43326. }
  43327. if (sampleRateIn == 0 || sampleRateOut == 0) {
  43328. return MA_INVALID_ARGS;
  43329. }
  43330. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onSetRate == NULL) {
  43331. return MA_NOT_IMPLEMENTED;
  43332. }
  43333. result = pResampler->pBackendVTable->onSetRate(pResampler->pBackendUserData, pResampler->pBackend, sampleRateIn, sampleRateOut);
  43334. if (result != MA_SUCCESS) {
  43335. return result;
  43336. }
  43337. pResampler->sampleRateIn = sampleRateIn;
  43338. pResampler->sampleRateOut = sampleRateOut;
  43339. return MA_SUCCESS;
  43340. }
  43341. MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio)
  43342. {
  43343. ma_uint32 n;
  43344. ma_uint32 d;
  43345. if (pResampler == NULL) {
  43346. return MA_INVALID_ARGS;
  43347. }
  43348. if (ratio <= 0) {
  43349. return MA_INVALID_ARGS;
  43350. }
  43351. d = 1000;
  43352. n = (ma_uint32)(ratio * d);
  43353. if (n == 0) {
  43354. return MA_INVALID_ARGS; /* Ratio too small. */
  43355. }
  43356. MA_ASSERT(n != 0);
  43357. return ma_resampler_set_rate(pResampler, n, d);
  43358. }
  43359. MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler)
  43360. {
  43361. if (pResampler == NULL) {
  43362. return 0;
  43363. }
  43364. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetInputLatency == NULL) {
  43365. return 0;
  43366. }
  43367. return pResampler->pBackendVTable->onGetInputLatency(pResampler->pBackendUserData, pResampler->pBackend);
  43368. }
  43369. MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler)
  43370. {
  43371. if (pResampler == NULL) {
  43372. return 0;
  43373. }
  43374. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetOutputLatency == NULL) {
  43375. return 0;
  43376. }
  43377. return pResampler->pBackendVTable->onGetOutputLatency(pResampler->pBackendUserData, pResampler->pBackend);
  43378. }
  43379. MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  43380. {
  43381. if (pInputFrameCount == NULL) {
  43382. return MA_INVALID_ARGS;
  43383. }
  43384. *pInputFrameCount = 0;
  43385. if (pResampler == NULL) {
  43386. return MA_INVALID_ARGS;
  43387. }
  43388. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetRequiredInputFrameCount == NULL) {
  43389. return MA_NOT_IMPLEMENTED;
  43390. }
  43391. return pResampler->pBackendVTable->onGetRequiredInputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, outputFrameCount, pInputFrameCount);
  43392. }
  43393. MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  43394. {
  43395. if (pOutputFrameCount == NULL) {
  43396. return MA_INVALID_ARGS;
  43397. }
  43398. *pOutputFrameCount = 0;
  43399. if (pResampler == NULL) {
  43400. return MA_INVALID_ARGS;
  43401. }
  43402. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetExpectedOutputFrameCount == NULL) {
  43403. return MA_NOT_IMPLEMENTED;
  43404. }
  43405. return pResampler->pBackendVTable->onGetExpectedOutputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, inputFrameCount, pOutputFrameCount);
  43406. }
  43407. MA_API ma_result ma_resampler_reset(ma_resampler* pResampler)
  43408. {
  43409. if (pResampler == NULL) {
  43410. return MA_INVALID_ARGS;
  43411. }
  43412. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onReset == NULL) {
  43413. return MA_NOT_IMPLEMENTED;
  43414. }
  43415. return pResampler->pBackendVTable->onReset(pResampler->pBackendUserData, pResampler->pBackend);
  43416. }
  43417. /**************************************************************************************************************************************************************
  43418. Channel Conversion
  43419. **************************************************************************************************************************************************************/
  43420. #ifndef MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT
  43421. #define MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT 12
  43422. #endif
  43423. #define MA_PLANE_LEFT 0
  43424. #define MA_PLANE_RIGHT 1
  43425. #define MA_PLANE_FRONT 2
  43426. #define MA_PLANE_BACK 3
  43427. #define MA_PLANE_BOTTOM 4
  43428. #define MA_PLANE_TOP 5
  43429. static float g_maChannelPlaneRatios[MA_CHANNEL_POSITION_COUNT][6] = {
  43430. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_NONE */
  43431. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_MONO */
  43432. { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT */
  43433. { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT */
  43434. { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_CENTER */
  43435. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_LFE */
  43436. { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_LEFT */
  43437. { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_RIGHT */
  43438. { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT_CENTER */
  43439. { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT_CENTER */
  43440. { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_CENTER */
  43441. { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_LEFT */
  43442. { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_RIGHT */
  43443. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, /* MA_CHANNEL_TOP_CENTER */
  43444. { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_LEFT */
  43445. { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_FRONT_CENTER */
  43446. { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_RIGHT */
  43447. { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_LEFT */
  43448. { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_BACK_CENTER */
  43449. { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_RIGHT */
  43450. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_0 */
  43451. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_1 */
  43452. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_2 */
  43453. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_3 */
  43454. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_4 */
  43455. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_5 */
  43456. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_6 */
  43457. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_7 */
  43458. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_8 */
  43459. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_9 */
  43460. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_10 */
  43461. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_11 */
  43462. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_12 */
  43463. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_13 */
  43464. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_14 */
  43465. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_15 */
  43466. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_16 */
  43467. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_17 */
  43468. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_18 */
  43469. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_19 */
  43470. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_20 */
  43471. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_21 */
  43472. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_22 */
  43473. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_23 */
  43474. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_24 */
  43475. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_25 */
  43476. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_26 */
  43477. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_27 */
  43478. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_28 */
  43479. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_29 */
  43480. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_30 */
  43481. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_31 */
  43482. };
  43483. static float ma_calculate_channel_position_rectangular_weight(ma_channel channelPositionA, ma_channel channelPositionB)
  43484. {
  43485. /*
  43486. Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to
  43487. the following output configuration:
  43488. - front/left
  43489. - side/left
  43490. - back/left
  43491. The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount
  43492. of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated.
  43493. 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
  43494. 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
  43495. 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
  43496. receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between
  43497. 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
  43498. across 3 spatial dimensions.
  43499. The first thing to do is figure out how each speaker's volume is spread over each of plane:
  43500. - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane
  43501. - side/left: 1 plane (left only) = 1/1 = entire volume from left plane
  43502. - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane
  43503. - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane
  43504. 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
  43505. 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
  43506. taken by the other to produce the final contribution.
  43507. */
  43508. /* Contribution = Sum(Volume to Give * Volume to Take) */
  43509. float contribution =
  43510. g_maChannelPlaneRatios[channelPositionA][0] * g_maChannelPlaneRatios[channelPositionB][0] +
  43511. g_maChannelPlaneRatios[channelPositionA][1] * g_maChannelPlaneRatios[channelPositionB][1] +
  43512. g_maChannelPlaneRatios[channelPositionA][2] * g_maChannelPlaneRatios[channelPositionB][2] +
  43513. g_maChannelPlaneRatios[channelPositionA][3] * g_maChannelPlaneRatios[channelPositionB][3] +
  43514. g_maChannelPlaneRatios[channelPositionA][4] * g_maChannelPlaneRatios[channelPositionB][4] +
  43515. g_maChannelPlaneRatios[channelPositionA][5] * g_maChannelPlaneRatios[channelPositionB][5];
  43516. return contribution;
  43517. }
  43518. 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)
  43519. {
  43520. ma_channel_converter_config config;
  43521. MA_ZERO_OBJECT(&config);
  43522. config.format = format;
  43523. config.channelsIn = channelsIn;
  43524. config.channelsOut = channelsOut;
  43525. config.pChannelMapIn = pChannelMapIn;
  43526. config.pChannelMapOut = pChannelMapOut;
  43527. config.mixingMode = mixingMode;
  43528. return config;
  43529. }
  43530. static ma_int32 ma_channel_converter_float_to_fixed(float x)
  43531. {
  43532. return (ma_int32)(x * (1<<MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT));
  43533. }
  43534. static ma_uint32 ma_channel_map_get_spatial_channel_count(const ma_channel* pChannelMap, ma_uint32 channels)
  43535. {
  43536. ma_uint32 spatialChannelCount = 0;
  43537. ma_uint32 iChannel;
  43538. MA_ASSERT(pChannelMap != NULL);
  43539. MA_ASSERT(channels > 0);
  43540. for (iChannel = 0; iChannel < channels; ++iChannel) {
  43541. if (ma_is_spatial_channel_position(ma_channel_map_get_channel(pChannelMap, channels, iChannel))) {
  43542. spatialChannelCount++;
  43543. }
  43544. }
  43545. return spatialChannelCount;
  43546. }
  43547. static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition)
  43548. {
  43549. int i;
  43550. if (channelPosition == MA_CHANNEL_NONE || channelPosition == MA_CHANNEL_MONO || channelPosition == MA_CHANNEL_LFE) {
  43551. return MA_FALSE;
  43552. }
  43553. if (channelPosition >= MA_CHANNEL_AUX_0 && channelPosition <= MA_CHANNEL_AUX_31) {
  43554. return MA_FALSE;
  43555. }
  43556. for (i = 0; i < 6; ++i) { /* Each side of a cube. */
  43557. if (g_maChannelPlaneRatios[channelPosition][i] != 0) {
  43558. return MA_TRUE;
  43559. }
  43560. }
  43561. return MA_FALSE;
  43562. }
  43563. static ma_bool32 ma_channel_map_is_passthrough(const ma_channel* pChannelMapIn, ma_uint32 channelsIn, const ma_channel* pChannelMapOut, ma_uint32 channelsOut)
  43564. {
  43565. if (channelsOut == channelsIn) {
  43566. return ma_channel_map_is_equal(pChannelMapOut, pChannelMapIn, channelsOut);
  43567. } else {
  43568. return MA_FALSE; /* Channel counts differ, so cannot be a passthrough. */
  43569. }
  43570. }
  43571. 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)
  43572. {
  43573. if (ma_channel_map_is_passthrough(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut)) {
  43574. return ma_channel_conversion_path_passthrough;
  43575. }
  43576. if (channelsOut == 1 && (pChannelMapOut == NULL || pChannelMapOut[0] == MA_CHANNEL_MONO)) {
  43577. return ma_channel_conversion_path_mono_out;
  43578. }
  43579. if (channelsIn == 1 && (pChannelMapIn == NULL || pChannelMapIn[0] == MA_CHANNEL_MONO)) {
  43580. return ma_channel_conversion_path_mono_in;
  43581. }
  43582. if (mode == ma_channel_mix_mode_custom_weights) {
  43583. return ma_channel_conversion_path_weights;
  43584. }
  43585. /*
  43586. We can use a simple shuffle if both channel maps have the same channel count and all channel
  43587. positions are present in both.
  43588. */
  43589. if (channelsIn == channelsOut) {
  43590. ma_uint32 iChannelIn;
  43591. ma_bool32 areAllChannelPositionsPresent = MA_TRUE;
  43592. for (iChannelIn = 0; iChannelIn < channelsIn; ++iChannelIn) {
  43593. ma_bool32 isInputChannelPositionInOutput = MA_FALSE;
  43594. if (ma_channel_map_contains_channel_position(channelsOut, pChannelMapOut, ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn))) {
  43595. isInputChannelPositionInOutput = MA_TRUE;
  43596. break;
  43597. }
  43598. if (!isInputChannelPositionInOutput) {
  43599. areAllChannelPositionsPresent = MA_FALSE;
  43600. break;
  43601. }
  43602. }
  43603. if (areAllChannelPositionsPresent) {
  43604. return ma_channel_conversion_path_shuffle;
  43605. }
  43606. }
  43607. /* Getting here means we'll need to use weights. */
  43608. return ma_channel_conversion_path_weights;
  43609. }
  43610. 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)
  43611. {
  43612. ma_uint32 iChannelIn;
  43613. ma_uint32 iChannelOut;
  43614. if (pShuffleTable == NULL || channelCountIn == 0 || channelCountOut == 0) {
  43615. return MA_INVALID_ARGS;
  43616. }
  43617. /*
  43618. When building the shuffle table we just do a 1:1 mapping based on the first occurance of a channel. If the
  43619. input channel has more than one occurance of a channel position, the second one will be ignored.
  43620. */
  43621. for (iChannelOut = 0; iChannelOut < channelCountOut; iChannelOut += 1) {
  43622. ma_channel channelOut;
  43623. /* Default to MA_CHANNEL_INDEX_NULL so that if a mapping is not found it'll be set appropriately. */
  43624. pShuffleTable[iChannelOut] = MA_CHANNEL_INDEX_NULL;
  43625. channelOut = ma_channel_map_get_channel(pChannelMapOut, channelCountOut, iChannelOut);
  43626. for (iChannelIn = 0; iChannelIn < channelCountIn; iChannelIn += 1) {
  43627. ma_channel channelIn;
  43628. channelIn = ma_channel_map_get_channel(pChannelMapIn, channelCountIn, iChannelIn);
  43629. if (channelOut == channelIn) {
  43630. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  43631. break;
  43632. }
  43633. /*
  43634. Getting here means the channels don't exactly match, but we are going to support some
  43635. relaxed matching for practicality. If, for example, there are two stereo channel maps,
  43636. but one uses front left/right and the other uses side left/right, it makes logical
  43637. sense to just map these. The way we'll do it is we'll check if there is a logical
  43638. corresponding mapping, and if so, apply it, but we will *not* break from the loop,
  43639. thereby giving the loop a chance to find an exact match later which will take priority.
  43640. */
  43641. switch (channelOut)
  43642. {
  43643. /* Left channels. */
  43644. case MA_CHANNEL_FRONT_LEFT:
  43645. case MA_CHANNEL_SIDE_LEFT:
  43646. {
  43647. switch (channelIn) {
  43648. case MA_CHANNEL_FRONT_LEFT:
  43649. case MA_CHANNEL_SIDE_LEFT:
  43650. {
  43651. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  43652. } break;
  43653. }
  43654. } break;
  43655. /* Right channels. */
  43656. case MA_CHANNEL_FRONT_RIGHT:
  43657. case MA_CHANNEL_SIDE_RIGHT:
  43658. {
  43659. switch (channelIn) {
  43660. case MA_CHANNEL_FRONT_RIGHT:
  43661. case MA_CHANNEL_SIDE_RIGHT:
  43662. {
  43663. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  43664. } break;
  43665. }
  43666. } break;
  43667. default: break;
  43668. }
  43669. }
  43670. }
  43671. return MA_SUCCESS;
  43672. }
  43673. 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)
  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_s16(ma_int16* pFramesOut, ma_uint32 channelsOut, const ma_int16* 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] = pFramesIn[iChannelIn];
  43699. } else {
  43700. pFramesOut[iChannelOut] = 0;
  43701. }
  43702. }
  43703. pFramesOut += channelsOut;
  43704. pFramesIn += channelsIn;
  43705. }
  43706. }
  43707. 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)
  43708. {
  43709. ma_uint64 iFrame;
  43710. ma_uint32 iChannelOut;
  43711. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43712. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43713. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43714. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43715. pFramesOut[iChannelOut*3 + 0] = pFramesIn[iChannelIn*3 + 0];
  43716. pFramesOut[iChannelOut*3 + 1] = pFramesIn[iChannelIn*3 + 1];
  43717. pFramesOut[iChannelOut*3 + 2] = pFramesIn[iChannelIn*3 + 2];
  43718. } else {
  43719. pFramesOut[iChannelOut*3 + 0] = 0;
  43720. } pFramesOut[iChannelOut*3 + 1] = 0;
  43721. } pFramesOut[iChannelOut*3 + 2] = 0;
  43722. pFramesOut += channelsOut*3;
  43723. pFramesIn += channelsIn*3;
  43724. }
  43725. }
  43726. 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)
  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 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)
  43744. {
  43745. ma_uint64 iFrame;
  43746. ma_uint32 iChannelOut;
  43747. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43748. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43749. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  43750. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  43751. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  43752. } else {
  43753. pFramesOut[iChannelOut] = 0;
  43754. }
  43755. }
  43756. pFramesOut += channelsOut;
  43757. pFramesIn += channelsIn;
  43758. }
  43759. }
  43760. 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)
  43761. {
  43762. if (pFramesOut == NULL || pFramesIn == NULL || channelsOut == 0 || pShuffleTable == NULL) {
  43763. return MA_INVALID_ARGS;
  43764. }
  43765. switch (format)
  43766. {
  43767. case ma_format_u8:
  43768. {
  43769. ma_channel_map_apply_shuffle_table_u8((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43770. } break;
  43771. case ma_format_s16:
  43772. {
  43773. ma_channel_map_apply_shuffle_table_s16((ma_int16*)pFramesOut, channelsOut, (const ma_int16*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43774. } break;
  43775. case ma_format_s24:
  43776. {
  43777. ma_channel_map_apply_shuffle_table_s24((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43778. } break;
  43779. case ma_format_s32:
  43780. {
  43781. ma_channel_map_apply_shuffle_table_s32((ma_int32*)pFramesOut, channelsOut, (const ma_int32*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43782. } break;
  43783. case ma_format_f32:
  43784. {
  43785. ma_channel_map_apply_shuffle_table_f32((float*)pFramesOut, channelsOut, (const float*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  43786. } break;
  43787. default: return MA_INVALID_ARGS; /* Unknown format. */
  43788. }
  43789. return MA_SUCCESS;
  43790. }
  43791. 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)
  43792. {
  43793. ma_uint64 iFrame;
  43794. ma_uint32 iChannelIn;
  43795. ma_uint32 accumulationCount;
  43796. if (pFramesOut == NULL || pFramesIn == NULL || channelsIn == 0) {
  43797. return MA_INVALID_ARGS;
  43798. }
  43799. /* In this case the output stream needs to be the average of all channels, ignoring NONE. */
  43800. /* A quick pre-processing step to get the accumulation counter since we're ignoring NONE channels. */
  43801. accumulationCount = 0;
  43802. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  43803. if (ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn) != MA_CHANNEL_NONE) {
  43804. accumulationCount += 1;
  43805. }
  43806. }
  43807. if (accumulationCount > 0) { /* <-- Prevent a division by zero. */
  43808. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43809. float accumulation = 0;
  43810. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  43811. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  43812. if (channelIn != MA_CHANNEL_NONE) {
  43813. accumulation += pFramesIn[iChannelIn];
  43814. }
  43815. }
  43816. pFramesOut[0] = accumulation / accumulationCount;
  43817. pFramesOut += 1;
  43818. pFramesIn += channelsIn;
  43819. }
  43820. } else {
  43821. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, 1);
  43822. }
  43823. return MA_SUCCESS;
  43824. }
  43825. 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)
  43826. {
  43827. ma_uint64 iFrame;
  43828. ma_uint32 iChannelOut;
  43829. if (pFramesOut == NULL || channelsOut == 0 || pFramesIn == NULL) {
  43830. return MA_INVALID_ARGS;
  43831. }
  43832. /* Note that the MA_CHANNEL_NONE channel must be ignored in all cases. */
  43833. switch (monoExpansionMode)
  43834. {
  43835. case ma_mono_expansion_mode_average:
  43836. {
  43837. float weight;
  43838. ma_uint32 validChannelCount = 0;
  43839. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43840. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43841. if (channelOut != MA_CHANNEL_NONE) {
  43842. validChannelCount += 1;
  43843. }
  43844. }
  43845. weight = 1.0f / validChannelCount;
  43846. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43847. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43848. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43849. if (channelOut != MA_CHANNEL_NONE) {
  43850. pFramesOut[iChannelOut] = pFramesIn[0] * weight;
  43851. }
  43852. }
  43853. pFramesOut += channelsOut;
  43854. pFramesIn += 1;
  43855. }
  43856. } break;
  43857. case ma_mono_expansion_mode_stereo_only:
  43858. {
  43859. if (channelsOut >= 2) {
  43860. ma_uint32 iChannelLeft = (ma_uint32)-1;
  43861. ma_uint32 iChannelRight = (ma_uint32)-1;
  43862. /*
  43863. We first need to find our stereo channels. We prefer front-left and front-right, but
  43864. if they're not available, we'll also try side-left and side-right. If neither are
  43865. available we'll fall through to the default case below.
  43866. */
  43867. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43868. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43869. if (channelOut == MA_CHANNEL_SIDE_LEFT) {
  43870. iChannelLeft = iChannelOut;
  43871. }
  43872. if (channelOut == MA_CHANNEL_SIDE_RIGHT) {
  43873. iChannelRight = iChannelOut;
  43874. }
  43875. }
  43876. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43877. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43878. if (channelOut == MA_CHANNEL_FRONT_LEFT) {
  43879. iChannelLeft = iChannelOut;
  43880. }
  43881. if (channelOut == MA_CHANNEL_FRONT_RIGHT) {
  43882. iChannelRight = iChannelOut;
  43883. }
  43884. }
  43885. if (iChannelLeft != (ma_uint32)-1 && iChannelRight != (ma_uint32)-1) {
  43886. /* We found our stereo channels so we can duplicate the signal across those channels. */
  43887. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43888. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43889. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43890. if (channelOut != MA_CHANNEL_NONE) {
  43891. if (iChannelOut == iChannelLeft || iChannelOut == iChannelRight) {
  43892. pFramesOut[iChannelOut] = pFramesIn[0];
  43893. } else {
  43894. pFramesOut[iChannelOut] = 0.0f;
  43895. }
  43896. }
  43897. }
  43898. pFramesOut += channelsOut;
  43899. pFramesIn += 1;
  43900. }
  43901. break; /* Get out of the switch. */
  43902. } else {
  43903. /* Fallthrough. Does not have left and right channels. */
  43904. goto default_handler;
  43905. }
  43906. } else {
  43907. /* Fallthrough. Does not have stereo channels. */
  43908. goto default_handler;
  43909. }
  43910. }; /* Fallthrough. See comments above. */
  43911. case ma_mono_expansion_mode_duplicate:
  43912. default:
  43913. {
  43914. default_handler:
  43915. {
  43916. if (channelsOut <= MA_MAX_CHANNELS) {
  43917. ma_bool32 hasEmptyChannel = MA_FALSE;
  43918. ma_channel channelPositions[MA_MAX_CHANNELS];
  43919. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  43920. channelPositions[iChannelOut] = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  43921. if (channelPositions[iChannelOut] == MA_CHANNEL_NONE) {
  43922. hasEmptyChannel = MA_TRUE;
  43923. }
  43924. }
  43925. if (hasEmptyChannel == MA_FALSE) {
  43926. /*
  43927. Faster path when there's no MA_CHANNEL_NONE channel positions. This should hopefully
  43928. help the compiler with auto-vectorization.m
  43929. */
  43930. if (channelsOut == 2) {
  43931. #if defined(MA_SUPPORT_SSE2)
  43932. if (ma_has_sse2()) {
  43933. /* We want to do two frames in each iteration. */
  43934. ma_uint64 unrolledFrameCount = frameCount >> 1;
  43935. for (iFrame = 0; iFrame < unrolledFrameCount; iFrame += 1) {
  43936. __m128 in0 = _mm_set1_ps(pFramesIn[iFrame*2 + 0]);
  43937. __m128 in1 = _mm_set1_ps(pFramesIn[iFrame*2 + 1]);
  43938. _mm_storeu_ps(&pFramesOut[iFrame*4 + 0], _mm_shuffle_ps(in0, in1, _MM_SHUFFLE(0, 0, 0, 0)));
  43939. }
  43940. /* Tail. */
  43941. iFrame = unrolledFrameCount << 1;
  43942. goto generic_on_fastpath;
  43943. } else
  43944. #endif
  43945. {
  43946. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43947. for (iChannelOut = 0; iChannelOut < 2; iChannelOut += 1) {
  43948. pFramesOut[iFrame*2 + iChannelOut] = pFramesIn[iFrame];
  43949. }
  43950. }
  43951. }
  43952. } else if (channelsOut == 6) {
  43953. #if defined(MA_SUPPORT_SSE2)
  43954. if (ma_has_sse2()) {
  43955. /* We want to do two frames in each iteration so we can have a multiple of 4 samples. */
  43956. ma_uint64 unrolledFrameCount = frameCount >> 1;
  43957. for (iFrame = 0; iFrame < unrolledFrameCount; iFrame += 1) {
  43958. __m128 in0 = _mm_set1_ps(pFramesIn[iFrame*2 + 0]);
  43959. __m128 in1 = _mm_set1_ps(pFramesIn[iFrame*2 + 1]);
  43960. _mm_storeu_ps(&pFramesOut[iFrame*12 + 0], in0);
  43961. _mm_storeu_ps(&pFramesOut[iFrame*12 + 4], _mm_shuffle_ps(in0, in1, _MM_SHUFFLE(0, 0, 0, 0)));
  43962. _mm_storeu_ps(&pFramesOut[iFrame*12 + 8], in1);
  43963. }
  43964. /* Tail. */
  43965. iFrame = unrolledFrameCount << 1;
  43966. goto generic_on_fastpath;
  43967. } else
  43968. #endif
  43969. {
  43970. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43971. for (iChannelOut = 0; iChannelOut < 6; iChannelOut += 1) {
  43972. pFramesOut[iFrame*6 + iChannelOut] = pFramesIn[iFrame];
  43973. }
  43974. }
  43975. }
  43976. } else if (channelsOut == 8) {
  43977. #if defined(MA_SUPPORT_SSE2)
  43978. if (ma_has_sse2()) {
  43979. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43980. __m128 in = _mm_set1_ps(pFramesIn[iFrame]);
  43981. _mm_storeu_ps(&pFramesOut[iFrame*8 + 0], in);
  43982. _mm_storeu_ps(&pFramesOut[iFrame*8 + 4], in);
  43983. }
  43984. } else
  43985. #endif
  43986. {
  43987. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43988. for (iChannelOut = 0; iChannelOut < 8; iChannelOut += 1) {
  43989. pFramesOut[iFrame*8 + iChannelOut] = pFramesIn[iFrame];
  43990. }
  43991. }
  43992. }
  43993. } else {
  43994. iFrame = 0;
  43995. #if defined(MA_SUPPORT_SSE2) /* For silencing a warning with non-x86 builds. */
  43996. generic_on_fastpath:
  43997. #endif
  43998. {
  43999. for (; iFrame < frameCount; iFrame += 1) {
  44000. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44001. pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame];
  44002. }
  44003. }
  44004. }
  44005. }
  44006. } else {
  44007. /* Slow path. Need to handle MA_CHANNEL_NONE. */
  44008. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44009. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44010. if (channelPositions[iChannelOut] != MA_CHANNEL_NONE) {
  44011. pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame];
  44012. }
  44013. }
  44014. }
  44015. }
  44016. } else {
  44017. /* Slow path. Too many channels to store on the stack. */
  44018. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44019. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44020. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  44021. if (channelOut != MA_CHANNEL_NONE) {
  44022. pFramesOut[iFrame*channelsOut + iChannelOut] = pFramesIn[iFrame];
  44023. }
  44024. }
  44025. }
  44026. }
  44027. }
  44028. } break;
  44029. }
  44030. return MA_SUCCESS;
  44031. }
  44032. 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)
  44033. {
  44034. ma_channel_conversion_path conversionPath = ma_channel_map_get_conversion_path(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, mode);
  44035. /* Optimized Path: Passthrough */
  44036. if (conversionPath == ma_channel_conversion_path_passthrough) {
  44037. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, channelsOut);
  44038. return;
  44039. }
  44040. /* Special Path: Mono Output. */
  44041. if (conversionPath == ma_channel_conversion_path_mono_out) {
  44042. ma_channel_map_apply_mono_out_f32(pFramesOut, pFramesIn, pChannelMapIn, channelsIn, frameCount);
  44043. return;
  44044. }
  44045. /* Special Path: Mono Input. */
  44046. if (conversionPath == ma_channel_conversion_path_mono_in) {
  44047. ma_channel_map_apply_mono_in_f32(pFramesOut, pChannelMapOut, channelsOut, pFramesIn, frameCount, monoExpansionMode);
  44048. return;
  44049. }
  44050. /* Getting here means we aren't running on an optimized conversion path. */
  44051. if (channelsOut <= MA_MAX_CHANNELS) {
  44052. ma_result result;
  44053. if (mode == ma_channel_mix_mode_simple) {
  44054. ma_channel shuffleTable[MA_MAX_CHANNELS];
  44055. result = ma_channel_map_build_shuffle_table(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, shuffleTable);
  44056. if (result != MA_SUCCESS) {
  44057. return;
  44058. }
  44059. result = ma_channel_map_apply_shuffle_table(pFramesOut, channelsOut, pFramesIn, channelsIn, frameCount, shuffleTable, ma_format_f32);
  44060. if (result != MA_SUCCESS) {
  44061. return;
  44062. }
  44063. } else {
  44064. ma_uint32 iFrame;
  44065. ma_uint32 iChannelOut;
  44066. ma_uint32 iChannelIn;
  44067. float weights[32][32]; /* Do not use MA_MAX_CHANNELS here! */
  44068. /*
  44069. If we have a small enough number of channels, pre-compute the weights. Otherwise we'll just need to
  44070. fall back to a slower path because otherwise we'll run out of stack space.
  44071. */
  44072. if (channelsIn <= ma_countof(weights) && channelsOut <= ma_countof(weights)) {
  44073. /* Pre-compute weights. */
  44074. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44075. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  44076. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44077. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  44078. weights[iChannelOut][iChannelIn] = ma_calculate_channel_position_rectangular_weight(channelOut, channelIn);
  44079. }
  44080. }
  44081. iFrame = 0;
  44082. /* Experiment: Try an optimized unroll for some specific cases to see how it improves performance. RESULT: Good gains. */
  44083. if (channelsOut == 8) {
  44084. /* Experiment 2: Expand the inner loop to see what kind of different it makes. RESULT: Small, but worthwhile gain. */
  44085. if (channelsIn == 2) {
  44086. for (; iFrame < frameCount; iFrame += 1) {
  44087. float accumulation[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  44088. accumulation[0] += pFramesIn[iFrame*2 + 0] * weights[0][0];
  44089. accumulation[1] += pFramesIn[iFrame*2 + 0] * weights[1][0];
  44090. accumulation[2] += pFramesIn[iFrame*2 + 0] * weights[2][0];
  44091. accumulation[3] += pFramesIn[iFrame*2 + 0] * weights[3][0];
  44092. accumulation[4] += pFramesIn[iFrame*2 + 0] * weights[4][0];
  44093. accumulation[5] += pFramesIn[iFrame*2 + 0] * weights[5][0];
  44094. accumulation[6] += pFramesIn[iFrame*2 + 0] * weights[6][0];
  44095. accumulation[7] += pFramesIn[iFrame*2 + 0] * weights[7][0];
  44096. accumulation[0] += pFramesIn[iFrame*2 + 1] * weights[0][1];
  44097. accumulation[1] += pFramesIn[iFrame*2 + 1] * weights[1][1];
  44098. accumulation[2] += pFramesIn[iFrame*2 + 1] * weights[2][1];
  44099. accumulation[3] += pFramesIn[iFrame*2 + 1] * weights[3][1];
  44100. accumulation[4] += pFramesIn[iFrame*2 + 1] * weights[4][1];
  44101. accumulation[5] += pFramesIn[iFrame*2 + 1] * weights[5][1];
  44102. accumulation[6] += pFramesIn[iFrame*2 + 1] * weights[6][1];
  44103. accumulation[7] += pFramesIn[iFrame*2 + 1] * weights[7][1];
  44104. pFramesOut[iFrame*8 + 0] = accumulation[0];
  44105. pFramesOut[iFrame*8 + 1] = accumulation[1];
  44106. pFramesOut[iFrame*8 + 2] = accumulation[2];
  44107. pFramesOut[iFrame*8 + 3] = accumulation[3];
  44108. pFramesOut[iFrame*8 + 4] = accumulation[4];
  44109. pFramesOut[iFrame*8 + 5] = accumulation[5];
  44110. pFramesOut[iFrame*8 + 6] = accumulation[6];
  44111. pFramesOut[iFrame*8 + 7] = accumulation[7];
  44112. }
  44113. } else {
  44114. /* When outputting to 8 channels, we can do everything in groups of two 4x SIMD operations. */
  44115. for (; iFrame < frameCount; iFrame += 1) {
  44116. float accumulation[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  44117. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44118. accumulation[0] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[0][iChannelIn];
  44119. accumulation[1] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[1][iChannelIn];
  44120. accumulation[2] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[2][iChannelIn];
  44121. accumulation[3] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[3][iChannelIn];
  44122. accumulation[4] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[4][iChannelIn];
  44123. accumulation[5] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[5][iChannelIn];
  44124. accumulation[6] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[6][iChannelIn];
  44125. accumulation[7] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[7][iChannelIn];
  44126. }
  44127. pFramesOut[iFrame*8 + 0] = accumulation[0];
  44128. pFramesOut[iFrame*8 + 1] = accumulation[1];
  44129. pFramesOut[iFrame*8 + 2] = accumulation[2];
  44130. pFramesOut[iFrame*8 + 3] = accumulation[3];
  44131. pFramesOut[iFrame*8 + 4] = accumulation[4];
  44132. pFramesOut[iFrame*8 + 5] = accumulation[5];
  44133. pFramesOut[iFrame*8 + 6] = accumulation[6];
  44134. pFramesOut[iFrame*8 + 7] = accumulation[7];
  44135. }
  44136. }
  44137. } else if (channelsOut == 6) {
  44138. /*
  44139. When outputting to 6 channels we unfortunately don't have a nice multiple of 4 to do 4x SIMD operations. Instead we'll
  44140. expand our weights and do two frames at a time.
  44141. */
  44142. for (; iFrame < frameCount; iFrame += 1) {
  44143. float accumulation[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  44144. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44145. accumulation[0] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[0][iChannelIn];
  44146. accumulation[1] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[1][iChannelIn];
  44147. accumulation[2] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[2][iChannelIn];
  44148. accumulation[3] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[3][iChannelIn];
  44149. accumulation[4] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[4][iChannelIn];
  44150. accumulation[5] += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[5][iChannelIn];
  44151. }
  44152. pFramesOut[iFrame*6 + 0] = accumulation[0];
  44153. pFramesOut[iFrame*6 + 1] = accumulation[1];
  44154. pFramesOut[iFrame*6 + 2] = accumulation[2];
  44155. pFramesOut[iFrame*6 + 3] = accumulation[3];
  44156. pFramesOut[iFrame*6 + 4] = accumulation[4];
  44157. pFramesOut[iFrame*6 + 5] = accumulation[5];
  44158. }
  44159. }
  44160. /* Leftover frames. */
  44161. for (; iFrame < frameCount; iFrame += 1) {
  44162. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44163. float accumulation = 0;
  44164. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44165. accumulation += pFramesIn[iFrame*channelsIn + iChannelIn] * weights[iChannelOut][iChannelIn];
  44166. }
  44167. pFramesOut[iFrame*channelsOut + iChannelOut] = accumulation;
  44168. }
  44169. }
  44170. } else {
  44171. /* Cannot pre-compute weights because not enough room in stack-allocated buffer. */
  44172. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44173. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  44174. float accumulation = 0;
  44175. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  44176. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  44177. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  44178. accumulation += pFramesIn[iFrame*channelsIn + iChannelIn] * ma_calculate_channel_position_rectangular_weight(channelOut, channelIn);
  44179. }
  44180. pFramesOut[iFrame*channelsOut + iChannelOut] = accumulation;
  44181. }
  44182. }
  44183. }
  44184. }
  44185. } else {
  44186. /* Fall back to silence. If you hit this, what are you doing with so many channels?! */
  44187. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, channelsOut);
  44188. }
  44189. }
  44190. typedef struct
  44191. {
  44192. size_t sizeInBytes;
  44193. size_t channelMapInOffset;
  44194. size_t channelMapOutOffset;
  44195. size_t shuffleTableOffset;
  44196. size_t weightsOffset;
  44197. } ma_channel_converter_heap_layout;
  44198. static ma_channel_conversion_path ma_channel_converter_config_get_conversion_path(const ma_channel_converter_config* pConfig)
  44199. {
  44200. return ma_channel_map_get_conversion_path(pConfig->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapOut, pConfig->channelsOut, pConfig->mixingMode);
  44201. }
  44202. static ma_result ma_channel_converter_get_heap_layout(const ma_channel_converter_config* pConfig, ma_channel_converter_heap_layout* pHeapLayout)
  44203. {
  44204. ma_channel_conversion_path conversionPath;
  44205. MA_ASSERT(pHeapLayout != NULL);
  44206. if (pConfig == NULL) {
  44207. return MA_INVALID_ARGS;
  44208. }
  44209. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  44210. return MA_INVALID_ARGS;
  44211. }
  44212. if (!ma_channel_map_is_valid(pConfig->pChannelMapIn, pConfig->channelsIn)) {
  44213. return MA_INVALID_ARGS;
  44214. }
  44215. if (!ma_channel_map_is_valid(pConfig->pChannelMapOut, pConfig->channelsOut)) {
  44216. return MA_INVALID_ARGS;
  44217. }
  44218. pHeapLayout->sizeInBytes = 0;
  44219. /* Input channel map. Only need to allocate this if we have an input channel map (otherwise default channel map is assumed). */
  44220. pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes;
  44221. if (pConfig->pChannelMapIn != NULL) {
  44222. pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsIn;
  44223. }
  44224. /* Output channel map. Only need to allocate this if we have an output channel map (otherwise default channel map is assumed). */
  44225. pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes;
  44226. if (pConfig->pChannelMapOut != NULL) {
  44227. pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsOut;
  44228. }
  44229. /* Alignment for the next section. */
  44230. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  44231. /* Whether or not we use weights of a shuffle table depends on the channel map themselves and the algorithm we've chosen. */
  44232. conversionPath = ma_channel_converter_config_get_conversion_path(pConfig);
  44233. /* Shuffle table */
  44234. pHeapLayout->shuffleTableOffset = pHeapLayout->sizeInBytes;
  44235. if (conversionPath == ma_channel_conversion_path_shuffle) {
  44236. pHeapLayout->sizeInBytes += sizeof(ma_uint8) * pConfig->channelsOut;
  44237. }
  44238. /* Weights */
  44239. pHeapLayout->weightsOffset = pHeapLayout->sizeInBytes;
  44240. if (conversionPath == ma_channel_conversion_path_weights) {
  44241. pHeapLayout->sizeInBytes += sizeof(float*) * pConfig->channelsIn;
  44242. pHeapLayout->sizeInBytes += sizeof(float ) * pConfig->channelsIn * pConfig->channelsOut;
  44243. }
  44244. /* Make sure allocation size is aligned. */
  44245. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  44246. return MA_SUCCESS;
  44247. }
  44248. MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes)
  44249. {
  44250. ma_result result;
  44251. ma_channel_converter_heap_layout heapLayout;
  44252. if (pHeapSizeInBytes == NULL) {
  44253. return MA_INVALID_ARGS;
  44254. }
  44255. *pHeapSizeInBytes = 0;
  44256. result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout);
  44257. if (result != MA_SUCCESS) {
  44258. return result;
  44259. }
  44260. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  44261. return MA_SUCCESS;
  44262. }
  44263. MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter)
  44264. {
  44265. ma_result result;
  44266. ma_channel_converter_heap_layout heapLayout;
  44267. if (pConverter == NULL) {
  44268. return MA_INVALID_ARGS;
  44269. }
  44270. MA_ZERO_OBJECT(pConverter);
  44271. result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout);
  44272. if (result != MA_SUCCESS) {
  44273. return result;
  44274. }
  44275. pConverter->_pHeap = pHeap;
  44276. MA_ZERO_MEMORY(pConverter->_pHeap, heapLayout.sizeInBytes);
  44277. pConverter->format = pConfig->format;
  44278. pConverter->channelsIn = pConfig->channelsIn;
  44279. pConverter->channelsOut = pConfig->channelsOut;
  44280. pConverter->mixingMode = pConfig->mixingMode;
  44281. if (pConfig->pChannelMapIn != NULL) {
  44282. pConverter->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset);
  44283. ma_channel_map_copy_or_default(pConverter->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsIn);
  44284. } else {
  44285. pConverter->pChannelMapIn = NULL; /* Use default channel map. */
  44286. }
  44287. if (pConfig->pChannelMapOut != NULL) {
  44288. pConverter->pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset);
  44289. ma_channel_map_copy_or_default(pConverter->pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut);
  44290. } else {
  44291. pConverter->pChannelMapOut = NULL; /* Use default channel map. */
  44292. }
  44293. pConverter->conversionPath = ma_channel_converter_config_get_conversion_path(pConfig);
  44294. if (pConverter->conversionPath == ma_channel_conversion_path_shuffle) {
  44295. pConverter->pShuffleTable = (ma_uint8*)ma_offset_ptr(pHeap, heapLayout.shuffleTableOffset);
  44296. ma_channel_map_build_shuffle_table(pConverter->pChannelMapIn, pConverter->channelsIn, pConverter->pChannelMapOut, pConverter->channelsOut, pConverter->pShuffleTable);
  44297. }
  44298. if (pConverter->conversionPath == ma_channel_conversion_path_weights) {
  44299. ma_uint32 iChannelIn;
  44300. ma_uint32 iChannelOut;
  44301. if (pConverter->format == ma_format_f32) {
  44302. pConverter->weights.f32 = (float** )ma_offset_ptr(pHeap, heapLayout.weightsOffset);
  44303. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44304. pConverter->weights.f32[iChannelIn] = (float*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(float*) * pConverter->channelsIn) + (sizeof(float) * pConverter->channelsOut * iChannelIn)));
  44305. }
  44306. } else {
  44307. pConverter->weights.s16 = (ma_int32**)ma_offset_ptr(pHeap, heapLayout.weightsOffset);
  44308. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44309. pConverter->weights.s16[iChannelIn] = (ma_int32*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(ma_int32*) * pConverter->channelsIn) + (sizeof(ma_int32) * pConverter->channelsOut * iChannelIn)));
  44310. }
  44311. }
  44312. /* Silence our weights by default. */
  44313. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44314. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) {
  44315. if (pConverter->format == ma_format_f32) {
  44316. pConverter->weights.f32[iChannelIn][iChannelOut] = 0.0f;
  44317. } else {
  44318. pConverter->weights.s16[iChannelIn][iChannelOut] = 0;
  44319. }
  44320. }
  44321. }
  44322. /*
  44323. We now need to fill out our weights table. This is determined by the mixing mode.
  44324. */
  44325. /* In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. */
  44326. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44327. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44328. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44329. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  44330. if (channelPosIn == channelPosOut) {
  44331. float weight = 1;
  44332. if (pConverter->format == ma_format_f32) {
  44333. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44334. } else {
  44335. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44336. }
  44337. }
  44338. }
  44339. }
  44340. switch (pConverter->mixingMode)
  44341. {
  44342. case ma_channel_mix_mode_custom_weights:
  44343. {
  44344. if (pConfig->ppWeights == NULL) {
  44345. return MA_INVALID_ARGS; /* Config specified a custom weights mixing mode, but no custom weights have been specified. */
  44346. }
  44347. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  44348. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) {
  44349. float weight = pConfig->ppWeights[iChannelIn][iChannelOut];
  44350. if (pConverter->format == ma_format_f32) {
  44351. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44352. } else {
  44353. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44354. }
  44355. }
  44356. }
  44357. } break;
  44358. case ma_channel_mix_mode_simple:
  44359. {
  44360. /*
  44361. In simple mode, only set weights for channels that have exactly matching types, leave the rest at
  44362. zero. The 1:1 mappings have already been covered before this switch statement.
  44363. */
  44364. } break;
  44365. case ma_channel_mix_mode_rectangular:
  44366. default:
  44367. {
  44368. /* Unmapped input channels. */
  44369. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44370. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44371. if (ma_is_spatial_channel_position(channelPosIn)) {
  44372. if (!ma_channel_map_contains_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, channelPosIn)) {
  44373. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44374. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  44375. if (ma_is_spatial_channel_position(channelPosOut)) {
  44376. float weight = 0;
  44377. if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
  44378. weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
  44379. }
  44380. /* Only apply the weight if we haven't already got some contribution from the respective channels. */
  44381. if (pConverter->format == ma_format_f32) {
  44382. if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
  44383. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44384. }
  44385. } else {
  44386. if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
  44387. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44388. }
  44389. }
  44390. }
  44391. }
  44392. }
  44393. }
  44394. }
  44395. /* Unmapped output channels. */
  44396. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44397. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  44398. if (ma_is_spatial_channel_position(channelPosOut)) {
  44399. if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, channelPosOut)) {
  44400. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44401. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44402. if (ma_is_spatial_channel_position(channelPosIn)) {
  44403. float weight = 0;
  44404. if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
  44405. weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
  44406. }
  44407. /* Only apply the weight if we haven't already got some contribution from the respective channels. */
  44408. if (pConverter->format == ma_format_f32) {
  44409. if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
  44410. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  44411. }
  44412. } else {
  44413. if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
  44414. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  44415. }
  44416. }
  44417. }
  44418. }
  44419. }
  44420. }
  44421. }
  44422. /* If LFE is in the output channel map but was not present in the input channel map, configure its weight now */
  44423. if (pConfig->calculateLFEFromSpatialChannels) {
  44424. if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, MA_CHANNEL_LFE)) {
  44425. ma_uint32 spatialChannelCount = ma_channel_map_get_spatial_channel_count(pConverter->pChannelMapIn, pConverter->channelsIn);
  44426. ma_uint32 iChannelOutLFE;
  44427. if (spatialChannelCount > 0 && ma_channel_map_find_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, MA_CHANNEL_LFE, &iChannelOutLFE)) {
  44428. const float weightForLFE = 1.0f / spatialChannelCount;
  44429. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44430. const ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  44431. if (ma_is_spatial_channel_position(channelPosIn)) {
  44432. if (pConverter->format == ma_format_f32) {
  44433. if (pConverter->weights.f32[iChannelIn][iChannelOutLFE] == 0) {
  44434. pConverter->weights.f32[iChannelIn][iChannelOutLFE] = weightForLFE;
  44435. }
  44436. } else {
  44437. if (pConverter->weights.s16[iChannelIn][iChannelOutLFE] == 0) {
  44438. pConverter->weights.s16[iChannelIn][iChannelOutLFE] = ma_channel_converter_float_to_fixed(weightForLFE);
  44439. }
  44440. }
  44441. }
  44442. }
  44443. }
  44444. }
  44445. }
  44446. } break;
  44447. }
  44448. }
  44449. return MA_SUCCESS;
  44450. }
  44451. MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter)
  44452. {
  44453. ma_result result;
  44454. size_t heapSizeInBytes;
  44455. void* pHeap;
  44456. result = ma_channel_converter_get_heap_size(pConfig, &heapSizeInBytes);
  44457. if (result != MA_SUCCESS) {
  44458. return result;
  44459. }
  44460. if (heapSizeInBytes > 0) {
  44461. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  44462. if (pHeap == NULL) {
  44463. return MA_OUT_OF_MEMORY;
  44464. }
  44465. } else {
  44466. pHeap = NULL;
  44467. }
  44468. result = ma_channel_converter_init_preallocated(pConfig, pHeap, pConverter);
  44469. if (result != MA_SUCCESS) {
  44470. ma_free(pHeap, pAllocationCallbacks);
  44471. return result;
  44472. }
  44473. pConverter->_ownsHeap = MA_TRUE;
  44474. return MA_SUCCESS;
  44475. }
  44476. MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks)
  44477. {
  44478. if (pConverter == NULL) {
  44479. return;
  44480. }
  44481. if (pConverter->_ownsHeap) {
  44482. ma_free(pConverter->_pHeap, pAllocationCallbacks);
  44483. }
  44484. }
  44485. static ma_result ma_channel_converter_process_pcm_frames__passthrough(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44486. {
  44487. MA_ASSERT(pConverter != NULL);
  44488. MA_ASSERT(pFramesOut != NULL);
  44489. MA_ASSERT(pFramesIn != NULL);
  44490. ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  44491. return MA_SUCCESS;
  44492. }
  44493. static ma_result ma_channel_converter_process_pcm_frames__shuffle(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44494. {
  44495. MA_ASSERT(pConverter != NULL);
  44496. MA_ASSERT(pFramesOut != NULL);
  44497. MA_ASSERT(pFramesIn != NULL);
  44498. MA_ASSERT(pConverter->channelsIn == pConverter->channelsOut);
  44499. return ma_channel_map_apply_shuffle_table(pFramesOut, pConverter->channelsOut, pFramesIn, pConverter->channelsIn, frameCount, pConverter->pShuffleTable, pConverter->format);
  44500. }
  44501. static ma_result ma_channel_converter_process_pcm_frames__mono_in(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44502. {
  44503. ma_uint64 iFrame;
  44504. MA_ASSERT(pConverter != NULL);
  44505. MA_ASSERT(pFramesOut != NULL);
  44506. MA_ASSERT(pFramesIn != NULL);
  44507. MA_ASSERT(pConverter->channelsIn == 1);
  44508. switch (pConverter->format)
  44509. {
  44510. case ma_format_u8:
  44511. {
  44512. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  44513. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  44514. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44515. ma_uint32 iChannel;
  44516. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44517. pFramesOutU8[iFrame*pConverter->channelsOut + iChannel] = pFramesInU8[iFrame];
  44518. }
  44519. }
  44520. } break;
  44521. case ma_format_s16:
  44522. {
  44523. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  44524. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  44525. if (pConverter->channelsOut == 2) {
  44526. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44527. pFramesOutS16[iFrame*2 + 0] = pFramesInS16[iFrame];
  44528. pFramesOutS16[iFrame*2 + 1] = pFramesInS16[iFrame];
  44529. }
  44530. } else {
  44531. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44532. ma_uint32 iChannel;
  44533. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44534. pFramesOutS16[iFrame*pConverter->channelsOut + iChannel] = pFramesInS16[iFrame];
  44535. }
  44536. }
  44537. }
  44538. } break;
  44539. case ma_format_s24:
  44540. {
  44541. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  44542. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  44543. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44544. ma_uint32 iChannel;
  44545. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44546. ma_uint64 iSampleOut = iFrame*pConverter->channelsOut + iChannel;
  44547. ma_uint64 iSampleIn = iFrame;
  44548. pFramesOutS24[iSampleOut*3 + 0] = pFramesInS24[iSampleIn*3 + 0];
  44549. pFramesOutS24[iSampleOut*3 + 1] = pFramesInS24[iSampleIn*3 + 1];
  44550. pFramesOutS24[iSampleOut*3 + 2] = pFramesInS24[iSampleIn*3 + 2];
  44551. }
  44552. }
  44553. } break;
  44554. case ma_format_s32:
  44555. {
  44556. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  44557. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  44558. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44559. ma_uint32 iChannel;
  44560. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44561. pFramesOutS32[iFrame*pConverter->channelsOut + iChannel] = pFramesInS32[iFrame];
  44562. }
  44563. }
  44564. } break;
  44565. case ma_format_f32:
  44566. {
  44567. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  44568. const float* pFramesInF32 = (const float*)pFramesIn;
  44569. if (pConverter->channelsOut == 2) {
  44570. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44571. pFramesOutF32[iFrame*2 + 0] = pFramesInF32[iFrame];
  44572. pFramesOutF32[iFrame*2 + 1] = pFramesInF32[iFrame];
  44573. }
  44574. } else {
  44575. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44576. ma_uint32 iChannel;
  44577. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  44578. pFramesOutF32[iFrame*pConverter->channelsOut + iChannel] = pFramesInF32[iFrame];
  44579. }
  44580. }
  44581. }
  44582. } break;
  44583. default: return MA_INVALID_OPERATION; /* Unknown format. */
  44584. }
  44585. return MA_SUCCESS;
  44586. }
  44587. static ma_result ma_channel_converter_process_pcm_frames__mono_out(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44588. {
  44589. ma_uint64 iFrame;
  44590. ma_uint32 iChannel;
  44591. MA_ASSERT(pConverter != NULL);
  44592. MA_ASSERT(pFramesOut != NULL);
  44593. MA_ASSERT(pFramesIn != NULL);
  44594. MA_ASSERT(pConverter->channelsOut == 1);
  44595. switch (pConverter->format)
  44596. {
  44597. case ma_format_u8:
  44598. {
  44599. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  44600. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  44601. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44602. ma_int32 t = 0;
  44603. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44604. t += ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8[iFrame*pConverter->channelsIn + iChannel]);
  44605. }
  44606. pFramesOutU8[iFrame] = ma_clip_u8(t / pConverter->channelsOut);
  44607. }
  44608. } break;
  44609. case ma_format_s16:
  44610. {
  44611. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  44612. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  44613. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44614. ma_int32 t = 0;
  44615. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44616. t += pFramesInS16[iFrame*pConverter->channelsIn + iChannel];
  44617. }
  44618. pFramesOutS16[iFrame] = (ma_int16)(t / pConverter->channelsIn);
  44619. }
  44620. } break;
  44621. case ma_format_s24:
  44622. {
  44623. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  44624. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  44625. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44626. ma_int64 t = 0;
  44627. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44628. t += ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24[(iFrame*pConverter->channelsIn + iChannel)*3]);
  44629. }
  44630. ma_pcm_sample_s32_to_s24_no_scale(t / pConverter->channelsIn, &pFramesOutS24[iFrame*3]);
  44631. }
  44632. } break;
  44633. case ma_format_s32:
  44634. {
  44635. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  44636. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  44637. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44638. ma_int64 t = 0;
  44639. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44640. t += pFramesInS32[iFrame*pConverter->channelsIn + iChannel];
  44641. }
  44642. pFramesOutS32[iFrame] = (ma_int32)(t / pConverter->channelsIn);
  44643. }
  44644. } break;
  44645. case ma_format_f32:
  44646. {
  44647. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  44648. const float* pFramesInF32 = (const float*)pFramesIn;
  44649. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  44650. float t = 0;
  44651. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  44652. t += pFramesInF32[iFrame*pConverter->channelsIn + iChannel];
  44653. }
  44654. pFramesOutF32[iFrame] = t / pConverter->channelsIn;
  44655. }
  44656. } break;
  44657. default: return MA_INVALID_OPERATION; /* Unknown format. */
  44658. }
  44659. return MA_SUCCESS;
  44660. }
  44661. static ma_result ma_channel_converter_process_pcm_frames__weights(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44662. {
  44663. ma_uint32 iFrame;
  44664. ma_uint32 iChannelIn;
  44665. ma_uint32 iChannelOut;
  44666. MA_ASSERT(pConverter != NULL);
  44667. MA_ASSERT(pFramesOut != NULL);
  44668. MA_ASSERT(pFramesIn != NULL);
  44669. /* This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. */
  44670. /* Clear. */
  44671. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  44672. /* Accumulate. */
  44673. switch (pConverter->format)
  44674. {
  44675. case ma_format_u8:
  44676. {
  44677. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  44678. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  44679. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44680. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44681. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44682. ma_int16 u8_O = ma_pcm_sample_u8_to_s16_no_scale(pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut]);
  44683. ma_int16 u8_I = ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8 [iFrame*pConverter->channelsIn + iChannelIn ]);
  44684. ma_int32 s = (ma_int32)ma_clamp(u8_O + ((u8_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -128, 127);
  44685. pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_u8((ma_int16)s);
  44686. }
  44687. }
  44688. }
  44689. } break;
  44690. case ma_format_s16:
  44691. {
  44692. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  44693. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  44694. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44695. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44696. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44697. ma_int32 s = pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut];
  44698. s += (pFramesInS16[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
  44699. pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut] = (ma_int16)ma_clamp(s, -32768, 32767);
  44700. }
  44701. }
  44702. }
  44703. } break;
  44704. case ma_format_s24:
  44705. {
  44706. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  44707. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  44708. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44709. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44710. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44711. ma_int64 s24_O = ma_pcm_sample_s24_to_s32_no_scale(&pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
  44712. ma_int64 s24_I = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24 [(iFrame*pConverter->channelsIn + iChannelIn )*3]);
  44713. ma_int64 s24 = (ma_int32)ma_clamp(s24_O + ((s24_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -8388608, 8388607);
  44714. ma_pcm_sample_s32_to_s24_no_scale(s24, &pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
  44715. }
  44716. }
  44717. }
  44718. } break;
  44719. case ma_format_s32:
  44720. {
  44721. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  44722. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  44723. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44724. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44725. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44726. ma_int64 s = pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut];
  44727. s += ((ma_int64)pFramesInS32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
  44728. pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_s32(s);
  44729. }
  44730. }
  44731. }
  44732. } break;
  44733. case ma_format_f32:
  44734. {
  44735. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  44736. const float* pFramesInF32 = (const float*)pFramesIn;
  44737. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  44738. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  44739. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  44740. pFramesOutF32[iFrame*pConverter->channelsOut + iChannelOut] += pFramesInF32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.f32[iChannelIn][iChannelOut];
  44741. }
  44742. }
  44743. }
  44744. } break;
  44745. default: return MA_INVALID_OPERATION; /* Unknown format. */
  44746. }
  44747. return MA_SUCCESS;
  44748. }
  44749. MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  44750. {
  44751. if (pConverter == NULL) {
  44752. return MA_INVALID_ARGS;
  44753. }
  44754. if (pFramesOut == NULL) {
  44755. return MA_INVALID_ARGS;
  44756. }
  44757. if (pFramesIn == NULL) {
  44758. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  44759. return MA_SUCCESS;
  44760. }
  44761. switch (pConverter->conversionPath)
  44762. {
  44763. case ma_channel_conversion_path_passthrough: return ma_channel_converter_process_pcm_frames__passthrough(pConverter, pFramesOut, pFramesIn, frameCount);
  44764. case ma_channel_conversion_path_mono_out: return ma_channel_converter_process_pcm_frames__mono_out(pConverter, pFramesOut, pFramesIn, frameCount);
  44765. case ma_channel_conversion_path_mono_in: return ma_channel_converter_process_pcm_frames__mono_in(pConverter, pFramesOut, pFramesIn, frameCount);
  44766. case ma_channel_conversion_path_shuffle: return ma_channel_converter_process_pcm_frames__shuffle(pConverter, pFramesOut, pFramesIn, frameCount);
  44767. case ma_channel_conversion_path_weights:
  44768. default:
  44769. {
  44770. return ma_channel_converter_process_pcm_frames__weights(pConverter, pFramesOut, pFramesIn, frameCount);
  44771. }
  44772. }
  44773. }
  44774. MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  44775. {
  44776. if (pConverter == NULL || pChannelMap == NULL) {
  44777. return MA_INVALID_ARGS;
  44778. }
  44779. ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapIn, pConverter->channelsIn);
  44780. return MA_SUCCESS;
  44781. }
  44782. MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  44783. {
  44784. if (pConverter == NULL || pChannelMap == NULL) {
  44785. return MA_INVALID_ARGS;
  44786. }
  44787. ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapOut, pConverter->channelsOut);
  44788. return MA_SUCCESS;
  44789. }
  44790. /**************************************************************************************************************************************************************
  44791. Data Conversion
  44792. **************************************************************************************************************************************************************/
  44793. MA_API ma_data_converter_config ma_data_converter_config_init_default(void)
  44794. {
  44795. ma_data_converter_config config;
  44796. MA_ZERO_OBJECT(&config);
  44797. config.ditherMode = ma_dither_mode_none;
  44798. config.resampling.algorithm = ma_resample_algorithm_linear;
  44799. 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. */
  44800. /* Linear resampling defaults. */
  44801. config.resampling.linear.lpfOrder = 1;
  44802. return config;
  44803. }
  44804. 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)
  44805. {
  44806. ma_data_converter_config config = ma_data_converter_config_init_default();
  44807. config.formatIn = formatIn;
  44808. config.formatOut = formatOut;
  44809. config.channelsIn = channelsIn;
  44810. config.channelsOut = channelsOut;
  44811. config.sampleRateIn = sampleRateIn;
  44812. config.sampleRateOut = sampleRateOut;
  44813. return config;
  44814. }
  44815. typedef struct
  44816. {
  44817. size_t sizeInBytes;
  44818. size_t channelConverterOffset;
  44819. size_t resamplerOffset;
  44820. } ma_data_converter_heap_layout;
  44821. static ma_bool32 ma_data_converter_config_is_resampler_required(const ma_data_converter_config* pConfig)
  44822. {
  44823. MA_ASSERT(pConfig != NULL);
  44824. return pConfig->allowDynamicSampleRate || pConfig->sampleRateIn != pConfig->sampleRateOut;
  44825. }
  44826. static ma_format ma_data_converter_config_get_mid_format(const ma_data_converter_config* pConfig)
  44827. {
  44828. MA_ASSERT(pConfig != NULL);
  44829. /*
  44830. We want to avoid as much data conversion as possible. The channel converter and linear
  44831. resampler both support s16 and f32 natively. We need to decide on the format to use for this
  44832. stage. We call this the mid format because it's used in the middle stage of the conversion
  44833. pipeline. If the output format is either s16 or f32 we use that one. If that is not the case it
  44834. will do the same thing for the input format. If it's neither we just use f32. If we are using a
  44835. custom resampling backend, we can only guarantee that f32 will be supported so we'll be forced
  44836. to use that if resampling is required.
  44837. */
  44838. if (ma_data_converter_config_is_resampler_required(pConfig) && pConfig->resampling.algorithm != ma_resample_algorithm_linear) {
  44839. return ma_format_f32; /* <-- Force f32 since that is the only one we can guarantee will be supported by the resampler. */
  44840. } else {
  44841. /* */ if (pConfig->formatOut == ma_format_s16 || pConfig->formatOut == ma_format_f32) {
  44842. return pConfig->formatOut;
  44843. } else if (pConfig->formatIn == ma_format_s16 || pConfig->formatIn == ma_format_f32) {
  44844. return pConfig->formatIn;
  44845. } else {
  44846. return ma_format_f32;
  44847. }
  44848. }
  44849. }
  44850. static ma_channel_converter_config ma_channel_converter_config_init_from_data_converter_config(const ma_data_converter_config* pConfig)
  44851. {
  44852. ma_channel_converter_config channelConverterConfig;
  44853. MA_ASSERT(pConfig != NULL);
  44854. channelConverterConfig = ma_channel_converter_config_init(ma_data_converter_config_get_mid_format(pConfig), pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelMixMode);
  44855. channelConverterConfig.ppWeights = pConfig->ppChannelWeights;
  44856. channelConverterConfig.calculateLFEFromSpatialChannels = pConfig->calculateLFEFromSpatialChannels;
  44857. return channelConverterConfig;
  44858. }
  44859. static ma_resampler_config ma_resampler_config_init_from_data_converter_config(const ma_data_converter_config* pConfig)
  44860. {
  44861. ma_resampler_config resamplerConfig;
  44862. ma_uint32 resamplerChannels;
  44863. MA_ASSERT(pConfig != NULL);
  44864. /* 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. */
  44865. if (pConfig->channelsIn < pConfig->channelsOut) {
  44866. resamplerChannels = pConfig->channelsIn;
  44867. } else {
  44868. resamplerChannels = pConfig->channelsOut;
  44869. }
  44870. resamplerConfig = ma_resampler_config_init(ma_data_converter_config_get_mid_format(pConfig), resamplerChannels, pConfig->sampleRateIn, pConfig->sampleRateOut, pConfig->resampling.algorithm);
  44871. resamplerConfig.linear = pConfig->resampling.linear;
  44872. resamplerConfig.pBackendVTable = pConfig->resampling.pBackendVTable;
  44873. resamplerConfig.pBackendUserData = pConfig->resampling.pBackendUserData;
  44874. return resamplerConfig;
  44875. }
  44876. static ma_result ma_data_converter_get_heap_layout(const ma_data_converter_config* pConfig, ma_data_converter_heap_layout* pHeapLayout)
  44877. {
  44878. ma_result result;
  44879. MA_ASSERT(pHeapLayout != NULL);
  44880. MA_ZERO_OBJECT(pHeapLayout);
  44881. if (pConfig == NULL) {
  44882. return MA_INVALID_ARGS;
  44883. }
  44884. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  44885. return MA_INVALID_ARGS;
  44886. }
  44887. pHeapLayout->sizeInBytes = 0;
  44888. /* Channel converter. */
  44889. pHeapLayout->channelConverterOffset = pHeapLayout->sizeInBytes;
  44890. {
  44891. size_t heapSizeInBytes;
  44892. ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig);
  44893. result = ma_channel_converter_get_heap_size(&channelConverterConfig, &heapSizeInBytes);
  44894. if (result != MA_SUCCESS) {
  44895. return result;
  44896. }
  44897. pHeapLayout->sizeInBytes += heapSizeInBytes;
  44898. }
  44899. /* Resampler. */
  44900. pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes;
  44901. if (ma_data_converter_config_is_resampler_required(pConfig)) {
  44902. size_t heapSizeInBytes;
  44903. ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig);
  44904. result = ma_resampler_get_heap_size(&resamplerConfig, &heapSizeInBytes);
  44905. if (result != MA_SUCCESS) {
  44906. return result;
  44907. }
  44908. pHeapLayout->sizeInBytes += heapSizeInBytes;
  44909. }
  44910. /* Make sure allocation size is aligned. */
  44911. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  44912. return MA_SUCCESS;
  44913. }
  44914. MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes)
  44915. {
  44916. ma_result result;
  44917. ma_data_converter_heap_layout heapLayout;
  44918. if (pHeapSizeInBytes == NULL) {
  44919. return MA_INVALID_ARGS;
  44920. }
  44921. *pHeapSizeInBytes = 0;
  44922. result = ma_data_converter_get_heap_layout(pConfig, &heapLayout);
  44923. if (result != MA_SUCCESS) {
  44924. return result;
  44925. }
  44926. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  44927. return MA_SUCCESS;
  44928. }
  44929. MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter)
  44930. {
  44931. ma_result result;
  44932. ma_data_converter_heap_layout heapLayout;
  44933. ma_format midFormat;
  44934. ma_bool32 isResamplingRequired;
  44935. if (pConverter == NULL) {
  44936. return MA_INVALID_ARGS;
  44937. }
  44938. MA_ZERO_OBJECT(pConverter);
  44939. result = ma_data_converter_get_heap_layout(pConfig, &heapLayout);
  44940. if (result != MA_SUCCESS) {
  44941. return result;
  44942. }
  44943. pConverter->_pHeap = pHeap;
  44944. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  44945. pConverter->formatIn = pConfig->formatIn;
  44946. pConverter->formatOut = pConfig->formatOut;
  44947. pConverter->channelsIn = pConfig->channelsIn;
  44948. pConverter->channelsOut = pConfig->channelsOut;
  44949. pConverter->sampleRateIn = pConfig->sampleRateIn;
  44950. pConverter->sampleRateOut = pConfig->sampleRateOut;
  44951. pConverter->ditherMode = pConfig->ditherMode;
  44952. /*
  44953. Determine if resampling is required. We need to do this so we can determine an appropriate
  44954. mid format to use. If resampling is required, the mid format must be ma_format_f32 since
  44955. that is the only one that is guaranteed to supported by custom resampling backends.
  44956. */
  44957. isResamplingRequired = ma_data_converter_config_is_resampler_required(pConfig);
  44958. midFormat = ma_data_converter_config_get_mid_format(pConfig);
  44959. /* Channel converter. We always initialize this, but we check if it configures itself as a passthrough to determine whether or not it's needed. */
  44960. {
  44961. ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig);
  44962. result = ma_channel_converter_init_preallocated(&channelConverterConfig, ma_offset_ptr(pHeap, heapLayout.channelConverterOffset), &pConverter->channelConverter);
  44963. if (result != MA_SUCCESS) {
  44964. return result;
  44965. }
  44966. /* If the channel converter is not a passthrough we need to enable it. Otherwise we can skip it. */
  44967. if (pConverter->channelConverter.conversionPath != ma_channel_conversion_path_passthrough) {
  44968. pConverter->hasChannelConverter = MA_TRUE;
  44969. }
  44970. }
  44971. /* Resampler. */
  44972. if (isResamplingRequired) {
  44973. ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig);
  44974. result = ma_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pConverter->resampler);
  44975. if (result != MA_SUCCESS) {
  44976. return result;
  44977. }
  44978. pConverter->hasResampler = MA_TRUE;
  44979. }
  44980. /* We can simplify pre- and post-format conversion if we have neither channel conversion nor resampling. */
  44981. if (pConverter->hasChannelConverter == MA_FALSE && pConverter->hasResampler == MA_FALSE) {
  44982. /* 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. */
  44983. if (pConverter->formatIn == pConverter->formatOut) {
  44984. /* The formats are the same so we can just pass through. */
  44985. pConverter->hasPreFormatConversion = MA_FALSE;
  44986. pConverter->hasPostFormatConversion = MA_FALSE;
  44987. } else {
  44988. /* The formats are different so we need to do either pre- or post-format conversion. It doesn't matter which. */
  44989. pConverter->hasPreFormatConversion = MA_FALSE;
  44990. pConverter->hasPostFormatConversion = MA_TRUE;
  44991. }
  44992. } else {
  44993. /* We have a channel converter and/or resampler so we'll need channel conversion based on the mid format. */
  44994. if (pConverter->formatIn != midFormat) {
  44995. pConverter->hasPreFormatConversion = MA_TRUE;
  44996. }
  44997. if (pConverter->formatOut != midFormat) {
  44998. pConverter->hasPostFormatConversion = MA_TRUE;
  44999. }
  45000. }
  45001. /* We can enable passthrough optimizations if applicable. Note that we'll only be able to do this if the sample rate is static. */
  45002. if (pConverter->hasPreFormatConversion == MA_FALSE &&
  45003. pConverter->hasPostFormatConversion == MA_FALSE &&
  45004. pConverter->hasChannelConverter == MA_FALSE &&
  45005. pConverter->hasResampler == MA_FALSE) {
  45006. pConverter->isPassthrough = MA_TRUE;
  45007. }
  45008. /* We now need to determine our execution path. */
  45009. if (pConverter->isPassthrough) {
  45010. pConverter->executionPath = ma_data_converter_execution_path_passthrough;
  45011. } else {
  45012. if (pConverter->channelsIn < pConverter->channelsOut) {
  45013. /* Do resampling first, if necessary. */
  45014. MA_ASSERT(pConverter->hasChannelConverter == MA_TRUE);
  45015. if (pConverter->hasResampler) {
  45016. pConverter->executionPath = ma_data_converter_execution_path_resample_first;
  45017. } else {
  45018. pConverter->executionPath = ma_data_converter_execution_path_channels_only;
  45019. }
  45020. } else {
  45021. /* Do channel conversion first, if necessary. */
  45022. if (pConverter->hasChannelConverter) {
  45023. if (pConverter->hasResampler) {
  45024. pConverter->executionPath = ma_data_converter_execution_path_channels_first;
  45025. } else {
  45026. pConverter->executionPath = ma_data_converter_execution_path_channels_only;
  45027. }
  45028. } else {
  45029. /* Channel routing not required. */
  45030. if (pConverter->hasResampler) {
  45031. pConverter->executionPath = ma_data_converter_execution_path_resample_only;
  45032. } else {
  45033. pConverter->executionPath = ma_data_converter_execution_path_format_only;
  45034. }
  45035. }
  45036. }
  45037. }
  45038. return MA_SUCCESS;
  45039. }
  45040. MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter)
  45041. {
  45042. ma_result result;
  45043. size_t heapSizeInBytes;
  45044. void* pHeap;
  45045. result = ma_data_converter_get_heap_size(pConfig, &heapSizeInBytes);
  45046. if (result != MA_SUCCESS) {
  45047. return result;
  45048. }
  45049. if (heapSizeInBytes > 0) {
  45050. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  45051. if (pHeap == NULL) {
  45052. return MA_OUT_OF_MEMORY;
  45053. }
  45054. } else {
  45055. pHeap = NULL;
  45056. }
  45057. result = ma_data_converter_init_preallocated(pConfig, pHeap, pConverter);
  45058. if (result != MA_SUCCESS) {
  45059. ma_free(pHeap, pAllocationCallbacks);
  45060. return result;
  45061. }
  45062. pConverter->_ownsHeap = MA_TRUE;
  45063. return MA_SUCCESS;
  45064. }
  45065. MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks)
  45066. {
  45067. if (pConverter == NULL) {
  45068. return;
  45069. }
  45070. if (pConverter->hasResampler) {
  45071. ma_resampler_uninit(&pConverter->resampler, pAllocationCallbacks);
  45072. }
  45073. ma_channel_converter_uninit(&pConverter->channelConverter, pAllocationCallbacks);
  45074. if (pConverter->_ownsHeap) {
  45075. ma_free(pConverter->_pHeap, pAllocationCallbacks);
  45076. }
  45077. }
  45078. 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)
  45079. {
  45080. ma_uint64 frameCountIn;
  45081. ma_uint64 frameCountOut;
  45082. ma_uint64 frameCount;
  45083. MA_ASSERT(pConverter != NULL);
  45084. frameCountIn = 0;
  45085. if (pFrameCountIn != NULL) {
  45086. frameCountIn = *pFrameCountIn;
  45087. }
  45088. frameCountOut = 0;
  45089. if (pFrameCountOut != NULL) {
  45090. frameCountOut = *pFrameCountOut;
  45091. }
  45092. frameCount = ma_min(frameCountIn, frameCountOut);
  45093. if (pFramesOut != NULL) {
  45094. if (pFramesIn != NULL) {
  45095. ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45096. } else {
  45097. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45098. }
  45099. }
  45100. if (pFrameCountIn != NULL) {
  45101. *pFrameCountIn = frameCount;
  45102. }
  45103. if (pFrameCountOut != NULL) {
  45104. *pFrameCountOut = frameCount;
  45105. }
  45106. return MA_SUCCESS;
  45107. }
  45108. 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)
  45109. {
  45110. ma_uint64 frameCountIn;
  45111. ma_uint64 frameCountOut;
  45112. ma_uint64 frameCount;
  45113. MA_ASSERT(pConverter != NULL);
  45114. frameCountIn = 0;
  45115. if (pFrameCountIn != NULL) {
  45116. frameCountIn = *pFrameCountIn;
  45117. }
  45118. frameCountOut = 0;
  45119. if (pFrameCountOut != NULL) {
  45120. frameCountOut = *pFrameCountOut;
  45121. }
  45122. frameCount = ma_min(frameCountIn, frameCountOut);
  45123. if (pFramesOut != NULL) {
  45124. if (pFramesIn != NULL) {
  45125. ma_convert_pcm_frames_format(pFramesOut, pConverter->formatOut, pFramesIn, pConverter->formatIn, frameCount, pConverter->channelsIn, pConverter->ditherMode);
  45126. } else {
  45127. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45128. }
  45129. }
  45130. if (pFrameCountIn != NULL) {
  45131. *pFrameCountIn = frameCount;
  45132. }
  45133. if (pFrameCountOut != NULL) {
  45134. *pFrameCountOut = frameCount;
  45135. }
  45136. return MA_SUCCESS;
  45137. }
  45138. 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)
  45139. {
  45140. ma_result result = MA_SUCCESS;
  45141. ma_uint64 frameCountIn;
  45142. ma_uint64 frameCountOut;
  45143. ma_uint64 framesProcessedIn;
  45144. ma_uint64 framesProcessedOut;
  45145. MA_ASSERT(pConverter != NULL);
  45146. frameCountIn = 0;
  45147. if (pFrameCountIn != NULL) {
  45148. frameCountIn = *pFrameCountIn;
  45149. }
  45150. frameCountOut = 0;
  45151. if (pFrameCountOut != NULL) {
  45152. frameCountOut = *pFrameCountOut;
  45153. }
  45154. framesProcessedIn = 0;
  45155. framesProcessedOut = 0;
  45156. while (framesProcessedOut < frameCountOut) {
  45157. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45158. const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45159. const void* pFramesInThisIteration;
  45160. /* */ void* pFramesOutThisIteration;
  45161. ma_uint64 frameCountInThisIteration;
  45162. ma_uint64 frameCountOutThisIteration;
  45163. if (pFramesIn != NULL) {
  45164. pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45165. } else {
  45166. pFramesInThisIteration = NULL;
  45167. }
  45168. if (pFramesOut != NULL) {
  45169. pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45170. } else {
  45171. pFramesOutThisIteration = NULL;
  45172. }
  45173. /* Do a pre format conversion if necessary. */
  45174. if (pConverter->hasPreFormatConversion) {
  45175. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45176. const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45177. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45178. if (frameCountInThisIteration > tempBufferInCap) {
  45179. frameCountInThisIteration = tempBufferInCap;
  45180. }
  45181. if (pConverter->hasPostFormatConversion) {
  45182. if (frameCountInThisIteration > tempBufferOutCap) {
  45183. frameCountInThisIteration = tempBufferOutCap;
  45184. }
  45185. }
  45186. if (pFramesInThisIteration != NULL) {
  45187. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pFramesInThisIteration, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45188. } else {
  45189. MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
  45190. }
  45191. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45192. if (pConverter->hasPostFormatConversion) {
  45193. /* Both input and output conversion required. Output to the temp buffer. */
  45194. if (frameCountOutThisIteration > tempBufferOutCap) {
  45195. frameCountOutThisIteration = tempBufferOutCap;
  45196. }
  45197. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
  45198. } else {
  45199. /* Only pre-format required. Output straight to the output buffer. */
  45200. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pFramesOutThisIteration, &frameCountOutThisIteration);
  45201. }
  45202. if (result != MA_SUCCESS) {
  45203. break;
  45204. }
  45205. } else {
  45206. /* No pre-format required. Just read straight from the input buffer. */
  45207. MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
  45208. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45209. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45210. if (frameCountOutThisIteration > tempBufferOutCap) {
  45211. frameCountOutThisIteration = tempBufferOutCap;
  45212. }
  45213. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesInThisIteration, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
  45214. if (result != MA_SUCCESS) {
  45215. break;
  45216. }
  45217. }
  45218. /* If we are doing a post format conversion we need to do that now. */
  45219. if (pConverter->hasPostFormatConversion) {
  45220. if (pFramesOutThisIteration != NULL) {
  45221. ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->resampler.channels, pConverter->ditherMode);
  45222. }
  45223. }
  45224. framesProcessedIn += frameCountInThisIteration;
  45225. framesProcessedOut += frameCountOutThisIteration;
  45226. MA_ASSERT(framesProcessedIn <= frameCountIn);
  45227. MA_ASSERT(framesProcessedOut <= frameCountOut);
  45228. if (frameCountOutThisIteration == 0) {
  45229. break; /* Consumed all of our input data. */
  45230. }
  45231. }
  45232. if (pFrameCountIn != NULL) {
  45233. *pFrameCountIn = framesProcessedIn;
  45234. }
  45235. if (pFrameCountOut != NULL) {
  45236. *pFrameCountOut = framesProcessedOut;
  45237. }
  45238. return result;
  45239. }
  45240. 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)
  45241. {
  45242. MA_ASSERT(pConverter != NULL);
  45243. if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
  45244. /* Neither pre- nor post-format required. This is simple case where only resampling is required. */
  45245. return ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45246. } else {
  45247. /* Format conversion required. */
  45248. return ma_data_converter_process_pcm_frames__resample_with_format_conversion(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45249. }
  45250. }
  45251. 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)
  45252. {
  45253. ma_result result;
  45254. ma_uint64 frameCountIn;
  45255. ma_uint64 frameCountOut;
  45256. ma_uint64 frameCount;
  45257. MA_ASSERT(pConverter != NULL);
  45258. frameCountIn = 0;
  45259. if (pFrameCountIn != NULL) {
  45260. frameCountIn = *pFrameCountIn;
  45261. }
  45262. frameCountOut = 0;
  45263. if (pFrameCountOut != NULL) {
  45264. frameCountOut = *pFrameCountOut;
  45265. }
  45266. frameCount = ma_min(frameCountIn, frameCountOut);
  45267. if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
  45268. /* No format conversion required. */
  45269. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOut, pFramesIn, frameCount);
  45270. if (result != MA_SUCCESS) {
  45271. return result;
  45272. }
  45273. } else {
  45274. /* Format conversion required. */
  45275. ma_uint64 framesProcessed = 0;
  45276. while (framesProcessed < frameCount) {
  45277. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45278. const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  45279. const void* pFramesInThisIteration;
  45280. /* */ void* pFramesOutThisIteration;
  45281. ma_uint64 frameCountThisIteration;
  45282. if (pFramesIn != NULL) {
  45283. pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessed * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45284. } else {
  45285. pFramesInThisIteration = NULL;
  45286. }
  45287. if (pFramesOut != NULL) {
  45288. pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessed * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45289. } else {
  45290. pFramesOutThisIteration = NULL;
  45291. }
  45292. /* Do a pre format conversion if necessary. */
  45293. if (pConverter->hasPreFormatConversion) {
  45294. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  45295. const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
  45296. frameCountThisIteration = (frameCount - framesProcessed);
  45297. if (frameCountThisIteration > tempBufferInCap) {
  45298. frameCountThisIteration = tempBufferInCap;
  45299. }
  45300. if (pConverter->hasPostFormatConversion) {
  45301. if (frameCountThisIteration > tempBufferOutCap) {
  45302. frameCountThisIteration = tempBufferOutCap;
  45303. }
  45304. }
  45305. if (pFramesInThisIteration != NULL) {
  45306. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pFramesInThisIteration, pConverter->formatIn, frameCountThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45307. } else {
  45308. MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
  45309. }
  45310. if (pConverter->hasPostFormatConversion) {
  45311. /* Both input and output conversion required. Output to the temp buffer. */
  45312. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pTempBufferIn, frameCountThisIteration);
  45313. } else {
  45314. /* Only pre-format required. Output straight to the output buffer. */
  45315. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOutThisIteration, pTempBufferIn, frameCountThisIteration);
  45316. }
  45317. if (result != MA_SUCCESS) {
  45318. break;
  45319. }
  45320. } else {
  45321. /* No pre-format required. Just read straight from the input buffer. */
  45322. MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
  45323. frameCountThisIteration = (frameCount - framesProcessed);
  45324. if (frameCountThisIteration > tempBufferOutCap) {
  45325. frameCountThisIteration = tempBufferOutCap;
  45326. }
  45327. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pFramesInThisIteration, frameCountThisIteration);
  45328. if (result != MA_SUCCESS) {
  45329. break;
  45330. }
  45331. }
  45332. /* If we are doing a post format conversion we need to do that now. */
  45333. if (pConverter->hasPostFormatConversion) {
  45334. if (pFramesOutThisIteration != NULL) {
  45335. ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->channelConverter.format, frameCountThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode);
  45336. }
  45337. }
  45338. framesProcessed += frameCountThisIteration;
  45339. }
  45340. }
  45341. if (pFrameCountIn != NULL) {
  45342. *pFrameCountIn = frameCount;
  45343. }
  45344. if (pFrameCountOut != NULL) {
  45345. *pFrameCountOut = frameCount;
  45346. }
  45347. return MA_SUCCESS;
  45348. }
  45349. 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)
  45350. {
  45351. ma_result result;
  45352. ma_uint64 frameCountIn;
  45353. ma_uint64 frameCountOut;
  45354. ma_uint64 framesProcessedIn;
  45355. ma_uint64 framesProcessedOut;
  45356. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
  45357. ma_uint64 tempBufferInCap;
  45358. ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
  45359. ma_uint64 tempBufferMidCap;
  45360. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
  45361. ma_uint64 tempBufferOutCap;
  45362. MA_ASSERT(pConverter != NULL);
  45363. MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format);
  45364. MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsIn);
  45365. MA_ASSERT(pConverter->resampler.channels < pConverter->channelConverter.channelsOut);
  45366. frameCountIn = 0;
  45367. if (pFrameCountIn != NULL) {
  45368. frameCountIn = *pFrameCountIn;
  45369. }
  45370. frameCountOut = 0;
  45371. if (pFrameCountOut != NULL) {
  45372. frameCountOut = *pFrameCountOut;
  45373. }
  45374. framesProcessedIn = 0;
  45375. framesProcessedOut = 0;
  45376. tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45377. tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45378. tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  45379. while (framesProcessedOut < frameCountOut) {
  45380. ma_uint64 frameCountInThisIteration;
  45381. ma_uint64 frameCountOutThisIteration;
  45382. const void* pRunningFramesIn = NULL;
  45383. void* pRunningFramesOut = NULL;
  45384. const void* pResampleBufferIn;
  45385. void* pChannelsBufferOut;
  45386. if (pFramesIn != NULL) {
  45387. pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45388. }
  45389. if (pFramesOut != NULL) {
  45390. pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45391. }
  45392. /* Run input data through the resampler and output it to the temporary buffer. */
  45393. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45394. if (pConverter->hasPreFormatConversion) {
  45395. if (frameCountInThisIteration > tempBufferInCap) {
  45396. frameCountInThisIteration = tempBufferInCap;
  45397. }
  45398. }
  45399. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45400. if (frameCountOutThisIteration > tempBufferMidCap) {
  45401. frameCountOutThisIteration = tempBufferMidCap;
  45402. }
  45403. /* We can't read more frames than can fit in the output buffer. */
  45404. if (pConverter->hasPostFormatConversion) {
  45405. if (frameCountOutThisIteration > tempBufferOutCap) {
  45406. frameCountOutThisIteration = tempBufferOutCap;
  45407. }
  45408. }
  45409. /* 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. */
  45410. /*
  45411. We need to try to predict how many input frames will be required for the resampler. If the
  45412. resampler can tell us, we'll use that. Otherwise we'll need to make a best guess. The further
  45413. off we are from this, the more wasted format conversions we'll end up doing.
  45414. */
  45415. #if 1
  45416. {
  45417. ma_uint64 requiredInputFrameCount;
  45418. result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount);
  45419. if (result != MA_SUCCESS) {
  45420. /* Fall back to a best guess. */
  45421. requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut;
  45422. }
  45423. if (frameCountInThisIteration > requiredInputFrameCount) {
  45424. frameCountInThisIteration = requiredInputFrameCount;
  45425. }
  45426. }
  45427. #endif
  45428. if (pConverter->hasPreFormatConversion) {
  45429. if (pFramesIn != NULL) {
  45430. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45431. pResampleBufferIn = pTempBufferIn;
  45432. } else {
  45433. pResampleBufferIn = NULL;
  45434. }
  45435. } else {
  45436. pResampleBufferIn = pRunningFramesIn;
  45437. }
  45438. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pResampleBufferIn, &frameCountInThisIteration, pTempBufferMid, &frameCountOutThisIteration);
  45439. if (result != MA_SUCCESS) {
  45440. return result;
  45441. }
  45442. /*
  45443. 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
  45444. this part if we have an output buffer.
  45445. */
  45446. if (pFramesOut != NULL) {
  45447. if (pConverter->hasPostFormatConversion) {
  45448. pChannelsBufferOut = pTempBufferOut;
  45449. } else {
  45450. pChannelsBufferOut = pRunningFramesOut;
  45451. }
  45452. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pChannelsBufferOut, pTempBufferMid, frameCountOutThisIteration);
  45453. if (result != MA_SUCCESS) {
  45454. return result;
  45455. }
  45456. /* Finally we do post format conversion. */
  45457. if (pConverter->hasPostFormatConversion) {
  45458. ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pChannelsBufferOut, pConverter->channelConverter.format, frameCountOutThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode);
  45459. }
  45460. }
  45461. framesProcessedIn += frameCountInThisIteration;
  45462. framesProcessedOut += frameCountOutThisIteration;
  45463. MA_ASSERT(framesProcessedIn <= frameCountIn);
  45464. MA_ASSERT(framesProcessedOut <= frameCountOut);
  45465. if (frameCountOutThisIteration == 0) {
  45466. break; /* Consumed all of our input data. */
  45467. }
  45468. }
  45469. if (pFrameCountIn != NULL) {
  45470. *pFrameCountIn = framesProcessedIn;
  45471. }
  45472. if (pFrameCountOut != NULL) {
  45473. *pFrameCountOut = framesProcessedOut;
  45474. }
  45475. return MA_SUCCESS;
  45476. }
  45477. 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)
  45478. {
  45479. ma_result result;
  45480. ma_uint64 frameCountIn;
  45481. ma_uint64 frameCountOut;
  45482. ma_uint64 framesProcessedIn;
  45483. ma_uint64 framesProcessedOut;
  45484. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
  45485. ma_uint64 tempBufferInCap;
  45486. ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
  45487. ma_uint64 tempBufferMidCap;
  45488. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
  45489. ma_uint64 tempBufferOutCap;
  45490. MA_ASSERT(pConverter != NULL);
  45491. MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format);
  45492. MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsOut);
  45493. MA_ASSERT(pConverter->resampler.channels <= pConverter->channelConverter.channelsIn);
  45494. frameCountIn = 0;
  45495. if (pFrameCountIn != NULL) {
  45496. frameCountIn = *pFrameCountIn;
  45497. }
  45498. frameCountOut = 0;
  45499. if (pFrameCountOut != NULL) {
  45500. frameCountOut = *pFrameCountOut;
  45501. }
  45502. framesProcessedIn = 0;
  45503. framesProcessedOut = 0;
  45504. tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
  45505. tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  45506. tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  45507. while (framesProcessedOut < frameCountOut) {
  45508. ma_uint64 frameCountInThisIteration;
  45509. ma_uint64 frameCountOutThisIteration;
  45510. const void* pRunningFramesIn = NULL;
  45511. void* pRunningFramesOut = NULL;
  45512. const void* pChannelsBufferIn;
  45513. void* pResampleBufferOut;
  45514. if (pFramesIn != NULL) {
  45515. pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  45516. }
  45517. if (pFramesOut != NULL) {
  45518. pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  45519. }
  45520. /*
  45521. Before doing any processing we need to determine how many frames we should try processing
  45522. this iteration, for both input and output. The resampler requires us to perform format and
  45523. channel conversion before passing any data into it. If we get our input count wrong, we'll
  45524. end up peforming redundant pre-processing. This isn't the end of the world, but it does
  45525. result in some inefficiencies proportionate to how far our estimates are off.
  45526. If the resampler has a means to calculate exactly how much we'll need, we'll use that.
  45527. Otherwise we'll make a best guess. In order to do this, we'll need to calculate the output
  45528. frame count first.
  45529. */
  45530. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  45531. if (frameCountOutThisIteration > tempBufferMidCap) {
  45532. frameCountOutThisIteration = tempBufferMidCap;
  45533. }
  45534. if (pConverter->hasPostFormatConversion) {
  45535. if (frameCountOutThisIteration > tempBufferOutCap) {
  45536. frameCountOutThisIteration = tempBufferOutCap;
  45537. }
  45538. }
  45539. /* Now that we have the output frame count we can determine the input frame count. */
  45540. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  45541. if (pConverter->hasPreFormatConversion) {
  45542. if (frameCountInThisIteration > tempBufferInCap) {
  45543. frameCountInThisIteration = tempBufferInCap;
  45544. }
  45545. }
  45546. if (frameCountInThisIteration > tempBufferMidCap) {
  45547. frameCountInThisIteration = tempBufferMidCap;
  45548. }
  45549. #if 1
  45550. {
  45551. ma_uint64 requiredInputFrameCount;
  45552. result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount);
  45553. if (result != MA_SUCCESS) {
  45554. /* Fall back to a best guess. */
  45555. requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut;
  45556. }
  45557. if (frameCountInThisIteration > requiredInputFrameCount) {
  45558. frameCountInThisIteration = requiredInputFrameCount;
  45559. }
  45560. }
  45561. #endif
  45562. /* Pre format conversion. */
  45563. if (pConverter->hasPreFormatConversion) {
  45564. if (pRunningFramesIn != NULL) {
  45565. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  45566. pChannelsBufferIn = pTempBufferIn;
  45567. } else {
  45568. pChannelsBufferIn = NULL;
  45569. }
  45570. } else {
  45571. pChannelsBufferIn = pRunningFramesIn;
  45572. }
  45573. /* Channel conversion. */
  45574. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferMid, pChannelsBufferIn, frameCountInThisIteration);
  45575. if (result != MA_SUCCESS) {
  45576. return result;
  45577. }
  45578. /* Resampling. */
  45579. if (pConverter->hasPostFormatConversion) {
  45580. pResampleBufferOut = pTempBufferOut;
  45581. } else {
  45582. pResampleBufferOut = pRunningFramesOut;
  45583. }
  45584. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferMid, &frameCountInThisIteration, pResampleBufferOut, &frameCountOutThisIteration);
  45585. if (result != MA_SUCCESS) {
  45586. return result;
  45587. }
  45588. /* Post format conversion. */
  45589. if (pConverter->hasPostFormatConversion) {
  45590. if (pRunningFramesOut != NULL) {
  45591. ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pResampleBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->channelsOut, pConverter->ditherMode);
  45592. }
  45593. }
  45594. framesProcessedIn += frameCountInThisIteration;
  45595. framesProcessedOut += frameCountOutThisIteration;
  45596. MA_ASSERT(framesProcessedIn <= frameCountIn);
  45597. MA_ASSERT(framesProcessedOut <= frameCountOut);
  45598. if (frameCountOutThisIteration == 0) {
  45599. break; /* Consumed all of our input data. */
  45600. }
  45601. }
  45602. if (pFrameCountIn != NULL) {
  45603. *pFrameCountIn = framesProcessedIn;
  45604. }
  45605. if (pFrameCountOut != NULL) {
  45606. *pFrameCountOut = framesProcessedOut;
  45607. }
  45608. return MA_SUCCESS;
  45609. }
  45610. 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)
  45611. {
  45612. if (pConverter == NULL) {
  45613. return MA_INVALID_ARGS;
  45614. }
  45615. switch (pConverter->executionPath)
  45616. {
  45617. case ma_data_converter_execution_path_passthrough: return ma_data_converter_process_pcm_frames__passthrough(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45618. case ma_data_converter_execution_path_format_only: return ma_data_converter_process_pcm_frames__format_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45619. case ma_data_converter_execution_path_channels_only: return ma_data_converter_process_pcm_frames__channels_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45620. case ma_data_converter_execution_path_resample_only: return ma_data_converter_process_pcm_frames__resample_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45621. case ma_data_converter_execution_path_resample_first: return ma_data_converter_process_pcm_frames__resample_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45622. case ma_data_converter_execution_path_channels_first: return ma_data_converter_process_pcm_frames__channels_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  45623. default: return MA_INVALID_OPERATION; /* Should never hit this. */
  45624. }
  45625. }
  45626. MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  45627. {
  45628. if (pConverter == NULL) {
  45629. return MA_INVALID_ARGS;
  45630. }
  45631. if (pConverter->hasResampler == MA_FALSE) {
  45632. return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
  45633. }
  45634. return ma_resampler_set_rate(&pConverter->resampler, sampleRateIn, sampleRateOut);
  45635. }
  45636. MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut)
  45637. {
  45638. if (pConverter == NULL) {
  45639. return MA_INVALID_ARGS;
  45640. }
  45641. if (pConverter->hasResampler == MA_FALSE) {
  45642. return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
  45643. }
  45644. return ma_resampler_set_rate_ratio(&pConverter->resampler, ratioInOut);
  45645. }
  45646. MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter)
  45647. {
  45648. if (pConverter == NULL) {
  45649. return 0;
  45650. }
  45651. if (pConverter->hasResampler) {
  45652. return ma_resampler_get_input_latency(&pConverter->resampler);
  45653. }
  45654. return 0; /* No latency without a resampler. */
  45655. }
  45656. MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter)
  45657. {
  45658. if (pConverter == NULL) {
  45659. return 0;
  45660. }
  45661. if (pConverter->hasResampler) {
  45662. return ma_resampler_get_output_latency(&pConverter->resampler);
  45663. }
  45664. return 0; /* No latency without a resampler. */
  45665. }
  45666. MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  45667. {
  45668. if (pInputFrameCount == NULL) {
  45669. return MA_INVALID_ARGS;
  45670. }
  45671. *pInputFrameCount = 0;
  45672. if (pConverter == NULL) {
  45673. return MA_INVALID_ARGS;
  45674. }
  45675. if (pConverter->hasResampler) {
  45676. return ma_resampler_get_required_input_frame_count(&pConverter->resampler, outputFrameCount, pInputFrameCount);
  45677. } else {
  45678. *pInputFrameCount = outputFrameCount; /* 1:1 */
  45679. return MA_SUCCESS;
  45680. }
  45681. }
  45682. MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  45683. {
  45684. if (pOutputFrameCount == NULL) {
  45685. return MA_INVALID_ARGS;
  45686. }
  45687. *pOutputFrameCount = 0;
  45688. if (pConverter == NULL) {
  45689. return MA_INVALID_ARGS;
  45690. }
  45691. if (pConverter->hasResampler) {
  45692. return ma_resampler_get_expected_output_frame_count(&pConverter->resampler, inputFrameCount, pOutputFrameCount);
  45693. } else {
  45694. *pOutputFrameCount = inputFrameCount; /* 1:1 */
  45695. return MA_SUCCESS;
  45696. }
  45697. }
  45698. MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  45699. {
  45700. if (pConverter == NULL || pChannelMap == NULL) {
  45701. return MA_INVALID_ARGS;
  45702. }
  45703. if (pConverter->hasChannelConverter) {
  45704. ma_channel_converter_get_output_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap);
  45705. } else {
  45706. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsOut);
  45707. }
  45708. return MA_SUCCESS;
  45709. }
  45710. MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  45711. {
  45712. if (pConverter == NULL || pChannelMap == NULL) {
  45713. return MA_INVALID_ARGS;
  45714. }
  45715. if (pConverter->hasChannelConverter) {
  45716. ma_channel_converter_get_input_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap);
  45717. } else {
  45718. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsIn);
  45719. }
  45720. return MA_SUCCESS;
  45721. }
  45722. MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter)
  45723. {
  45724. if (pConverter == NULL) {
  45725. return MA_INVALID_ARGS;
  45726. }
  45727. /* There's nothing to do if we're not resampling. */
  45728. if (pConverter->hasResampler == MA_FALSE) {
  45729. return MA_SUCCESS;
  45730. }
  45731. return ma_resampler_reset(&pConverter->resampler);
  45732. }
  45733. /**************************************************************************************************************************************************************
  45734. Channel Maps
  45735. **************************************************************************************************************************************************************/
  45736. static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
  45737. MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex)
  45738. {
  45739. if (pChannelMap == NULL) {
  45740. return ma_channel_map_init_standard_channel(ma_standard_channel_map_default, channelCount, channelIndex);
  45741. } else {
  45742. if (channelIndex >= channelCount) {
  45743. return MA_CHANNEL_NONE;
  45744. }
  45745. return pChannelMap[channelIndex];
  45746. }
  45747. }
  45748. MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels)
  45749. {
  45750. if (pChannelMap == NULL) {
  45751. return;
  45752. }
  45753. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channels);
  45754. }
  45755. static ma_channel ma_channel_map_init_standard_channel_microsoft(ma_uint32 channelCount, ma_uint32 channelIndex)
  45756. {
  45757. if (channelCount == 0 || channelIndex >= channelCount) {
  45758. return MA_CHANNEL_NONE;
  45759. }
  45760. /* 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 */
  45761. switch (channelCount)
  45762. {
  45763. case 0: return MA_CHANNEL_NONE;
  45764. case 1:
  45765. {
  45766. return MA_CHANNEL_MONO;
  45767. } break;
  45768. case 2:
  45769. {
  45770. switch (channelIndex) {
  45771. case 0: return MA_CHANNEL_FRONT_LEFT;
  45772. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45773. }
  45774. } break;
  45775. case 3: /* No defined, but best guess. */
  45776. {
  45777. switch (channelIndex) {
  45778. case 0: return MA_CHANNEL_FRONT_LEFT;
  45779. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45780. case 2: return MA_CHANNEL_FRONT_CENTER;
  45781. }
  45782. } break;
  45783. case 4:
  45784. {
  45785. switch (channelIndex) {
  45786. #ifndef MA_USE_QUAD_MICROSOFT_CHANNEL_MAP
  45787. /* Surround. Using the Surround profile has the advantage of the 3rd channel (MA_CHANNEL_FRONT_CENTER) mapping nicely with higher channel counts. */
  45788. case 0: return MA_CHANNEL_FRONT_LEFT;
  45789. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45790. case 2: return MA_CHANNEL_FRONT_CENTER;
  45791. case 3: return MA_CHANNEL_BACK_CENTER;
  45792. #else
  45793. /* Quad. */
  45794. case 0: return MA_CHANNEL_FRONT_LEFT;
  45795. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45796. case 2: return MA_CHANNEL_BACK_LEFT;
  45797. case 3: return MA_CHANNEL_BACK_RIGHT;
  45798. #endif
  45799. }
  45800. } break;
  45801. case 5: /* Not defined, but best guess. */
  45802. {
  45803. switch (channelIndex) {
  45804. case 0: return MA_CHANNEL_FRONT_LEFT;
  45805. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45806. case 2: return MA_CHANNEL_FRONT_CENTER;
  45807. case 3: return MA_CHANNEL_BACK_LEFT;
  45808. case 4: return MA_CHANNEL_BACK_RIGHT;
  45809. }
  45810. } break;
  45811. case 6:
  45812. {
  45813. switch (channelIndex) {
  45814. case 0: return MA_CHANNEL_FRONT_LEFT;
  45815. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45816. case 2: return MA_CHANNEL_FRONT_CENTER;
  45817. case 3: return MA_CHANNEL_LFE;
  45818. case 4: return MA_CHANNEL_SIDE_LEFT;
  45819. case 5: return MA_CHANNEL_SIDE_RIGHT;
  45820. }
  45821. } break;
  45822. case 7: /* Not defined, but best guess. */
  45823. {
  45824. switch (channelIndex) {
  45825. case 0: return MA_CHANNEL_FRONT_LEFT;
  45826. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45827. case 2: return MA_CHANNEL_FRONT_CENTER;
  45828. case 3: return MA_CHANNEL_LFE;
  45829. case 4: return MA_CHANNEL_BACK_CENTER;
  45830. case 5: return MA_CHANNEL_SIDE_LEFT;
  45831. case 6: return MA_CHANNEL_SIDE_RIGHT;
  45832. }
  45833. } break;
  45834. case 8:
  45835. default:
  45836. {
  45837. switch (channelIndex) {
  45838. case 0: return MA_CHANNEL_FRONT_LEFT;
  45839. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45840. case 2: return MA_CHANNEL_FRONT_CENTER;
  45841. case 3: return MA_CHANNEL_LFE;
  45842. case 4: return MA_CHANNEL_BACK_LEFT;
  45843. case 5: return MA_CHANNEL_BACK_RIGHT;
  45844. case 6: return MA_CHANNEL_SIDE_LEFT;
  45845. case 7: return MA_CHANNEL_SIDE_RIGHT;
  45846. }
  45847. } break;
  45848. }
  45849. if (channelCount > 8) {
  45850. if (channelIndex < 32) { /* We have 32 AUX channels. */
  45851. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  45852. }
  45853. }
  45854. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  45855. return MA_CHANNEL_NONE;
  45856. }
  45857. static ma_channel ma_channel_map_init_standard_channel_alsa(ma_uint32 channelCount, ma_uint32 channelIndex)
  45858. {
  45859. switch (channelCount)
  45860. {
  45861. case 0: return MA_CHANNEL_NONE;
  45862. case 1:
  45863. {
  45864. return MA_CHANNEL_MONO;
  45865. } break;
  45866. case 2:
  45867. {
  45868. switch (channelIndex) {
  45869. case 0: return MA_CHANNEL_FRONT_LEFT;
  45870. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45871. }
  45872. } break;
  45873. case 3:
  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_FRONT_CENTER;
  45879. }
  45880. } break;
  45881. case 4:
  45882. {
  45883. switch (channelIndex) {
  45884. case 0: return MA_CHANNEL_FRONT_LEFT;
  45885. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45886. case 2: return MA_CHANNEL_BACK_LEFT;
  45887. case 3: return MA_CHANNEL_BACK_RIGHT;
  45888. }
  45889. } break;
  45890. case 5:
  45891. {
  45892. switch (channelIndex) {
  45893. case 0: return MA_CHANNEL_FRONT_LEFT;
  45894. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45895. case 2: return MA_CHANNEL_BACK_LEFT;
  45896. case 3: return MA_CHANNEL_BACK_RIGHT;
  45897. case 4: return MA_CHANNEL_FRONT_CENTER;
  45898. }
  45899. } break;
  45900. case 6:
  45901. {
  45902. switch (channelIndex) {
  45903. case 0: return MA_CHANNEL_FRONT_LEFT;
  45904. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45905. case 2: return MA_CHANNEL_BACK_LEFT;
  45906. case 3: return MA_CHANNEL_BACK_RIGHT;
  45907. case 4: return MA_CHANNEL_FRONT_CENTER;
  45908. case 5: return MA_CHANNEL_LFE;
  45909. }
  45910. } break;
  45911. case 7:
  45912. {
  45913. switch (channelIndex) {
  45914. case 0: return MA_CHANNEL_FRONT_LEFT;
  45915. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45916. case 2: return MA_CHANNEL_BACK_LEFT;
  45917. case 3: return MA_CHANNEL_BACK_RIGHT;
  45918. case 4: return MA_CHANNEL_FRONT_CENTER;
  45919. case 5: return MA_CHANNEL_LFE;
  45920. case 6: return MA_CHANNEL_BACK_CENTER;
  45921. }
  45922. } break;
  45923. case 8:
  45924. default:
  45925. {
  45926. switch (channelIndex) {
  45927. case 0: return MA_CHANNEL_FRONT_LEFT;
  45928. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45929. case 2: return MA_CHANNEL_BACK_LEFT;
  45930. case 3: return MA_CHANNEL_BACK_RIGHT;
  45931. case 4: return MA_CHANNEL_FRONT_CENTER;
  45932. case 5: return MA_CHANNEL_LFE;
  45933. case 6: return MA_CHANNEL_SIDE_LEFT;
  45934. case 7: return MA_CHANNEL_SIDE_RIGHT;
  45935. }
  45936. } break;
  45937. }
  45938. if (channelCount > 8) {
  45939. if (channelIndex < 32) { /* We have 32 AUX channels. */
  45940. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  45941. }
  45942. }
  45943. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  45944. return MA_CHANNEL_NONE;
  45945. }
  45946. static ma_channel ma_channel_map_init_standard_channel_rfc3551(ma_uint32 channelCount, ma_uint32 channelIndex)
  45947. {
  45948. switch (channelCount)
  45949. {
  45950. case 0: return MA_CHANNEL_NONE;
  45951. case 1:
  45952. {
  45953. return MA_CHANNEL_MONO;
  45954. } break;
  45955. case 2:
  45956. {
  45957. switch (channelIndex) {
  45958. case 0: return MA_CHANNEL_FRONT_LEFT;
  45959. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45960. }
  45961. } break;
  45962. case 3:
  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. }
  45969. } break;
  45970. case 4:
  45971. {
  45972. switch (channelIndex) {
  45973. case 0: return MA_CHANNEL_FRONT_LEFT;
  45974. case 2: return MA_CHANNEL_FRONT_CENTER;
  45975. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45976. case 3: return MA_CHANNEL_BACK_CENTER;
  45977. }
  45978. } break;
  45979. case 5:
  45980. {
  45981. switch (channelIndex) {
  45982. case 0: return MA_CHANNEL_FRONT_LEFT;
  45983. case 1: return MA_CHANNEL_FRONT_RIGHT;
  45984. case 2: return MA_CHANNEL_FRONT_CENTER;
  45985. case 3: return MA_CHANNEL_BACK_LEFT;
  45986. case 4: return MA_CHANNEL_BACK_RIGHT;
  45987. }
  45988. } break;
  45989. case 6:
  45990. default:
  45991. {
  45992. switch (channelIndex) {
  45993. case 0: return MA_CHANNEL_FRONT_LEFT;
  45994. case 1: return MA_CHANNEL_SIDE_LEFT;
  45995. case 2: return MA_CHANNEL_FRONT_CENTER;
  45996. case 3: return MA_CHANNEL_FRONT_RIGHT;
  45997. case 4: return MA_CHANNEL_SIDE_RIGHT;
  45998. case 5: return MA_CHANNEL_BACK_CENTER;
  45999. }
  46000. } break;
  46001. }
  46002. if (channelCount > 6) {
  46003. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46004. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6));
  46005. }
  46006. }
  46007. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46008. return MA_CHANNEL_NONE;
  46009. }
  46010. static ma_channel ma_channel_map_init_standard_channel_flac(ma_uint32 channelCount, ma_uint32 channelIndex)
  46011. {
  46012. switch (channelCount)
  46013. {
  46014. case 0: return MA_CHANNEL_NONE;
  46015. case 1:
  46016. {
  46017. return MA_CHANNEL_MONO;
  46018. } break;
  46019. case 2:
  46020. {
  46021. switch (channelIndex) {
  46022. case 0: return MA_CHANNEL_FRONT_LEFT;
  46023. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46024. }
  46025. } break;
  46026. case 3:
  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. }
  46033. } break;
  46034. case 4:
  46035. {
  46036. switch (channelIndex) {
  46037. case 0: return MA_CHANNEL_FRONT_LEFT;
  46038. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46039. case 2: return MA_CHANNEL_BACK_LEFT;
  46040. case 3: return MA_CHANNEL_BACK_RIGHT;
  46041. }
  46042. } break;
  46043. case 5:
  46044. {
  46045. switch (channelIndex) {
  46046. case 0: return MA_CHANNEL_FRONT_LEFT;
  46047. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46048. case 2: return MA_CHANNEL_FRONT_CENTER;
  46049. case 3: return MA_CHANNEL_BACK_LEFT;
  46050. case 4: return MA_CHANNEL_BACK_RIGHT;
  46051. }
  46052. } break;
  46053. case 6:
  46054. {
  46055. switch (channelIndex) {
  46056. case 0: return MA_CHANNEL_FRONT_LEFT;
  46057. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46058. case 2: return MA_CHANNEL_FRONT_CENTER;
  46059. case 3: return MA_CHANNEL_LFE;
  46060. case 4: return MA_CHANNEL_BACK_LEFT;
  46061. case 5: return MA_CHANNEL_BACK_RIGHT;
  46062. }
  46063. } break;
  46064. case 7:
  46065. {
  46066. switch (channelIndex) {
  46067. case 0: return MA_CHANNEL_FRONT_LEFT;
  46068. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46069. case 2: return MA_CHANNEL_FRONT_CENTER;
  46070. case 3: return MA_CHANNEL_LFE;
  46071. case 4: return MA_CHANNEL_BACK_CENTER;
  46072. case 5: return MA_CHANNEL_SIDE_LEFT;
  46073. case 6: return MA_CHANNEL_SIDE_RIGHT;
  46074. }
  46075. } break;
  46076. case 8:
  46077. default:
  46078. {
  46079. switch (channelIndex) {
  46080. case 0: return MA_CHANNEL_FRONT_LEFT;
  46081. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46082. case 2: return MA_CHANNEL_FRONT_CENTER;
  46083. case 3: return MA_CHANNEL_LFE;
  46084. case 4: return MA_CHANNEL_BACK_LEFT;
  46085. case 5: return MA_CHANNEL_BACK_RIGHT;
  46086. case 6: return MA_CHANNEL_SIDE_LEFT;
  46087. case 7: return MA_CHANNEL_SIDE_RIGHT;
  46088. }
  46089. } break;
  46090. }
  46091. if (channelCount > 8) {
  46092. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46093. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  46094. }
  46095. }
  46096. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46097. return MA_CHANNEL_NONE;
  46098. }
  46099. static ma_channel ma_channel_map_init_standard_channel_vorbis(ma_uint32 channelCount, ma_uint32 channelIndex)
  46100. {
  46101. switch (channelCount)
  46102. {
  46103. case 0: return MA_CHANNEL_NONE;
  46104. case 1:
  46105. {
  46106. return MA_CHANNEL_MONO;
  46107. } break;
  46108. case 2:
  46109. {
  46110. switch (channelIndex) {
  46111. case 0: return MA_CHANNEL_FRONT_LEFT;
  46112. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46113. }
  46114. } break;
  46115. case 3:
  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. }
  46122. } break;
  46123. case 4:
  46124. {
  46125. switch (channelIndex) {
  46126. case 0: return MA_CHANNEL_FRONT_LEFT;
  46127. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46128. case 2: return MA_CHANNEL_BACK_LEFT;
  46129. case 3: return MA_CHANNEL_BACK_RIGHT;
  46130. }
  46131. } break;
  46132. case 5:
  46133. {
  46134. switch (channelIndex) {
  46135. case 0: return MA_CHANNEL_FRONT_LEFT;
  46136. case 1: return MA_CHANNEL_FRONT_CENTER;
  46137. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46138. case 3: return MA_CHANNEL_BACK_LEFT;
  46139. case 4: return MA_CHANNEL_BACK_RIGHT;
  46140. }
  46141. } break;
  46142. case 6:
  46143. {
  46144. switch (channelIndex) {
  46145. case 0: return MA_CHANNEL_FRONT_LEFT;
  46146. case 1: return MA_CHANNEL_FRONT_CENTER;
  46147. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46148. case 3: return MA_CHANNEL_BACK_LEFT;
  46149. case 4: return MA_CHANNEL_BACK_RIGHT;
  46150. case 5: return MA_CHANNEL_LFE;
  46151. }
  46152. } break;
  46153. case 7:
  46154. {
  46155. switch (channelIndex) {
  46156. case 0: return MA_CHANNEL_FRONT_LEFT;
  46157. case 1: return MA_CHANNEL_FRONT_CENTER;
  46158. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46159. case 3: return MA_CHANNEL_SIDE_LEFT;
  46160. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46161. case 5: return MA_CHANNEL_BACK_CENTER;
  46162. case 6: return MA_CHANNEL_LFE;
  46163. }
  46164. } break;
  46165. case 8:
  46166. default:
  46167. {
  46168. switch (channelIndex) {
  46169. case 0: return MA_CHANNEL_FRONT_LEFT;
  46170. case 1: return MA_CHANNEL_FRONT_CENTER;
  46171. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46172. case 3: return MA_CHANNEL_SIDE_LEFT;
  46173. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46174. case 5: return MA_CHANNEL_BACK_LEFT;
  46175. case 6: return MA_CHANNEL_BACK_RIGHT;
  46176. case 7: return MA_CHANNEL_LFE;
  46177. }
  46178. } break;
  46179. }
  46180. if (channelCount > 8) {
  46181. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46182. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  46183. }
  46184. }
  46185. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46186. return MA_CHANNEL_NONE;
  46187. }
  46188. static ma_channel ma_channel_map_init_standard_channel_sound4(ma_uint32 channelCount, ma_uint32 channelIndex)
  46189. {
  46190. switch (channelCount)
  46191. {
  46192. case 0: return MA_CHANNEL_NONE;
  46193. case 1:
  46194. {
  46195. return MA_CHANNEL_MONO;
  46196. } break;
  46197. case 2:
  46198. {
  46199. switch (channelIndex) {
  46200. case 0: return MA_CHANNEL_FRONT_LEFT;
  46201. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46202. }
  46203. } break;
  46204. case 3:
  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. }
  46211. } break;
  46212. case 4:
  46213. {
  46214. switch (channelIndex) {
  46215. case 0: return MA_CHANNEL_FRONT_LEFT;
  46216. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46217. case 2: return MA_CHANNEL_BACK_LEFT;
  46218. case 3: return MA_CHANNEL_BACK_RIGHT;
  46219. }
  46220. } break;
  46221. case 5:
  46222. {
  46223. switch (channelIndex) {
  46224. case 0: return MA_CHANNEL_FRONT_LEFT;
  46225. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46226. case 2: return MA_CHANNEL_FRONT_CENTER;
  46227. case 3: return MA_CHANNEL_BACK_LEFT;
  46228. case 4: return MA_CHANNEL_BACK_RIGHT;
  46229. }
  46230. } break;
  46231. case 6:
  46232. {
  46233. switch (channelIndex) {
  46234. case 0: return MA_CHANNEL_FRONT_LEFT;
  46235. case 1: return MA_CHANNEL_FRONT_CENTER;
  46236. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46237. case 3: return MA_CHANNEL_BACK_LEFT;
  46238. case 4: return MA_CHANNEL_BACK_RIGHT;
  46239. case 5: return MA_CHANNEL_LFE;
  46240. }
  46241. } break;
  46242. case 7:
  46243. {
  46244. switch (channelIndex) {
  46245. case 0: return MA_CHANNEL_FRONT_LEFT;
  46246. case 1: return MA_CHANNEL_FRONT_CENTER;
  46247. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46248. case 3: return MA_CHANNEL_SIDE_LEFT;
  46249. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46250. case 5: return MA_CHANNEL_BACK_CENTER;
  46251. case 6: return MA_CHANNEL_LFE;
  46252. }
  46253. } break;
  46254. case 8:
  46255. default:
  46256. {
  46257. switch (channelIndex) {
  46258. case 0: return MA_CHANNEL_FRONT_LEFT;
  46259. case 1: return MA_CHANNEL_FRONT_CENTER;
  46260. case 2: return MA_CHANNEL_FRONT_RIGHT;
  46261. case 3: return MA_CHANNEL_SIDE_LEFT;
  46262. case 4: return MA_CHANNEL_SIDE_RIGHT;
  46263. case 5: return MA_CHANNEL_BACK_LEFT;
  46264. case 6: return MA_CHANNEL_BACK_RIGHT;
  46265. case 7: return MA_CHANNEL_LFE;
  46266. }
  46267. } break;
  46268. }
  46269. if (channelCount > 8) {
  46270. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46271. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  46272. }
  46273. }
  46274. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46275. return MA_CHANNEL_NONE;
  46276. }
  46277. static ma_channel ma_channel_map_init_standard_channel_sndio(ma_uint32 channelCount, ma_uint32 channelIndex)
  46278. {
  46279. switch (channelCount)
  46280. {
  46281. case 0: return MA_CHANNEL_NONE;
  46282. case 1:
  46283. {
  46284. return MA_CHANNEL_MONO;
  46285. } break;
  46286. case 2:
  46287. {
  46288. switch (channelIndex) {
  46289. case 0: return MA_CHANNEL_FRONT_LEFT;
  46290. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46291. }
  46292. } break;
  46293. case 3: /* No 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_FRONT_CENTER;
  46299. }
  46300. } break;
  46301. case 4:
  46302. {
  46303. switch (channelIndex) {
  46304. case 0: return MA_CHANNEL_FRONT_LEFT;
  46305. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46306. case 2: return MA_CHANNEL_BACK_LEFT;
  46307. case 3: return MA_CHANNEL_BACK_RIGHT;
  46308. }
  46309. } break;
  46310. case 5: /* Not defined, but best guess. */
  46311. {
  46312. switch (channelIndex) {
  46313. case 0: return MA_CHANNEL_FRONT_LEFT;
  46314. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46315. case 2: return MA_CHANNEL_BACK_LEFT;
  46316. case 3: return MA_CHANNEL_BACK_RIGHT;
  46317. case 4: return MA_CHANNEL_FRONT_CENTER;
  46318. }
  46319. } break;
  46320. case 6:
  46321. default:
  46322. {
  46323. switch (channelIndex) {
  46324. case 0: return MA_CHANNEL_FRONT_LEFT;
  46325. case 1: return MA_CHANNEL_FRONT_RIGHT;
  46326. case 2: return MA_CHANNEL_BACK_LEFT;
  46327. case 3: return MA_CHANNEL_BACK_RIGHT;
  46328. case 4: return MA_CHANNEL_FRONT_CENTER;
  46329. case 5: return MA_CHANNEL_LFE;
  46330. }
  46331. } break;
  46332. }
  46333. if (channelCount > 6) {
  46334. if (channelIndex < 32) { /* We have 32 AUX channels. */
  46335. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6));
  46336. }
  46337. }
  46338. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  46339. return MA_CHANNEL_NONE;
  46340. }
  46341. static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex)
  46342. {
  46343. if (channelCount == 0 || channelIndex >= channelCount) {
  46344. return MA_CHANNEL_NONE;
  46345. }
  46346. switch (standardChannelMap)
  46347. {
  46348. case ma_standard_channel_map_alsa:
  46349. {
  46350. return ma_channel_map_init_standard_channel_alsa(channelCount, channelIndex);
  46351. } break;
  46352. case ma_standard_channel_map_rfc3551:
  46353. {
  46354. return ma_channel_map_init_standard_channel_rfc3551(channelCount, channelIndex);
  46355. } break;
  46356. case ma_standard_channel_map_flac:
  46357. {
  46358. return ma_channel_map_init_standard_channel_flac(channelCount, channelIndex);
  46359. } break;
  46360. case ma_standard_channel_map_vorbis:
  46361. {
  46362. return ma_channel_map_init_standard_channel_vorbis(channelCount, channelIndex);
  46363. } break;
  46364. case ma_standard_channel_map_sound4:
  46365. {
  46366. return ma_channel_map_init_standard_channel_sound4(channelCount, channelIndex);
  46367. } break;
  46368. case ma_standard_channel_map_sndio:
  46369. {
  46370. return ma_channel_map_init_standard_channel_sndio(channelCount, channelIndex);
  46371. } break;
  46372. case ma_standard_channel_map_microsoft: /* Also default. */
  46373. /*case ma_standard_channel_map_default;*/
  46374. default:
  46375. {
  46376. return ma_channel_map_init_standard_channel_microsoft(channelCount, channelIndex);
  46377. } break;
  46378. }
  46379. }
  46380. MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels)
  46381. {
  46382. ma_uint32 iChannel;
  46383. if (pChannelMap == NULL || channelMapCap == 0 || channels == 0) {
  46384. return;
  46385. }
  46386. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  46387. if (channelMapCap == 0) {
  46388. break; /* Ran out of room. */
  46389. }
  46390. pChannelMap[0] = ma_channel_map_init_standard_channel(standardChannelMap, channels, iChannel);
  46391. pChannelMap += 1;
  46392. channelMapCap -= 1;
  46393. }
  46394. }
  46395. MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels)
  46396. {
  46397. if (pOut != NULL && pIn != NULL && channels > 0) {
  46398. MA_COPY_MEMORY(pOut, pIn, sizeof(*pOut) * channels);
  46399. }
  46400. }
  46401. MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels)
  46402. {
  46403. if (pOut == NULL || channels == 0) {
  46404. return;
  46405. }
  46406. if (pIn != NULL) {
  46407. ma_channel_map_copy(pOut, pIn, channels);
  46408. } else {
  46409. ma_channel_map_init_standard(ma_standard_channel_map_default, pOut, channelMapCapOut, channels);
  46410. }
  46411. }
  46412. MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels)
  46413. {
  46414. /* A channel count of 0 is invalid. */
  46415. if (channels == 0) {
  46416. return MA_FALSE;
  46417. }
  46418. /* It does not make sense to have a mono channel when there is more than 1 channel. */
  46419. if (channels > 1) {
  46420. ma_uint32 iChannel;
  46421. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46422. if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == MA_CHANNEL_MONO) {
  46423. return MA_FALSE;
  46424. }
  46425. }
  46426. }
  46427. return MA_TRUE;
  46428. }
  46429. MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels)
  46430. {
  46431. ma_uint32 iChannel;
  46432. if (pChannelMapA == pChannelMapB) {
  46433. return MA_TRUE;
  46434. }
  46435. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46436. if (ma_channel_map_get_channel(pChannelMapA, channels, iChannel) != ma_channel_map_get_channel(pChannelMapB, channels, iChannel)) {
  46437. return MA_FALSE;
  46438. }
  46439. }
  46440. return MA_TRUE;
  46441. }
  46442. MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels)
  46443. {
  46444. ma_uint32 iChannel;
  46445. /* A null channel map is equivalent to the default channel map. */
  46446. if (pChannelMap == NULL) {
  46447. return MA_FALSE;
  46448. }
  46449. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46450. if (pChannelMap[iChannel] != MA_CHANNEL_NONE) {
  46451. return MA_FALSE;
  46452. }
  46453. }
  46454. return MA_TRUE;
  46455. }
  46456. MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition)
  46457. {
  46458. return ma_channel_map_find_channel_position(channels, pChannelMap, channelPosition, NULL);
  46459. }
  46460. MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex)
  46461. {
  46462. ma_uint32 iChannel;
  46463. if (pChannelIndex != NULL) {
  46464. *pChannelIndex = (ma_uint32)-1;
  46465. }
  46466. for (iChannel = 0; iChannel < channels; ++iChannel) {
  46467. if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == channelPosition) {
  46468. if (pChannelIndex != NULL) {
  46469. *pChannelIndex = iChannel;
  46470. }
  46471. return MA_TRUE;
  46472. }
  46473. }
  46474. /* Getting here means the channel position was not found. */
  46475. return MA_FALSE;
  46476. }
  46477. MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap)
  46478. {
  46479. size_t len;
  46480. ma_uint32 iChannel;
  46481. len = 0;
  46482. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  46483. const char* pChannelStr = ma_channel_position_to_string(ma_channel_map_get_channel(pChannelMap, channels, iChannel));
  46484. size_t channelStrLen = strlen(pChannelStr);
  46485. /* Append the string if necessary. */
  46486. if (pBufferOut != NULL && bufferCap > len + channelStrLen) {
  46487. MA_COPY_MEMORY(pBufferOut + len, pChannelStr, channelStrLen);
  46488. }
  46489. len += channelStrLen;
  46490. /* Append a space if it's not the last item. */
  46491. if (iChannel+1 < channels) {
  46492. if (pBufferOut != NULL && bufferCap > len + 1) {
  46493. pBufferOut[len] = ' ';
  46494. }
  46495. len += 1;
  46496. }
  46497. }
  46498. /* Null terminate. Don't increment the length here. */
  46499. if (pBufferOut != NULL && bufferCap > len + 1) {
  46500. pBufferOut[len] = '\0';
  46501. }
  46502. return len;
  46503. }
  46504. MA_API const char* ma_channel_position_to_string(ma_channel channel)
  46505. {
  46506. switch (channel)
  46507. {
  46508. case MA_CHANNEL_NONE : return "CHANNEL_NONE";
  46509. case MA_CHANNEL_MONO : return "CHANNEL_MONO";
  46510. case MA_CHANNEL_FRONT_LEFT : return "CHANNEL_FRONT_LEFT";
  46511. case MA_CHANNEL_FRONT_RIGHT : return "CHANNEL_FRONT_RIGHT";
  46512. case MA_CHANNEL_FRONT_CENTER : return "CHANNEL_FRONT_CENTER";
  46513. case MA_CHANNEL_LFE : return "CHANNEL_LFE";
  46514. case MA_CHANNEL_BACK_LEFT : return "CHANNEL_BACK_LEFT";
  46515. case MA_CHANNEL_BACK_RIGHT : return "CHANNEL_BACK_RIGHT";
  46516. case MA_CHANNEL_FRONT_LEFT_CENTER : return "CHANNEL_FRONT_LEFT_CENTER ";
  46517. case MA_CHANNEL_FRONT_RIGHT_CENTER: return "CHANNEL_FRONT_RIGHT_CENTER";
  46518. case MA_CHANNEL_BACK_CENTER : return "CHANNEL_BACK_CENTER";
  46519. case MA_CHANNEL_SIDE_LEFT : return "CHANNEL_SIDE_LEFT";
  46520. case MA_CHANNEL_SIDE_RIGHT : return "CHANNEL_SIDE_RIGHT";
  46521. case MA_CHANNEL_TOP_CENTER : return "CHANNEL_TOP_CENTER";
  46522. case MA_CHANNEL_TOP_FRONT_LEFT : return "CHANNEL_TOP_FRONT_LEFT";
  46523. case MA_CHANNEL_TOP_FRONT_CENTER : return "CHANNEL_TOP_FRONT_CENTER";
  46524. case MA_CHANNEL_TOP_FRONT_RIGHT : return "CHANNEL_TOP_FRONT_RIGHT";
  46525. case MA_CHANNEL_TOP_BACK_LEFT : return "CHANNEL_TOP_BACK_LEFT";
  46526. case MA_CHANNEL_TOP_BACK_CENTER : return "CHANNEL_TOP_BACK_CENTER";
  46527. case MA_CHANNEL_TOP_BACK_RIGHT : return "CHANNEL_TOP_BACK_RIGHT";
  46528. case MA_CHANNEL_AUX_0 : return "CHANNEL_AUX_0";
  46529. case MA_CHANNEL_AUX_1 : return "CHANNEL_AUX_1";
  46530. case MA_CHANNEL_AUX_2 : return "CHANNEL_AUX_2";
  46531. case MA_CHANNEL_AUX_3 : return "CHANNEL_AUX_3";
  46532. case MA_CHANNEL_AUX_4 : return "CHANNEL_AUX_4";
  46533. case MA_CHANNEL_AUX_5 : return "CHANNEL_AUX_5";
  46534. case MA_CHANNEL_AUX_6 : return "CHANNEL_AUX_6";
  46535. case MA_CHANNEL_AUX_7 : return "CHANNEL_AUX_7";
  46536. case MA_CHANNEL_AUX_8 : return "CHANNEL_AUX_8";
  46537. case MA_CHANNEL_AUX_9 : return "CHANNEL_AUX_9";
  46538. case MA_CHANNEL_AUX_10 : return "CHANNEL_AUX_10";
  46539. case MA_CHANNEL_AUX_11 : return "CHANNEL_AUX_11";
  46540. case MA_CHANNEL_AUX_12 : return "CHANNEL_AUX_12";
  46541. case MA_CHANNEL_AUX_13 : return "CHANNEL_AUX_13";
  46542. case MA_CHANNEL_AUX_14 : return "CHANNEL_AUX_14";
  46543. case MA_CHANNEL_AUX_15 : return "CHANNEL_AUX_15";
  46544. case MA_CHANNEL_AUX_16 : return "CHANNEL_AUX_16";
  46545. case MA_CHANNEL_AUX_17 : return "CHANNEL_AUX_17";
  46546. case MA_CHANNEL_AUX_18 : return "CHANNEL_AUX_18";
  46547. case MA_CHANNEL_AUX_19 : return "CHANNEL_AUX_19";
  46548. case MA_CHANNEL_AUX_20 : return "CHANNEL_AUX_20";
  46549. case MA_CHANNEL_AUX_21 : return "CHANNEL_AUX_21";
  46550. case MA_CHANNEL_AUX_22 : return "CHANNEL_AUX_22";
  46551. case MA_CHANNEL_AUX_23 : return "CHANNEL_AUX_23";
  46552. case MA_CHANNEL_AUX_24 : return "CHANNEL_AUX_24";
  46553. case MA_CHANNEL_AUX_25 : return "CHANNEL_AUX_25";
  46554. case MA_CHANNEL_AUX_26 : return "CHANNEL_AUX_26";
  46555. case MA_CHANNEL_AUX_27 : return "CHANNEL_AUX_27";
  46556. case MA_CHANNEL_AUX_28 : return "CHANNEL_AUX_28";
  46557. case MA_CHANNEL_AUX_29 : return "CHANNEL_AUX_29";
  46558. case MA_CHANNEL_AUX_30 : return "CHANNEL_AUX_30";
  46559. case MA_CHANNEL_AUX_31 : return "CHANNEL_AUX_31";
  46560. default: break;
  46561. }
  46562. return "UNKNOWN";
  46563. }
  46564. /**************************************************************************************************************************************************************
  46565. Conversion Helpers
  46566. **************************************************************************************************************************************************************/
  46567. 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)
  46568. {
  46569. ma_data_converter_config config;
  46570. config = ma_data_converter_config_init(formatIn, formatOut, channelsIn, channelsOut, sampleRateIn, sampleRateOut);
  46571. config.resampling.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  46572. return ma_convert_frames_ex(pOut, frameCountOut, pIn, frameCountIn, &config);
  46573. }
  46574. 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)
  46575. {
  46576. ma_result result;
  46577. ma_data_converter converter;
  46578. if (frameCountIn == 0 || pConfig == NULL) {
  46579. return 0;
  46580. }
  46581. result = ma_data_converter_init(pConfig, NULL, &converter);
  46582. if (result != MA_SUCCESS) {
  46583. return 0; /* Failed to initialize the data converter. */
  46584. }
  46585. if (pOut == NULL) {
  46586. result = ma_data_converter_get_expected_output_frame_count(&converter, frameCountIn, &frameCountOut);
  46587. if (result != MA_SUCCESS) {
  46588. if (result == MA_NOT_IMPLEMENTED) {
  46589. /* No way to calculate the number of frames, so we'll need to brute force it and loop. */
  46590. frameCountOut = 0;
  46591. while (frameCountIn > 0) {
  46592. ma_uint64 framesProcessedIn = frameCountIn;
  46593. ma_uint64 framesProcessedOut = 0xFFFFFFFF;
  46594. result = ma_data_converter_process_pcm_frames(&converter, pIn, &framesProcessedIn, NULL, &framesProcessedOut);
  46595. if (result != MA_SUCCESS) {
  46596. break;
  46597. }
  46598. frameCountIn -= framesProcessedIn;
  46599. }
  46600. }
  46601. }
  46602. } else {
  46603. result = ma_data_converter_process_pcm_frames(&converter, pIn, &frameCountIn, pOut, &frameCountOut);
  46604. if (result != MA_SUCCESS) {
  46605. frameCountOut = 0;
  46606. }
  46607. }
  46608. ma_data_converter_uninit(&converter, NULL);
  46609. return frameCountOut;
  46610. }
  46611. /**************************************************************************************************************************************************************
  46612. Ring Buffer
  46613. **************************************************************************************************************************************************************/
  46614. static MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset)
  46615. {
  46616. return encodedOffset & 0x7FFFFFFF;
  46617. }
  46618. static MA_INLINE ma_uint32 ma_rb__extract_offset_loop_flag(ma_uint32 encodedOffset)
  46619. {
  46620. return encodedOffset & 0x80000000;
  46621. }
  46622. static MA_INLINE void* ma_rb__get_read_ptr(ma_rb* pRB)
  46623. {
  46624. MA_ASSERT(pRB != NULL);
  46625. return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(ma_atomic_load_32(&pRB->encodedReadOffset)));
  46626. }
  46627. static MA_INLINE void* ma_rb__get_write_ptr(ma_rb* pRB)
  46628. {
  46629. MA_ASSERT(pRB != NULL);
  46630. return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(ma_atomic_load_32(&pRB->encodedWriteOffset)));
  46631. }
  46632. static MA_INLINE ma_uint32 ma_rb__construct_offset(ma_uint32 offsetInBytes, ma_uint32 offsetLoopFlag)
  46633. {
  46634. return offsetLoopFlag | offsetInBytes;
  46635. }
  46636. static MA_INLINE void ma_rb__deconstruct_offset(ma_uint32 encodedOffset, ma_uint32* pOffsetInBytes, ma_uint32* pOffsetLoopFlag)
  46637. {
  46638. MA_ASSERT(pOffsetInBytes != NULL);
  46639. MA_ASSERT(pOffsetLoopFlag != NULL);
  46640. *pOffsetInBytes = ma_rb__extract_offset_in_bytes(encodedOffset);
  46641. *pOffsetLoopFlag = ma_rb__extract_offset_loop_flag(encodedOffset);
  46642. }
  46643. 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)
  46644. {
  46645. ma_result result;
  46646. const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1);
  46647. if (pRB == NULL) {
  46648. return MA_INVALID_ARGS;
  46649. }
  46650. if (subbufferSizeInBytes == 0 || subbufferCount == 0) {
  46651. return MA_INVALID_ARGS;
  46652. }
  46653. if (subbufferSizeInBytes > maxSubBufferSize) {
  46654. return MA_INVALID_ARGS; /* Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. */
  46655. }
  46656. MA_ZERO_OBJECT(pRB);
  46657. result = ma_allocation_callbacks_init_copy(&pRB->allocationCallbacks, pAllocationCallbacks);
  46658. if (result != MA_SUCCESS) {
  46659. return result;
  46660. }
  46661. pRB->subbufferSizeInBytes = (ma_uint32)subbufferSizeInBytes;
  46662. pRB->subbufferCount = (ma_uint32)subbufferCount;
  46663. if (pOptionalPreallocatedBuffer != NULL) {
  46664. pRB->subbufferStrideInBytes = (ma_uint32)subbufferStrideInBytes;
  46665. pRB->pBuffer = pOptionalPreallocatedBuffer;
  46666. } else {
  46667. size_t bufferSizeInBytes;
  46668. /*
  46669. 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
  46670. we need to make sure the stride is a multiple of MA_SIMD_ALIGNMENT.
  46671. */
  46672. pRB->subbufferStrideInBytes = (pRB->subbufferSizeInBytes + (MA_SIMD_ALIGNMENT-1)) & ~MA_SIMD_ALIGNMENT;
  46673. bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes;
  46674. pRB->pBuffer = ma_aligned_malloc(bufferSizeInBytes, MA_SIMD_ALIGNMENT, &pRB->allocationCallbacks);
  46675. if (pRB->pBuffer == NULL) {
  46676. return MA_OUT_OF_MEMORY;
  46677. }
  46678. MA_ZERO_MEMORY(pRB->pBuffer, bufferSizeInBytes);
  46679. pRB->ownsBuffer = MA_TRUE;
  46680. }
  46681. return MA_SUCCESS;
  46682. }
  46683. MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB)
  46684. {
  46685. return ma_rb_init_ex(bufferSizeInBytes, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
  46686. }
  46687. MA_API void ma_rb_uninit(ma_rb* pRB)
  46688. {
  46689. if (pRB == NULL) {
  46690. return;
  46691. }
  46692. if (pRB->ownsBuffer) {
  46693. ma_aligned_free(pRB->pBuffer, &pRB->allocationCallbacks);
  46694. }
  46695. }
  46696. MA_API void ma_rb_reset(ma_rb* pRB)
  46697. {
  46698. if (pRB == NULL) {
  46699. return;
  46700. }
  46701. ma_atomic_exchange_32(&pRB->encodedReadOffset, 0);
  46702. ma_atomic_exchange_32(&pRB->encodedWriteOffset, 0);
  46703. }
  46704. MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut)
  46705. {
  46706. ma_uint32 writeOffset;
  46707. ma_uint32 writeOffsetInBytes;
  46708. ma_uint32 writeOffsetLoopFlag;
  46709. ma_uint32 readOffset;
  46710. ma_uint32 readOffsetInBytes;
  46711. ma_uint32 readOffsetLoopFlag;
  46712. size_t bytesAvailable;
  46713. size_t bytesRequested;
  46714. if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) {
  46715. return MA_INVALID_ARGS;
  46716. }
  46717. /* The returned buffer should never move ahead of the write pointer. */
  46718. writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset);
  46719. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46720. readOffset = ma_atomic_load_32(&pRB->encodedReadOffset);
  46721. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46722. /*
  46723. The number of bytes available depends on whether or not the read and write pointers are on the same loop iteration. If so, we
  46724. can only read up to the write pointer. If not, we can only read up to the end of the buffer.
  46725. */
  46726. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46727. bytesAvailable = writeOffsetInBytes - readOffsetInBytes;
  46728. } else {
  46729. bytesAvailable = pRB->subbufferSizeInBytes - readOffsetInBytes;
  46730. }
  46731. bytesRequested = *pSizeInBytes;
  46732. if (bytesRequested > bytesAvailable) {
  46733. bytesRequested = bytesAvailable;
  46734. }
  46735. *pSizeInBytes = bytesRequested;
  46736. (*ppBufferOut) = ma_rb__get_read_ptr(pRB);
  46737. return MA_SUCCESS;
  46738. }
  46739. MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes)
  46740. {
  46741. ma_uint32 readOffset;
  46742. ma_uint32 readOffsetInBytes;
  46743. ma_uint32 readOffsetLoopFlag;
  46744. ma_uint32 newReadOffsetInBytes;
  46745. ma_uint32 newReadOffsetLoopFlag;
  46746. if (pRB == NULL) {
  46747. return MA_INVALID_ARGS;
  46748. }
  46749. readOffset = ma_atomic_load_32(&pRB->encodedReadOffset);
  46750. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46751. /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */
  46752. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + sizeInBytes);
  46753. if (newReadOffsetInBytes > pRB->subbufferSizeInBytes) {
  46754. return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */
  46755. }
  46756. /* Move the read pointer back to the start if necessary. */
  46757. newReadOffsetLoopFlag = readOffsetLoopFlag;
  46758. if (newReadOffsetInBytes == pRB->subbufferSizeInBytes) {
  46759. newReadOffsetInBytes = 0;
  46760. newReadOffsetLoopFlag ^= 0x80000000;
  46761. }
  46762. ma_atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetLoopFlag, newReadOffsetInBytes));
  46763. if (ma_rb_pointer_distance(pRB) == 0) {
  46764. return MA_AT_END;
  46765. } else {
  46766. return MA_SUCCESS;
  46767. }
  46768. }
  46769. MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut)
  46770. {
  46771. ma_uint32 readOffset;
  46772. ma_uint32 readOffsetInBytes;
  46773. ma_uint32 readOffsetLoopFlag;
  46774. ma_uint32 writeOffset;
  46775. ma_uint32 writeOffsetInBytes;
  46776. ma_uint32 writeOffsetLoopFlag;
  46777. size_t bytesAvailable;
  46778. size_t bytesRequested;
  46779. if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) {
  46780. return MA_INVALID_ARGS;
  46781. }
  46782. /* The returned buffer should never overtake the read buffer. */
  46783. readOffset = ma_atomic_load_32(&pRB->encodedReadOffset);
  46784. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46785. writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset);
  46786. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46787. /*
  46788. In the case of writing, if the write pointer and the read pointer are on the same loop iteration we can only
  46789. write up to the end of the buffer. Otherwise we can only write up to the read pointer. The write pointer should
  46790. never overtake the read pointer.
  46791. */
  46792. if (writeOffsetLoopFlag == readOffsetLoopFlag) {
  46793. bytesAvailable = pRB->subbufferSizeInBytes - writeOffsetInBytes;
  46794. } else {
  46795. bytesAvailable = readOffsetInBytes - writeOffsetInBytes;
  46796. }
  46797. bytesRequested = *pSizeInBytes;
  46798. if (bytesRequested > bytesAvailable) {
  46799. bytesRequested = bytesAvailable;
  46800. }
  46801. *pSizeInBytes = bytesRequested;
  46802. *ppBufferOut = ma_rb__get_write_ptr(pRB);
  46803. /* Clear the buffer if desired. */
  46804. if (pRB->clearOnWriteAcquire) {
  46805. MA_ZERO_MEMORY(*ppBufferOut, *pSizeInBytes);
  46806. }
  46807. return MA_SUCCESS;
  46808. }
  46809. MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes)
  46810. {
  46811. ma_uint32 writeOffset;
  46812. ma_uint32 writeOffsetInBytes;
  46813. ma_uint32 writeOffsetLoopFlag;
  46814. ma_uint32 newWriteOffsetInBytes;
  46815. ma_uint32 newWriteOffsetLoopFlag;
  46816. if (pRB == NULL) {
  46817. return MA_INVALID_ARGS;
  46818. }
  46819. writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset);
  46820. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46821. /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */
  46822. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + sizeInBytes);
  46823. if (newWriteOffsetInBytes > pRB->subbufferSizeInBytes) {
  46824. return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */
  46825. }
  46826. /* Move the read pointer back to the start if necessary. */
  46827. newWriteOffsetLoopFlag = writeOffsetLoopFlag;
  46828. if (newWriteOffsetInBytes == pRB->subbufferSizeInBytes) {
  46829. newWriteOffsetInBytes = 0;
  46830. newWriteOffsetLoopFlag ^= 0x80000000;
  46831. }
  46832. ma_atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetLoopFlag, newWriteOffsetInBytes));
  46833. if (ma_rb_pointer_distance(pRB) == 0) {
  46834. return MA_AT_END;
  46835. } else {
  46836. return MA_SUCCESS;
  46837. }
  46838. }
  46839. MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes)
  46840. {
  46841. ma_uint32 readOffset;
  46842. ma_uint32 readOffsetInBytes;
  46843. ma_uint32 readOffsetLoopFlag;
  46844. ma_uint32 writeOffset;
  46845. ma_uint32 writeOffsetInBytes;
  46846. ma_uint32 writeOffsetLoopFlag;
  46847. ma_uint32 newReadOffsetInBytes;
  46848. ma_uint32 newReadOffsetLoopFlag;
  46849. if (pRB == NULL || offsetInBytes > pRB->subbufferSizeInBytes) {
  46850. return MA_INVALID_ARGS;
  46851. }
  46852. readOffset = ma_atomic_load_32(&pRB->encodedReadOffset);
  46853. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46854. writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset);
  46855. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46856. newReadOffsetLoopFlag = readOffsetLoopFlag;
  46857. /* We cannot go past the write buffer. */
  46858. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46859. if ((readOffsetInBytes + offsetInBytes) > writeOffsetInBytes) {
  46860. newReadOffsetInBytes = writeOffsetInBytes;
  46861. } else {
  46862. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes);
  46863. }
  46864. } else {
  46865. /* May end up looping. */
  46866. if ((readOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) {
  46867. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes;
  46868. newReadOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */
  46869. } else {
  46870. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes);
  46871. }
  46872. }
  46873. ma_atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetInBytes, newReadOffsetLoopFlag));
  46874. return MA_SUCCESS;
  46875. }
  46876. MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes)
  46877. {
  46878. ma_uint32 readOffset;
  46879. ma_uint32 readOffsetInBytes;
  46880. ma_uint32 readOffsetLoopFlag;
  46881. ma_uint32 writeOffset;
  46882. ma_uint32 writeOffsetInBytes;
  46883. ma_uint32 writeOffsetLoopFlag;
  46884. ma_uint32 newWriteOffsetInBytes;
  46885. ma_uint32 newWriteOffsetLoopFlag;
  46886. if (pRB == NULL) {
  46887. return MA_INVALID_ARGS;
  46888. }
  46889. readOffset = ma_atomic_load_32(&pRB->encodedReadOffset);
  46890. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46891. writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset);
  46892. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46893. newWriteOffsetLoopFlag = writeOffsetLoopFlag;
  46894. /* We cannot go past the write buffer. */
  46895. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46896. /* May end up looping. */
  46897. if ((writeOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) {
  46898. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes;
  46899. newWriteOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */
  46900. } else {
  46901. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes);
  46902. }
  46903. } else {
  46904. if ((writeOffsetInBytes + offsetInBytes) > readOffsetInBytes) {
  46905. newWriteOffsetInBytes = readOffsetInBytes;
  46906. } else {
  46907. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes);
  46908. }
  46909. }
  46910. ma_atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetInBytes, newWriteOffsetLoopFlag));
  46911. return MA_SUCCESS;
  46912. }
  46913. MA_API ma_int32 ma_rb_pointer_distance(ma_rb* pRB)
  46914. {
  46915. ma_uint32 readOffset;
  46916. ma_uint32 readOffsetInBytes;
  46917. ma_uint32 readOffsetLoopFlag;
  46918. ma_uint32 writeOffset;
  46919. ma_uint32 writeOffsetInBytes;
  46920. ma_uint32 writeOffsetLoopFlag;
  46921. if (pRB == NULL) {
  46922. return 0;
  46923. }
  46924. readOffset = ma_atomic_load_32(&pRB->encodedReadOffset);
  46925. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  46926. writeOffset = ma_atomic_load_32(&pRB->encodedWriteOffset);
  46927. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  46928. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  46929. return writeOffsetInBytes - readOffsetInBytes;
  46930. } else {
  46931. return writeOffsetInBytes + (pRB->subbufferSizeInBytes - readOffsetInBytes);
  46932. }
  46933. }
  46934. MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB)
  46935. {
  46936. ma_int32 dist;
  46937. if (pRB == NULL) {
  46938. return 0;
  46939. }
  46940. dist = ma_rb_pointer_distance(pRB);
  46941. if (dist < 0) {
  46942. return 0;
  46943. }
  46944. return dist;
  46945. }
  46946. MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB)
  46947. {
  46948. if (pRB == NULL) {
  46949. return 0;
  46950. }
  46951. return (ma_uint32)(ma_rb_get_subbuffer_size(pRB) - ma_rb_pointer_distance(pRB));
  46952. }
  46953. MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB)
  46954. {
  46955. if (pRB == NULL) {
  46956. return 0;
  46957. }
  46958. return pRB->subbufferSizeInBytes;
  46959. }
  46960. MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB)
  46961. {
  46962. if (pRB == NULL) {
  46963. return 0;
  46964. }
  46965. if (pRB->subbufferStrideInBytes == 0) {
  46966. return (size_t)pRB->subbufferSizeInBytes;
  46967. }
  46968. return (size_t)pRB->subbufferStrideInBytes;
  46969. }
  46970. MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex)
  46971. {
  46972. if (pRB == NULL) {
  46973. return 0;
  46974. }
  46975. return subbufferIndex * ma_rb_get_subbuffer_stride(pRB);
  46976. }
  46977. MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer)
  46978. {
  46979. if (pRB == NULL) {
  46980. return NULL;
  46981. }
  46982. return ma_offset_ptr(pBuffer, ma_rb_get_subbuffer_offset(pRB, subbufferIndex));
  46983. }
  46984. static ma_result ma_pcm_rb_data_source__on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  46985. {
  46986. /* 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. */
  46987. ma_pcm_rb* pRB = (ma_pcm_rb*)pDataSource;
  46988. ma_result result;
  46989. ma_uint64 totalFramesRead;
  46990. MA_ASSERT(pRB != NULL);
  46991. /* We need to run this in a loop since the ring buffer itself may loop. */
  46992. totalFramesRead = 0;
  46993. while (totalFramesRead < frameCount) {
  46994. void* pMappedBuffer;
  46995. ma_uint32 mappedFrameCount;
  46996. ma_uint64 framesToRead = frameCount - totalFramesRead;
  46997. if (framesToRead > 0xFFFFFFFF) {
  46998. framesToRead = 0xFFFFFFFF;
  46999. }
  47000. mappedFrameCount = (ma_uint32)framesToRead;
  47001. result = ma_pcm_rb_acquire_read(pRB, &mappedFrameCount, &pMappedBuffer);
  47002. if (result != MA_SUCCESS) {
  47003. break;
  47004. }
  47005. if (mappedFrameCount == 0) {
  47006. break; /* <-- End of ring buffer. */
  47007. }
  47008. ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, pRB->format, pRB->channels), pMappedBuffer, mappedFrameCount, pRB->format, pRB->channels);
  47009. result = ma_pcm_rb_commit_read(pRB, mappedFrameCount);
  47010. if (result != MA_SUCCESS) {
  47011. break;
  47012. }
  47013. totalFramesRead += mappedFrameCount;
  47014. }
  47015. *pFramesRead = totalFramesRead;
  47016. return MA_SUCCESS;
  47017. }
  47018. 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)
  47019. {
  47020. ma_pcm_rb* pRB = (ma_pcm_rb*)pDataSource;
  47021. MA_ASSERT(pRB != NULL);
  47022. if (pFormat != NULL) {
  47023. *pFormat = pRB->format;
  47024. }
  47025. if (pChannels != NULL) {
  47026. *pChannels = pRB->channels;
  47027. }
  47028. if (pSampleRate != NULL) {
  47029. *pSampleRate = pRB->sampleRate;
  47030. }
  47031. /* Just assume the default channel map. */
  47032. if (pChannelMap != NULL) {
  47033. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pRB->channels);
  47034. }
  47035. return MA_SUCCESS;
  47036. }
  47037. static ma_data_source_vtable ma_gRBDataSourceVTable =
  47038. {
  47039. ma_pcm_rb_data_source__on_read,
  47040. NULL, /* onSeek */
  47041. ma_pcm_rb_data_source__on_get_data_format,
  47042. NULL, /* onGetCursor */
  47043. NULL, /* onGetLength */
  47044. NULL, /* onSetLooping */
  47045. 0
  47046. };
  47047. static MA_INLINE ma_uint32 ma_pcm_rb_get_bpf(ma_pcm_rb* pRB)
  47048. {
  47049. MA_ASSERT(pRB != NULL);
  47050. return ma_get_bytes_per_frame(pRB->format, pRB->channels);
  47051. }
  47052. 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)
  47053. {
  47054. ma_uint32 bpf;
  47055. ma_result result;
  47056. if (pRB == NULL) {
  47057. return MA_INVALID_ARGS;
  47058. }
  47059. MA_ZERO_OBJECT(pRB);
  47060. bpf = ma_get_bytes_per_frame(format, channels);
  47061. if (bpf == 0) {
  47062. return MA_INVALID_ARGS;
  47063. }
  47064. result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, pAllocationCallbacks, &pRB->rb);
  47065. if (result != MA_SUCCESS) {
  47066. return result;
  47067. }
  47068. pRB->format = format;
  47069. pRB->channels = channels;
  47070. pRB->sampleRate = 0; /* The sample rate is not passed in as a parameter. */
  47071. /* The PCM ring buffer is a data source. We need to get that set up as well. */
  47072. {
  47073. ma_data_source_config dataSourceConfig = ma_data_source_config_init();
  47074. dataSourceConfig.vtable = &ma_gRBDataSourceVTable;
  47075. result = ma_data_source_init(&dataSourceConfig, &pRB->ds);
  47076. if (result != MA_SUCCESS) {
  47077. ma_rb_uninit(&pRB->rb);
  47078. return result;
  47079. }
  47080. }
  47081. return MA_SUCCESS;
  47082. }
  47083. 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)
  47084. {
  47085. return ma_pcm_rb_init_ex(format, channels, bufferSizeInFrames, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
  47086. }
  47087. MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB)
  47088. {
  47089. if (pRB == NULL) {
  47090. return;
  47091. }
  47092. ma_data_source_uninit(&pRB->ds);
  47093. ma_rb_uninit(&pRB->rb);
  47094. }
  47095. MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB)
  47096. {
  47097. if (pRB == NULL) {
  47098. return;
  47099. }
  47100. ma_rb_reset(&pRB->rb);
  47101. }
  47102. MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
  47103. {
  47104. size_t sizeInBytes;
  47105. ma_result result;
  47106. if (pRB == NULL || pSizeInFrames == NULL) {
  47107. return MA_INVALID_ARGS;
  47108. }
  47109. sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
  47110. result = ma_rb_acquire_read(&pRB->rb, &sizeInBytes, ppBufferOut);
  47111. if (result != MA_SUCCESS) {
  47112. return result;
  47113. }
  47114. *pSizeInFrames = (ma_uint32)(sizeInBytes / (size_t)ma_pcm_rb_get_bpf(pRB));
  47115. return MA_SUCCESS;
  47116. }
  47117. MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames)
  47118. {
  47119. if (pRB == NULL) {
  47120. return MA_INVALID_ARGS;
  47121. }
  47122. return ma_rb_commit_read(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB));
  47123. }
  47124. MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
  47125. {
  47126. size_t sizeInBytes;
  47127. ma_result result;
  47128. if (pRB == NULL) {
  47129. return MA_INVALID_ARGS;
  47130. }
  47131. sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
  47132. result = ma_rb_acquire_write(&pRB->rb, &sizeInBytes, ppBufferOut);
  47133. if (result != MA_SUCCESS) {
  47134. return result;
  47135. }
  47136. *pSizeInFrames = (ma_uint32)(sizeInBytes / ma_pcm_rb_get_bpf(pRB));
  47137. return MA_SUCCESS;
  47138. }
  47139. MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames)
  47140. {
  47141. if (pRB == NULL) {
  47142. return MA_INVALID_ARGS;
  47143. }
  47144. return ma_rb_commit_write(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB));
  47145. }
  47146. MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames)
  47147. {
  47148. if (pRB == NULL) {
  47149. return MA_INVALID_ARGS;
  47150. }
  47151. return ma_rb_seek_read(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB));
  47152. }
  47153. MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames)
  47154. {
  47155. if (pRB == NULL) {
  47156. return MA_INVALID_ARGS;
  47157. }
  47158. return ma_rb_seek_write(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB));
  47159. }
  47160. MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB)
  47161. {
  47162. if (pRB == NULL) {
  47163. return 0;
  47164. }
  47165. return ma_rb_pointer_distance(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  47166. }
  47167. MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB)
  47168. {
  47169. if (pRB == NULL) {
  47170. return 0;
  47171. }
  47172. return ma_rb_available_read(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  47173. }
  47174. MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB)
  47175. {
  47176. if (pRB == NULL) {
  47177. return 0;
  47178. }
  47179. return ma_rb_available_write(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  47180. }
  47181. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB)
  47182. {
  47183. if (pRB == NULL) {
  47184. return 0;
  47185. }
  47186. return (ma_uint32)(ma_rb_get_subbuffer_size(&pRB->rb) / ma_pcm_rb_get_bpf(pRB));
  47187. }
  47188. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB)
  47189. {
  47190. if (pRB == NULL) {
  47191. return 0;
  47192. }
  47193. return (ma_uint32)(ma_rb_get_subbuffer_stride(&pRB->rb) / ma_pcm_rb_get_bpf(pRB));
  47194. }
  47195. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex)
  47196. {
  47197. if (pRB == NULL) {
  47198. return 0;
  47199. }
  47200. return (ma_uint32)(ma_rb_get_subbuffer_offset(&pRB->rb, subbufferIndex) / ma_pcm_rb_get_bpf(pRB));
  47201. }
  47202. MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer)
  47203. {
  47204. if (pRB == NULL) {
  47205. return NULL;
  47206. }
  47207. return ma_rb_get_subbuffer_ptr(&pRB->rb, subbufferIndex, pBuffer);
  47208. }
  47209. MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB)
  47210. {
  47211. if (pRB == NULL) {
  47212. return ma_format_unknown;
  47213. }
  47214. return pRB->format;
  47215. }
  47216. MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB)
  47217. {
  47218. if (pRB == NULL) {
  47219. return 0;
  47220. }
  47221. return pRB->channels;
  47222. }
  47223. MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB)
  47224. {
  47225. if (pRB == NULL) {
  47226. return 0;
  47227. }
  47228. return pRB->sampleRate;
  47229. }
  47230. MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate)
  47231. {
  47232. if (pRB == NULL) {
  47233. return;
  47234. }
  47235. pRB->sampleRate = sampleRate;
  47236. }
  47237. 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)
  47238. {
  47239. ma_result result;
  47240. ma_uint32 sizeInFrames;
  47241. sizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(sampleRate, captureInternalSampleRate, captureInternalPeriodSizeInFrames * 5);
  47242. if (sizeInFrames == 0) {
  47243. return MA_INVALID_ARGS;
  47244. }
  47245. result = ma_pcm_rb_init(captureFormat, captureChannels, sizeInFrames, NULL, pAllocationCallbacks, &pRB->rb);
  47246. if (result != MA_SUCCESS) {
  47247. return result;
  47248. }
  47249. /* Seek forward a bit so we have a bit of a buffer in case of desyncs. */
  47250. ma_pcm_rb_seek_write((ma_pcm_rb*)pRB, captureInternalPeriodSizeInFrames * 2);
  47251. return MA_SUCCESS;
  47252. }
  47253. MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB)
  47254. {
  47255. ma_pcm_rb_uninit((ma_pcm_rb*)pRB);
  47256. return MA_SUCCESS;
  47257. }
  47258. /**************************************************************************************************************************************************************
  47259. Miscellaneous Helpers
  47260. **************************************************************************************************************************************************************/
  47261. MA_API const char* ma_result_description(ma_result result)
  47262. {
  47263. switch (result)
  47264. {
  47265. case MA_SUCCESS: return "No error";
  47266. case MA_ERROR: return "Unknown error";
  47267. case MA_INVALID_ARGS: return "Invalid argument";
  47268. case MA_INVALID_OPERATION: return "Invalid operation";
  47269. case MA_OUT_OF_MEMORY: return "Out of memory";
  47270. case MA_OUT_OF_RANGE: return "Out of range";
  47271. case MA_ACCESS_DENIED: return "Permission denied";
  47272. case MA_DOES_NOT_EXIST: return "Resource does not exist";
  47273. case MA_ALREADY_EXISTS: return "Resource already exists";
  47274. case MA_TOO_MANY_OPEN_FILES: return "Too many open files";
  47275. case MA_INVALID_FILE: return "Invalid file";
  47276. case MA_TOO_BIG: return "Too large";
  47277. case MA_PATH_TOO_LONG: return "Path too long";
  47278. case MA_NAME_TOO_LONG: return "Name too long";
  47279. case MA_NOT_DIRECTORY: return "Not a directory";
  47280. case MA_IS_DIRECTORY: return "Is a directory";
  47281. case MA_DIRECTORY_NOT_EMPTY: return "Directory not empty";
  47282. case MA_AT_END: return "At end";
  47283. case MA_NO_SPACE: return "No space available";
  47284. case MA_BUSY: return "Device or resource busy";
  47285. case MA_IO_ERROR: return "Input/output error";
  47286. case MA_INTERRUPT: return "Interrupted";
  47287. case MA_UNAVAILABLE: return "Resource unavailable";
  47288. case MA_ALREADY_IN_USE: return "Resource already in use";
  47289. case MA_BAD_ADDRESS: return "Bad address";
  47290. case MA_BAD_SEEK: return "Illegal seek";
  47291. case MA_BAD_PIPE: return "Broken pipe";
  47292. case MA_DEADLOCK: return "Deadlock";
  47293. case MA_TOO_MANY_LINKS: return "Too many links";
  47294. case MA_NOT_IMPLEMENTED: return "Not implemented";
  47295. case MA_NO_MESSAGE: return "No message of desired type";
  47296. case MA_BAD_MESSAGE: return "Invalid message";
  47297. case MA_NO_DATA_AVAILABLE: return "No data available";
  47298. case MA_INVALID_DATA: return "Invalid data";
  47299. case MA_TIMEOUT: return "Timeout";
  47300. case MA_NO_NETWORK: return "Network unavailable";
  47301. case MA_NOT_UNIQUE: return "Not unique";
  47302. case MA_NOT_SOCKET: return "Socket operation on non-socket";
  47303. case MA_NO_ADDRESS: return "Destination address required";
  47304. case MA_BAD_PROTOCOL: return "Protocol wrong type for socket";
  47305. case MA_PROTOCOL_UNAVAILABLE: return "Protocol not available";
  47306. case MA_PROTOCOL_NOT_SUPPORTED: return "Protocol not supported";
  47307. case MA_PROTOCOL_FAMILY_NOT_SUPPORTED: return "Protocol family not supported";
  47308. case MA_ADDRESS_FAMILY_NOT_SUPPORTED: return "Address family not supported";
  47309. case MA_SOCKET_NOT_SUPPORTED: return "Socket type not supported";
  47310. case MA_CONNECTION_RESET: return "Connection reset";
  47311. case MA_ALREADY_CONNECTED: return "Already connected";
  47312. case MA_NOT_CONNECTED: return "Not connected";
  47313. case MA_CONNECTION_REFUSED: return "Connection refused";
  47314. case MA_NO_HOST: return "No host";
  47315. case MA_IN_PROGRESS: return "Operation in progress";
  47316. case MA_CANCELLED: return "Operation cancelled";
  47317. case MA_MEMORY_ALREADY_MAPPED: return "Memory already mapped";
  47318. case MA_FORMAT_NOT_SUPPORTED: return "Format not supported";
  47319. case MA_DEVICE_TYPE_NOT_SUPPORTED: return "Device type not supported";
  47320. case MA_SHARE_MODE_NOT_SUPPORTED: return "Share mode not supported";
  47321. case MA_NO_BACKEND: return "No backend";
  47322. case MA_NO_DEVICE: return "No device";
  47323. case MA_API_NOT_FOUND: return "API not found";
  47324. case MA_INVALID_DEVICE_CONFIG: return "Invalid device config";
  47325. case MA_DEVICE_NOT_INITIALIZED: return "Device not initialized";
  47326. case MA_DEVICE_NOT_STARTED: return "Device not started";
  47327. case MA_FAILED_TO_INIT_BACKEND: return "Failed to initialize backend";
  47328. case MA_FAILED_TO_OPEN_BACKEND_DEVICE: return "Failed to open backend device";
  47329. case MA_FAILED_TO_START_BACKEND_DEVICE: return "Failed to start backend device";
  47330. case MA_FAILED_TO_STOP_BACKEND_DEVICE: return "Failed to stop backend device";
  47331. default: return "Unknown error";
  47332. }
  47333. }
  47334. MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  47335. {
  47336. if (pAllocationCallbacks != NULL) {
  47337. if (pAllocationCallbacks->onMalloc != NULL) {
  47338. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  47339. } else {
  47340. return NULL; /* Do not fall back to the default implementation. */
  47341. }
  47342. } else {
  47343. return ma__malloc_default(sz, NULL);
  47344. }
  47345. }
  47346. MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  47347. {
  47348. void* p = ma_malloc(sz, pAllocationCallbacks);
  47349. if (p != NULL) {
  47350. MA_ZERO_MEMORY(p, sz);
  47351. }
  47352. return p;
  47353. }
  47354. MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  47355. {
  47356. if (pAllocationCallbacks != NULL) {
  47357. if (pAllocationCallbacks->onRealloc != NULL) {
  47358. return pAllocationCallbacks->onRealloc(p, sz, pAllocationCallbacks->pUserData);
  47359. } else {
  47360. return NULL; /* Do not fall back to the default implementation. */
  47361. }
  47362. } else {
  47363. return ma__realloc_default(p, sz, NULL);
  47364. }
  47365. }
  47366. MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  47367. {
  47368. if (p == NULL) {
  47369. return;
  47370. }
  47371. if (pAllocationCallbacks != NULL) {
  47372. if (pAllocationCallbacks->onFree != NULL) {
  47373. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  47374. } else {
  47375. return; /* Do no fall back to the default implementation. */
  47376. }
  47377. } else {
  47378. ma__free_default(p, NULL);
  47379. }
  47380. }
  47381. MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks)
  47382. {
  47383. size_t extraBytes;
  47384. void* pUnaligned;
  47385. void* pAligned;
  47386. if (alignment == 0) {
  47387. return 0;
  47388. }
  47389. extraBytes = alignment-1 + sizeof(void*);
  47390. pUnaligned = ma_malloc(sz + extraBytes, pAllocationCallbacks);
  47391. if (pUnaligned == NULL) {
  47392. return NULL;
  47393. }
  47394. pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1)));
  47395. ((void**)pAligned)[-1] = pUnaligned;
  47396. return pAligned;
  47397. }
  47398. MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  47399. {
  47400. ma_free(((void**)p)[-1], pAllocationCallbacks);
  47401. }
  47402. MA_API const char* ma_get_format_name(ma_format format)
  47403. {
  47404. switch (format)
  47405. {
  47406. case ma_format_unknown: return "Unknown";
  47407. case ma_format_u8: return "8-bit Unsigned Integer";
  47408. case ma_format_s16: return "16-bit Signed Integer";
  47409. case ma_format_s24: return "24-bit Signed Integer (Tightly Packed)";
  47410. case ma_format_s32: return "32-bit Signed Integer";
  47411. case ma_format_f32: return "32-bit IEEE Floating Point";
  47412. default: return "Invalid";
  47413. }
  47414. }
  47415. MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels)
  47416. {
  47417. ma_uint32 i;
  47418. for (i = 0; i < channels; ++i) {
  47419. pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor);
  47420. }
  47421. }
  47422. MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format)
  47423. {
  47424. ma_uint32 sizes[] = {
  47425. 0, /* unknown */
  47426. 1, /* u8 */
  47427. 2, /* s16 */
  47428. 3, /* s24 */
  47429. 4, /* s32 */
  47430. 4, /* f32 */
  47431. };
  47432. return sizes[format];
  47433. }
  47434. #define MA_DATA_SOURCE_DEFAULT_RANGE_BEG 0
  47435. #define MA_DATA_SOURCE_DEFAULT_RANGE_END ~((ma_uint64)0)
  47436. #define MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG 0
  47437. #define MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END ~((ma_uint64)0)
  47438. MA_API ma_data_source_config ma_data_source_config_init(void)
  47439. {
  47440. ma_data_source_config config;
  47441. MA_ZERO_OBJECT(&config);
  47442. return config;
  47443. }
  47444. MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource)
  47445. {
  47446. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47447. if (pDataSource == NULL) {
  47448. return MA_INVALID_ARGS;
  47449. }
  47450. MA_ZERO_OBJECT(pDataSourceBase);
  47451. if (pConfig == NULL) {
  47452. return MA_INVALID_ARGS;
  47453. }
  47454. pDataSourceBase->vtable = pConfig->vtable;
  47455. pDataSourceBase->rangeBegInFrames = MA_DATA_SOURCE_DEFAULT_RANGE_BEG;
  47456. pDataSourceBase->rangeEndInFrames = MA_DATA_SOURCE_DEFAULT_RANGE_END;
  47457. pDataSourceBase->loopBegInFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG;
  47458. pDataSourceBase->loopEndInFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END;
  47459. pDataSourceBase->pCurrent = pDataSource; /* Always read from ourself by default. */
  47460. pDataSourceBase->pNext = NULL;
  47461. pDataSourceBase->onGetNext = NULL;
  47462. return MA_SUCCESS;
  47463. }
  47464. MA_API void ma_data_source_uninit(ma_data_source* pDataSource)
  47465. {
  47466. if (pDataSource == NULL) {
  47467. return;
  47468. }
  47469. /*
  47470. This is placeholder in case we need this later. Data sources need to call this in their
  47471. uninitialization routine to ensure things work later on if something is added here.
  47472. */
  47473. }
  47474. static ma_result ma_data_source_resolve_current(ma_data_source* pDataSource, ma_data_source** ppCurrentDataSource)
  47475. {
  47476. ma_data_source_base* pCurrentDataSource = (ma_data_source_base*)pDataSource;
  47477. MA_ASSERT(pDataSource != NULL);
  47478. MA_ASSERT(ppCurrentDataSource != NULL);
  47479. if (pCurrentDataSource->pCurrent == NULL) {
  47480. /*
  47481. The current data source is NULL. If we're using this in the context of a chain we need to return NULL
  47482. here so that we don't end up looping. Otherwise we just return the data source itself.
  47483. */
  47484. if (pCurrentDataSource->pNext != NULL || pCurrentDataSource->onGetNext != NULL) {
  47485. pCurrentDataSource = NULL;
  47486. } else {
  47487. 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. */
  47488. }
  47489. } else {
  47490. pCurrentDataSource = (ma_data_source_base*)pCurrentDataSource->pCurrent;
  47491. }
  47492. *ppCurrentDataSource = pCurrentDataSource;
  47493. return MA_SUCCESS;
  47494. }
  47495. static ma_result ma_data_source_read_pcm_frames_within_range(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  47496. {
  47497. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47498. ma_result result;
  47499. ma_uint64 framesRead = 0;
  47500. ma_bool32 loop = ma_data_source_is_looping(pDataSource);
  47501. if (pDataSourceBase == NULL) {
  47502. return MA_AT_END;
  47503. }
  47504. if (frameCount == 0) {
  47505. return MA_INVALID_ARGS;
  47506. }
  47507. 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))) {
  47508. /* 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. */
  47509. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  47510. } else {
  47511. /* Need to clamp to within the range. */
  47512. ma_uint64 relativeCursor;
  47513. ma_uint64 absoluteCursor;
  47514. result = ma_data_source_get_cursor_in_pcm_frames(pDataSourceBase, &relativeCursor);
  47515. if (result != MA_SUCCESS) {
  47516. /* 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. */
  47517. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  47518. } else {
  47519. ma_uint64 rangeBeg;
  47520. ma_uint64 rangeEnd;
  47521. /* We have the cursor. We need to make sure we don't read beyond our range. */
  47522. rangeBeg = pDataSourceBase->rangeBegInFrames;
  47523. rangeEnd = pDataSourceBase->rangeEndInFrames;
  47524. absoluteCursor = rangeBeg + relativeCursor;
  47525. /* If looping, make sure we're within range. */
  47526. if (loop) {
  47527. if (pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) {
  47528. rangeEnd = ma_min(rangeEnd, pDataSourceBase->rangeBegInFrames + pDataSourceBase->loopEndInFrames);
  47529. }
  47530. }
  47531. if (frameCount > (rangeEnd - absoluteCursor) && rangeEnd != ~((ma_uint64)0)) {
  47532. frameCount = (rangeEnd - absoluteCursor);
  47533. }
  47534. /*
  47535. If the cursor is sitting on the end of the range the frame count will be set to 0 which can
  47536. result in MA_INVALID_ARGS. In this case, we don't want to try reading, but instead return
  47537. MA_AT_END so the higher level function can know about it.
  47538. */
  47539. if (frameCount > 0) {
  47540. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  47541. } else {
  47542. result = MA_AT_END; /* The cursor is sitting on the end of the range which means we're at the end. */
  47543. }
  47544. }
  47545. }
  47546. if (pFramesRead != NULL) {
  47547. *pFramesRead = framesRead;
  47548. }
  47549. /* We need to make sure MA_AT_END is returned if we hit the end of the range. */
  47550. if (result == MA_SUCCESS && framesRead == 0) {
  47551. result = MA_AT_END;
  47552. }
  47553. return result;
  47554. }
  47555. MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  47556. {
  47557. ma_result result = MA_SUCCESS;
  47558. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47559. ma_data_source_base* pCurrentDataSource;
  47560. void* pRunningFramesOut = pFramesOut;
  47561. ma_uint64 totalFramesProcessed = 0;
  47562. ma_format format;
  47563. ma_uint32 channels;
  47564. 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. */
  47565. ma_bool32 loop;
  47566. if (pFramesRead != NULL) {
  47567. *pFramesRead = 0;
  47568. }
  47569. if (frameCount == 0) {
  47570. return MA_INVALID_ARGS;
  47571. }
  47572. if (pDataSourceBase == NULL) {
  47573. return MA_INVALID_ARGS;
  47574. }
  47575. loop = ma_data_source_is_looping(pDataSource);
  47576. /*
  47577. We need to know the data format so we can advance the output buffer as we read frames. If this
  47578. fails, chaining will not work and we'll just read as much as we can from the current source.
  47579. */
  47580. if (ma_data_source_get_data_format(pDataSource, &format, &channels, NULL, NULL, 0) != MA_SUCCESS) {
  47581. result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource);
  47582. if (result != MA_SUCCESS) {
  47583. return result;
  47584. }
  47585. return ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pFramesOut, frameCount, pFramesRead);
  47586. }
  47587. /*
  47588. Looping is a bit of a special case. When the `loop` argument is true, chaining will not work and
  47589. only the current data source will be read from.
  47590. */
  47591. /* Keep reading until we've read as many frames as possible. */
  47592. while (totalFramesProcessed < frameCount) {
  47593. ma_uint64 framesProcessed;
  47594. ma_uint64 framesRemaining = frameCount - totalFramesProcessed;
  47595. /* We need to resolve the data source that we'll actually be reading from. */
  47596. result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource);
  47597. if (result != MA_SUCCESS) {
  47598. break;
  47599. }
  47600. if (pCurrentDataSource == NULL) {
  47601. break;
  47602. }
  47603. result = ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pRunningFramesOut, framesRemaining, &framesProcessed);
  47604. totalFramesProcessed += framesProcessed;
  47605. /*
  47606. 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
  47607. not necessarily considered an error.
  47608. */
  47609. if (result != MA_SUCCESS && result != MA_AT_END) {
  47610. break;
  47611. }
  47612. /*
  47613. We can determine if we've reached the end by checking if ma_data_source_read_pcm_frames_within_range() returned
  47614. MA_AT_END. To loop back to the start, all we need to do is seek back to the first frame.
  47615. */
  47616. if (result == MA_AT_END) {
  47617. /*
  47618. The result needs to be reset back to MA_SUCCESS (from MA_AT_END) so that we don't
  47619. accidentally return MA_AT_END when data has been read in prior loop iterations. at the
  47620. end of this function, the result will be checked for MA_SUCCESS, and if the total
  47621. number of frames processed is 0, will be explicitly set to MA_AT_END.
  47622. */
  47623. result = MA_SUCCESS;
  47624. /*
  47625. We reached the end. If we're looping, we just loop back to the start of the current
  47626. data source. If we're not looping we need to check if we have another in the chain, and
  47627. if so, switch to it.
  47628. */
  47629. if (loop) {
  47630. if (framesProcessed == 0) {
  47631. emptyLoopCounter += 1;
  47632. if (emptyLoopCounter > 1) {
  47633. break; /* Infinite loop detected. Get out. */
  47634. }
  47635. } else {
  47636. emptyLoopCounter = 0;
  47637. }
  47638. result = ma_data_source_seek_to_pcm_frame(pCurrentDataSource, pCurrentDataSource->loopBegInFrames);
  47639. if (result != MA_SUCCESS) {
  47640. break; /* Failed to loop. Abort. */
  47641. }
  47642. /* Don't return MA_AT_END for looping sounds. */
  47643. result = MA_SUCCESS;
  47644. } else {
  47645. if (pCurrentDataSource->pNext != NULL) {
  47646. pDataSourceBase->pCurrent = pCurrentDataSource->pNext;
  47647. } else if (pCurrentDataSource->onGetNext != NULL) {
  47648. pDataSourceBase->pCurrent = pCurrentDataSource->onGetNext(pCurrentDataSource);
  47649. if (pDataSourceBase->pCurrent == NULL) {
  47650. break; /* Our callback did not return a next data source. We're done. */
  47651. }
  47652. } else {
  47653. /* Reached the end of the chain. We're done. */
  47654. break;
  47655. }
  47656. /* The next data source needs to be rewound to ensure data is read in looping scenarios. */
  47657. result = ma_data_source_seek_to_pcm_frame(pDataSourceBase->pCurrent, 0);
  47658. if (result != MA_SUCCESS) {
  47659. break;
  47660. }
  47661. }
  47662. }
  47663. if (pRunningFramesOut != NULL) {
  47664. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesProcessed * ma_get_bytes_per_frame(format, channels));
  47665. }
  47666. }
  47667. if (pFramesRead != NULL) {
  47668. *pFramesRead = totalFramesProcessed;
  47669. }
  47670. MA_ASSERT(!(result == MA_AT_END && totalFramesProcessed > 0)); /* We should never be returning MA_AT_END if we read some data. */
  47671. if (result == MA_SUCCESS && totalFramesProcessed == 0) {
  47672. result = MA_AT_END;
  47673. }
  47674. return result;
  47675. }
  47676. MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked)
  47677. {
  47678. return ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, pFramesSeeked);
  47679. }
  47680. MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  47681. {
  47682. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47683. if (pDataSourceBase == NULL) {
  47684. return MA_SUCCESS;
  47685. }
  47686. if (pDataSourceBase->vtable->onSeek == NULL) {
  47687. return MA_NOT_IMPLEMENTED;
  47688. }
  47689. if (frameIndex > pDataSourceBase->rangeEndInFrames) {
  47690. return MA_INVALID_OPERATION; /* Trying to seek to far forward. */
  47691. }
  47692. return pDataSourceBase->vtable->onSeek(pDataSource, pDataSourceBase->rangeBegInFrames + frameIndex);
  47693. }
  47694. 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)
  47695. {
  47696. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47697. ma_result result;
  47698. ma_format format;
  47699. ma_uint32 channels;
  47700. ma_uint32 sampleRate;
  47701. /* Initialize to defaults for safety just in case the data source does not implement this callback. */
  47702. if (pFormat != NULL) {
  47703. *pFormat = ma_format_unknown;
  47704. }
  47705. if (pChannels != NULL) {
  47706. *pChannels = 0;
  47707. }
  47708. if (pSampleRate != NULL) {
  47709. *pSampleRate = 0;
  47710. }
  47711. if (pChannelMap != NULL) {
  47712. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  47713. }
  47714. if (pDataSourceBase == NULL) {
  47715. return MA_INVALID_ARGS;
  47716. }
  47717. if (pDataSourceBase->vtable->onGetDataFormat == NULL) {
  47718. return MA_NOT_IMPLEMENTED;
  47719. }
  47720. result = pDataSourceBase->vtable->onGetDataFormat(pDataSource, &format, &channels, &sampleRate, pChannelMap, channelMapCap);
  47721. if (result != MA_SUCCESS) {
  47722. return result;
  47723. }
  47724. if (pFormat != NULL) {
  47725. *pFormat = format;
  47726. }
  47727. if (pChannels != NULL) {
  47728. *pChannels = channels;
  47729. }
  47730. if (pSampleRate != NULL) {
  47731. *pSampleRate = sampleRate;
  47732. }
  47733. /* Channel map was passed in directly to the callback. This is safe due to the channelMapCap parameter. */
  47734. return MA_SUCCESS;
  47735. }
  47736. MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  47737. {
  47738. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47739. ma_result result;
  47740. ma_uint64 cursor;
  47741. if (pCursor == NULL) {
  47742. return MA_INVALID_ARGS;
  47743. }
  47744. *pCursor = 0;
  47745. if (pDataSourceBase == NULL) {
  47746. return MA_SUCCESS;
  47747. }
  47748. if (pDataSourceBase->vtable->onGetCursor == NULL) {
  47749. return MA_NOT_IMPLEMENTED;
  47750. }
  47751. result = pDataSourceBase->vtable->onGetCursor(pDataSourceBase, &cursor);
  47752. if (result != MA_SUCCESS) {
  47753. return result;
  47754. }
  47755. /* The cursor needs to be made relative to the start of the range. */
  47756. if (cursor < pDataSourceBase->rangeBegInFrames) { /* Safety check so we don't return some huge number. */
  47757. *pCursor = 0;
  47758. } else {
  47759. *pCursor = cursor - pDataSourceBase->rangeBegInFrames;
  47760. }
  47761. return MA_SUCCESS;
  47762. }
  47763. MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  47764. {
  47765. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47766. if (pLength == NULL) {
  47767. return MA_INVALID_ARGS;
  47768. }
  47769. *pLength = 0;
  47770. if (pDataSourceBase == NULL) {
  47771. return MA_INVALID_ARGS;
  47772. }
  47773. /*
  47774. If we have a range defined we'll use that to determine the length. This is one of rare times
  47775. where we'll actually trust the caller. If they've set the range, I think it's mostly safe to
  47776. assume they've set it based on some higher level knowledge of the structure of the sound bank.
  47777. */
  47778. if (pDataSourceBase->rangeEndInFrames != ~((ma_uint64)0)) {
  47779. *pLength = pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames;
  47780. return MA_SUCCESS;
  47781. }
  47782. /*
  47783. Getting here means a range is not defined so we'll need to get the data source itself to tell
  47784. us the length.
  47785. */
  47786. if (pDataSourceBase->vtable->onGetLength == NULL) {
  47787. return MA_NOT_IMPLEMENTED;
  47788. }
  47789. return pDataSourceBase->vtable->onGetLength(pDataSource, pLength);
  47790. }
  47791. MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor)
  47792. {
  47793. ma_result result;
  47794. ma_uint64 cursorInPCMFrames;
  47795. ma_uint32 sampleRate;
  47796. if (pCursor == NULL) {
  47797. return MA_INVALID_ARGS;
  47798. }
  47799. *pCursor = 0;
  47800. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursorInPCMFrames);
  47801. if (result != MA_SUCCESS) {
  47802. return result;
  47803. }
  47804. result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0);
  47805. if (result != MA_SUCCESS) {
  47806. return result;
  47807. }
  47808. /* 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. */
  47809. *pCursor = (ma_int64)cursorInPCMFrames / (float)sampleRate;
  47810. return MA_SUCCESS;
  47811. }
  47812. MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength)
  47813. {
  47814. ma_result result;
  47815. ma_uint64 lengthInPCMFrames;
  47816. ma_uint32 sampleRate;
  47817. if (pLength == NULL) {
  47818. return MA_INVALID_ARGS;
  47819. }
  47820. *pLength = 0;
  47821. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &lengthInPCMFrames);
  47822. if (result != MA_SUCCESS) {
  47823. return result;
  47824. }
  47825. result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0);
  47826. if (result != MA_SUCCESS) {
  47827. return result;
  47828. }
  47829. /* 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. */
  47830. *pLength = (ma_int64)lengthInPCMFrames / (float)sampleRate;
  47831. return MA_SUCCESS;
  47832. }
  47833. MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  47834. {
  47835. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47836. if (pDataSource == NULL) {
  47837. return MA_INVALID_ARGS;
  47838. }
  47839. ma_atomic_exchange_32(&pDataSourceBase->isLooping, isLooping);
  47840. /* If there's no callback for this just treat it as a successful no-op. */
  47841. if (pDataSourceBase->vtable->onSetLooping == NULL) {
  47842. return MA_SUCCESS;
  47843. }
  47844. return pDataSourceBase->vtable->onSetLooping(pDataSource, isLooping);
  47845. }
  47846. MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource)
  47847. {
  47848. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47849. if (pDataSource == NULL) {
  47850. return MA_FALSE;
  47851. }
  47852. return ma_atomic_load_32(&pDataSourceBase->isLooping);
  47853. }
  47854. MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames)
  47855. {
  47856. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47857. ma_result result;
  47858. ma_uint64 relativeCursor;
  47859. ma_uint64 absoluteCursor;
  47860. ma_bool32 doSeekAdjustment = MA_FALSE;
  47861. if (pDataSource == NULL) {
  47862. return MA_INVALID_ARGS;
  47863. }
  47864. if (rangeEndInFrames < rangeBegInFrames) {
  47865. return MA_INVALID_ARGS; /* The end of the range must come after the beginning. */
  47866. }
  47867. /*
  47868. We may need to adjust the position of the cursor to ensure it's clamped to the range. Grab it now
  47869. so we can calculate it's absolute position before we change the range.
  47870. */
  47871. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &relativeCursor);
  47872. if (result == MA_SUCCESS) {
  47873. doSeekAdjustment = MA_TRUE;
  47874. absoluteCursor = relativeCursor + pDataSourceBase->rangeBegInFrames;
  47875. } else {
  47876. /*
  47877. We couldn't get the position of the cursor. It probably means the data source has no notion
  47878. of a cursor. We'll just leave it at position 0. Don't treat this as an error.
  47879. */
  47880. doSeekAdjustment = MA_FALSE;
  47881. relativeCursor = 0;
  47882. absoluteCursor = 0;
  47883. }
  47884. pDataSourceBase->rangeBegInFrames = rangeBegInFrames;
  47885. pDataSourceBase->rangeEndInFrames = rangeEndInFrames;
  47886. /*
  47887. The commented out logic below was intended to maintain loop points in response to a change in the
  47888. range. However, this is not useful because it results in the sound breaking when you move the range
  47889. outside of the old loop points. I'm simplifying this by simply resetting the loop points. The
  47890. caller is expected to update their loop points if they change the range.
  47891. In practice this should be mostly a non-issue because the majority of the time the range will be
  47892. set once right after initialization.
  47893. */
  47894. pDataSourceBase->loopBegInFrames = 0;
  47895. pDataSourceBase->loopEndInFrames = ~((ma_uint64)0);
  47896. /*
  47897. Seek to within range. Note that our seek positions here are relative to the new range. We don't want
  47898. do do this if we failed to retrieve the cursor earlier on because it probably means the data source
  47899. has no notion of a cursor. In practice the seek would probably fail (which we silently ignore), but
  47900. I'm just not even going to attempt it.
  47901. */
  47902. if (doSeekAdjustment) {
  47903. if (absoluteCursor < rangeBegInFrames) {
  47904. ma_data_source_seek_to_pcm_frame(pDataSource, 0);
  47905. } else if (absoluteCursor > rangeEndInFrames) {
  47906. ma_data_source_seek_to_pcm_frame(pDataSource, rangeEndInFrames - rangeBegInFrames);
  47907. }
  47908. }
  47909. return MA_SUCCESS;
  47910. }
  47911. MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames)
  47912. {
  47913. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47914. if (pDataSource == NULL) {
  47915. return;
  47916. }
  47917. if (pRangeBegInFrames != NULL) {
  47918. *pRangeBegInFrames = pDataSourceBase->rangeBegInFrames;
  47919. }
  47920. if (pRangeEndInFrames != NULL) {
  47921. *pRangeEndInFrames = pDataSourceBase->rangeEndInFrames;
  47922. }
  47923. }
  47924. MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames)
  47925. {
  47926. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47927. if (pDataSource == NULL) {
  47928. return MA_INVALID_ARGS;
  47929. }
  47930. if (loopEndInFrames < loopBegInFrames) {
  47931. return MA_INVALID_ARGS; /* The end of the loop point must come after the beginning. */
  47932. }
  47933. if (loopEndInFrames > pDataSourceBase->rangeEndInFrames && loopEndInFrames != ~((ma_uint64)0)) {
  47934. return MA_INVALID_ARGS; /* The end of the loop point must not go beyond the range. */
  47935. }
  47936. pDataSourceBase->loopBegInFrames = loopBegInFrames;
  47937. pDataSourceBase->loopEndInFrames = loopEndInFrames;
  47938. /* The end cannot exceed the range. */
  47939. if (pDataSourceBase->loopEndInFrames > (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames) && pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) {
  47940. pDataSourceBase->loopEndInFrames = (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames);
  47941. }
  47942. return MA_SUCCESS;
  47943. }
  47944. MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames)
  47945. {
  47946. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  47947. if (pDataSource == NULL) {
  47948. return;
  47949. }
  47950. if (pLoopBegInFrames != NULL) {
  47951. *pLoopBegInFrames = pDataSourceBase->loopBegInFrames;
  47952. }
  47953. if (pLoopEndInFrames != NULL) {
  47954. *pLoopEndInFrames = pDataSourceBase->loopEndInFrames;
  47955. }
  47956. }
  47957. MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource)
  47958. {
  47959. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47960. if (pDataSource == NULL) {
  47961. return MA_INVALID_ARGS;
  47962. }
  47963. pDataSourceBase->pCurrent = pCurrentDataSource;
  47964. return MA_SUCCESS;
  47965. }
  47966. MA_API ma_data_source* ma_data_source_get_current(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->pCurrent;
  47973. }
  47974. MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource)
  47975. {
  47976. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47977. if (pDataSource == NULL) {
  47978. return MA_INVALID_ARGS;
  47979. }
  47980. pDataSourceBase->pNext = pNextDataSource;
  47981. return MA_SUCCESS;
  47982. }
  47983. MA_API ma_data_source* ma_data_source_get_next(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->pNext;
  47990. }
  47991. MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext)
  47992. {
  47993. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  47994. if (pDataSource == NULL) {
  47995. return MA_INVALID_ARGS;
  47996. }
  47997. pDataSourceBase->onGetNext = onGetNext;
  47998. return MA_SUCCESS;
  47999. }
  48000. MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource)
  48001. {
  48002. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  48003. if (pDataSource == NULL) {
  48004. return NULL;
  48005. }
  48006. return pDataSourceBase->onGetNext;
  48007. }
  48008. static ma_result ma_audio_buffer_ref__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  48009. {
  48010. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48011. ma_uint64 framesRead = ma_audio_buffer_ref_read_pcm_frames(pAudioBufferRef, pFramesOut, frameCount, MA_FALSE);
  48012. if (pFramesRead != NULL) {
  48013. *pFramesRead = framesRead;
  48014. }
  48015. if (framesRead < frameCount || framesRead == 0) {
  48016. return MA_AT_END;
  48017. }
  48018. return MA_SUCCESS;
  48019. }
  48020. static ma_result ma_audio_buffer_ref__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  48021. {
  48022. return ma_audio_buffer_ref_seek_to_pcm_frame((ma_audio_buffer_ref*)pDataSource, frameIndex);
  48023. }
  48024. 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)
  48025. {
  48026. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48027. *pFormat = pAudioBufferRef->format;
  48028. *pChannels = pAudioBufferRef->channels;
  48029. *pSampleRate = pAudioBufferRef->sampleRate;
  48030. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pAudioBufferRef->channels);
  48031. return MA_SUCCESS;
  48032. }
  48033. static ma_result ma_audio_buffer_ref__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  48034. {
  48035. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48036. *pCursor = pAudioBufferRef->cursor;
  48037. return MA_SUCCESS;
  48038. }
  48039. static ma_result ma_audio_buffer_ref__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  48040. {
  48041. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  48042. *pLength = pAudioBufferRef->sizeInFrames;
  48043. return MA_SUCCESS;
  48044. }
  48045. static ma_data_source_vtable g_ma_audio_buffer_ref_data_source_vtable =
  48046. {
  48047. ma_audio_buffer_ref__data_source_on_read,
  48048. ma_audio_buffer_ref__data_source_on_seek,
  48049. ma_audio_buffer_ref__data_source_on_get_data_format,
  48050. ma_audio_buffer_ref__data_source_on_get_cursor,
  48051. ma_audio_buffer_ref__data_source_on_get_length,
  48052. NULL, /* onSetLooping */
  48053. 0
  48054. };
  48055. 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)
  48056. {
  48057. ma_result result;
  48058. ma_data_source_config dataSourceConfig;
  48059. if (pAudioBufferRef == NULL) {
  48060. return MA_INVALID_ARGS;
  48061. }
  48062. MA_ZERO_OBJECT(pAudioBufferRef);
  48063. dataSourceConfig = ma_data_source_config_init();
  48064. dataSourceConfig.vtable = &g_ma_audio_buffer_ref_data_source_vtable;
  48065. result = ma_data_source_init(&dataSourceConfig, &pAudioBufferRef->ds);
  48066. if (result != MA_SUCCESS) {
  48067. return result;
  48068. }
  48069. pAudioBufferRef->format = format;
  48070. pAudioBufferRef->channels = channels;
  48071. pAudioBufferRef->sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */
  48072. pAudioBufferRef->cursor = 0;
  48073. pAudioBufferRef->sizeInFrames = sizeInFrames;
  48074. pAudioBufferRef->pData = pData;
  48075. return MA_SUCCESS;
  48076. }
  48077. MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef)
  48078. {
  48079. if (pAudioBufferRef == NULL) {
  48080. return;
  48081. }
  48082. ma_data_source_uninit(&pAudioBufferRef->ds);
  48083. }
  48084. MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames)
  48085. {
  48086. if (pAudioBufferRef == NULL) {
  48087. return MA_INVALID_ARGS;
  48088. }
  48089. pAudioBufferRef->cursor = 0;
  48090. pAudioBufferRef->sizeInFrames = sizeInFrames;
  48091. pAudioBufferRef->pData = pData;
  48092. return MA_SUCCESS;
  48093. }
  48094. MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
  48095. {
  48096. ma_uint64 totalFramesRead = 0;
  48097. if (pAudioBufferRef == NULL) {
  48098. return 0;
  48099. }
  48100. if (frameCount == 0) {
  48101. return 0;
  48102. }
  48103. while (totalFramesRead < frameCount) {
  48104. ma_uint64 framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48105. ma_uint64 framesRemaining = frameCount - totalFramesRead;
  48106. ma_uint64 framesToRead;
  48107. framesToRead = framesRemaining;
  48108. if (framesToRead > framesAvailable) {
  48109. framesToRead = framesAvailable;
  48110. }
  48111. if (pFramesOut != NULL) {
  48112. 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);
  48113. }
  48114. totalFramesRead += framesToRead;
  48115. pAudioBufferRef->cursor += framesToRead;
  48116. if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) {
  48117. if (loop) {
  48118. pAudioBufferRef->cursor = 0;
  48119. } else {
  48120. break; /* We've reached the end and we're not looping. Done. */
  48121. }
  48122. }
  48123. MA_ASSERT(pAudioBufferRef->cursor < pAudioBufferRef->sizeInFrames);
  48124. }
  48125. return totalFramesRead;
  48126. }
  48127. MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex)
  48128. {
  48129. if (pAudioBufferRef == NULL) {
  48130. return MA_INVALID_ARGS;
  48131. }
  48132. if (frameIndex > pAudioBufferRef->sizeInFrames) {
  48133. return MA_INVALID_ARGS;
  48134. }
  48135. pAudioBufferRef->cursor = (size_t)frameIndex;
  48136. return MA_SUCCESS;
  48137. }
  48138. MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount)
  48139. {
  48140. ma_uint64 framesAvailable;
  48141. ma_uint64 frameCount = 0;
  48142. if (ppFramesOut != NULL) {
  48143. *ppFramesOut = NULL; /* Safety. */
  48144. }
  48145. if (pFrameCount != NULL) {
  48146. frameCount = *pFrameCount;
  48147. *pFrameCount = 0; /* Safety. */
  48148. }
  48149. if (pAudioBufferRef == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
  48150. return MA_INVALID_ARGS;
  48151. }
  48152. framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48153. if (frameCount > framesAvailable) {
  48154. frameCount = framesAvailable;
  48155. }
  48156. *ppFramesOut = ma_offset_ptr(pAudioBufferRef->pData, pAudioBufferRef->cursor * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels));
  48157. *pFrameCount = frameCount;
  48158. return MA_SUCCESS;
  48159. }
  48160. MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount)
  48161. {
  48162. ma_uint64 framesAvailable;
  48163. if (pAudioBufferRef == NULL) {
  48164. return MA_INVALID_ARGS;
  48165. }
  48166. framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48167. if (frameCount > framesAvailable) {
  48168. 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. */
  48169. }
  48170. pAudioBufferRef->cursor += frameCount;
  48171. if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) {
  48172. return MA_AT_END; /* Successful. Need to tell the caller that the end has been reached so that it can loop if desired. */
  48173. } else {
  48174. return MA_SUCCESS;
  48175. }
  48176. }
  48177. MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef)
  48178. {
  48179. if (pAudioBufferRef == NULL) {
  48180. return MA_FALSE;
  48181. }
  48182. return pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames;
  48183. }
  48184. MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor)
  48185. {
  48186. if (pCursor == NULL) {
  48187. return MA_INVALID_ARGS;
  48188. }
  48189. *pCursor = 0;
  48190. if (pAudioBufferRef == NULL) {
  48191. return MA_INVALID_ARGS;
  48192. }
  48193. *pCursor = pAudioBufferRef->cursor;
  48194. return MA_SUCCESS;
  48195. }
  48196. MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength)
  48197. {
  48198. if (pLength == NULL) {
  48199. return MA_INVALID_ARGS;
  48200. }
  48201. *pLength = 0;
  48202. if (pAudioBufferRef == NULL) {
  48203. return MA_INVALID_ARGS;
  48204. }
  48205. *pLength = pAudioBufferRef->sizeInFrames;
  48206. return MA_SUCCESS;
  48207. }
  48208. MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames)
  48209. {
  48210. if (pAvailableFrames == NULL) {
  48211. return MA_INVALID_ARGS;
  48212. }
  48213. *pAvailableFrames = 0;
  48214. if (pAudioBufferRef == NULL) {
  48215. return MA_INVALID_ARGS;
  48216. }
  48217. if (pAudioBufferRef->sizeInFrames <= pAudioBufferRef->cursor) {
  48218. *pAvailableFrames = 0;
  48219. } else {
  48220. *pAvailableFrames = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  48221. }
  48222. return MA_SUCCESS;
  48223. }
  48224. 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)
  48225. {
  48226. ma_audio_buffer_config config;
  48227. MA_ZERO_OBJECT(&config);
  48228. config.format = format;
  48229. config.channels = channels;
  48230. config.sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */
  48231. config.sizeInFrames = sizeInFrames;
  48232. config.pData = pData;
  48233. ma_allocation_callbacks_init_copy(&config.allocationCallbacks, pAllocationCallbacks);
  48234. return config;
  48235. }
  48236. static ma_result ma_audio_buffer_init_ex(const ma_audio_buffer_config* pConfig, ma_bool32 doCopy, ma_audio_buffer* pAudioBuffer)
  48237. {
  48238. ma_result result;
  48239. if (pAudioBuffer == NULL) {
  48240. return MA_INVALID_ARGS;
  48241. }
  48242. MA_ZERO_MEMORY(pAudioBuffer, sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData)); /* Safety. Don't overwrite the extra data. */
  48243. if (pConfig == NULL) {
  48244. return MA_INVALID_ARGS;
  48245. }
  48246. if (pConfig->sizeInFrames == 0) {
  48247. return MA_INVALID_ARGS; /* Not allowing buffer sizes of 0 frames. */
  48248. }
  48249. result = ma_audio_buffer_ref_init(pConfig->format, pConfig->channels, NULL, 0, &pAudioBuffer->ref);
  48250. if (result != MA_SUCCESS) {
  48251. return result;
  48252. }
  48253. /* TODO: Version 0.12. Set this in ma_audio_buffer_ref_init() instead of here. */
  48254. pAudioBuffer->ref.sampleRate = pConfig->sampleRate;
  48255. ma_allocation_callbacks_init_copy(&pAudioBuffer->allocationCallbacks, &pConfig->allocationCallbacks);
  48256. if (doCopy) {
  48257. ma_uint64 allocationSizeInBytes;
  48258. void* pData;
  48259. allocationSizeInBytes = pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels);
  48260. if (allocationSizeInBytes > MA_SIZE_MAX) {
  48261. return MA_OUT_OF_MEMORY; /* Too big. */
  48262. }
  48263. pData = ma_malloc((size_t)allocationSizeInBytes, &pAudioBuffer->allocationCallbacks); /* Safe cast to size_t. */
  48264. if (pData == NULL) {
  48265. return MA_OUT_OF_MEMORY;
  48266. }
  48267. if (pConfig->pData != NULL) {
  48268. ma_copy_pcm_frames(pData, pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48269. } else {
  48270. ma_silence_pcm_frames(pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48271. }
  48272. ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pData, pConfig->sizeInFrames);
  48273. pAudioBuffer->ownsData = MA_TRUE;
  48274. } else {
  48275. ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pConfig->pData, pConfig->sizeInFrames);
  48276. pAudioBuffer->ownsData = MA_FALSE;
  48277. }
  48278. return MA_SUCCESS;
  48279. }
  48280. static void ma_audio_buffer_uninit_ex(ma_audio_buffer* pAudioBuffer, ma_bool32 doFree)
  48281. {
  48282. if (pAudioBuffer == NULL) {
  48283. return;
  48284. }
  48285. if (pAudioBuffer->ownsData && pAudioBuffer->ref.pData != &pAudioBuffer->_pExtraData[0]) {
  48286. 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. */
  48287. }
  48288. if (doFree) {
  48289. ma_free(pAudioBuffer, &pAudioBuffer->allocationCallbacks);
  48290. }
  48291. ma_audio_buffer_ref_uninit(&pAudioBuffer->ref);
  48292. }
  48293. MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
  48294. {
  48295. return ma_audio_buffer_init_ex(pConfig, MA_FALSE, pAudioBuffer);
  48296. }
  48297. MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
  48298. {
  48299. return ma_audio_buffer_init_ex(pConfig, MA_TRUE, pAudioBuffer);
  48300. }
  48301. MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer)
  48302. {
  48303. ma_result result;
  48304. ma_audio_buffer* pAudioBuffer;
  48305. ma_audio_buffer_config innerConfig; /* We'll be making some changes to the config, so need to make a copy. */
  48306. ma_uint64 allocationSizeInBytes;
  48307. if (ppAudioBuffer == NULL) {
  48308. return MA_INVALID_ARGS;
  48309. }
  48310. *ppAudioBuffer = NULL; /* Safety. */
  48311. if (pConfig == NULL) {
  48312. return MA_INVALID_ARGS;
  48313. }
  48314. innerConfig = *pConfig;
  48315. ma_allocation_callbacks_init_copy(&innerConfig.allocationCallbacks, &pConfig->allocationCallbacks);
  48316. allocationSizeInBytes = sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData) + (pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels));
  48317. if (allocationSizeInBytes > MA_SIZE_MAX) {
  48318. return MA_OUT_OF_MEMORY; /* Too big. */
  48319. }
  48320. pAudioBuffer = (ma_audio_buffer*)ma_malloc((size_t)allocationSizeInBytes, &innerConfig.allocationCallbacks); /* Safe cast to size_t. */
  48321. if (pAudioBuffer == NULL) {
  48322. return MA_OUT_OF_MEMORY;
  48323. }
  48324. if (pConfig->pData != NULL) {
  48325. ma_copy_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48326. } else {
  48327. ma_silence_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  48328. }
  48329. innerConfig.pData = &pAudioBuffer->_pExtraData[0];
  48330. result = ma_audio_buffer_init_ex(&innerConfig, MA_FALSE, pAudioBuffer);
  48331. if (result != MA_SUCCESS) {
  48332. ma_free(pAudioBuffer, &innerConfig.allocationCallbacks);
  48333. return result;
  48334. }
  48335. *ppAudioBuffer = pAudioBuffer;
  48336. return MA_SUCCESS;
  48337. }
  48338. MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer)
  48339. {
  48340. ma_audio_buffer_uninit_ex(pAudioBuffer, MA_FALSE);
  48341. }
  48342. MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer)
  48343. {
  48344. ma_audio_buffer_uninit_ex(pAudioBuffer, MA_TRUE);
  48345. }
  48346. MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
  48347. {
  48348. if (pAudioBuffer == NULL) {
  48349. return 0;
  48350. }
  48351. return ma_audio_buffer_ref_read_pcm_frames(&pAudioBuffer->ref, pFramesOut, frameCount, loop);
  48352. }
  48353. MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex)
  48354. {
  48355. if (pAudioBuffer == NULL) {
  48356. return MA_INVALID_ARGS;
  48357. }
  48358. return ma_audio_buffer_ref_seek_to_pcm_frame(&pAudioBuffer->ref, frameIndex);
  48359. }
  48360. MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount)
  48361. {
  48362. if (ppFramesOut != NULL) {
  48363. *ppFramesOut = NULL; /* Safety. */
  48364. }
  48365. if (pAudioBuffer == NULL) {
  48366. if (pFrameCount != NULL) {
  48367. *pFrameCount = 0;
  48368. }
  48369. return MA_INVALID_ARGS;
  48370. }
  48371. return ma_audio_buffer_ref_map(&pAudioBuffer->ref, ppFramesOut, pFrameCount);
  48372. }
  48373. MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount)
  48374. {
  48375. if (pAudioBuffer == NULL) {
  48376. return MA_INVALID_ARGS;
  48377. }
  48378. return ma_audio_buffer_ref_unmap(&pAudioBuffer->ref, frameCount);
  48379. }
  48380. MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer)
  48381. {
  48382. if (pAudioBuffer == NULL) {
  48383. return MA_FALSE;
  48384. }
  48385. return ma_audio_buffer_ref_at_end(&pAudioBuffer->ref);
  48386. }
  48387. MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor)
  48388. {
  48389. if (pAudioBuffer == NULL) {
  48390. return MA_INVALID_ARGS;
  48391. }
  48392. return ma_audio_buffer_ref_get_cursor_in_pcm_frames(&pAudioBuffer->ref, pCursor);
  48393. }
  48394. MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength)
  48395. {
  48396. if (pAudioBuffer == NULL) {
  48397. return MA_INVALID_ARGS;
  48398. }
  48399. return ma_audio_buffer_ref_get_length_in_pcm_frames(&pAudioBuffer->ref, pLength);
  48400. }
  48401. MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames)
  48402. {
  48403. if (pAvailableFrames == NULL) {
  48404. return MA_INVALID_ARGS;
  48405. }
  48406. *pAvailableFrames = 0;
  48407. if (pAudioBuffer == NULL) {
  48408. return MA_INVALID_ARGS;
  48409. }
  48410. return ma_audio_buffer_ref_get_available_frames(&pAudioBuffer->ref, pAvailableFrames);
  48411. }
  48412. MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData)
  48413. {
  48414. if (pData == NULL) {
  48415. return MA_INVALID_ARGS;
  48416. }
  48417. MA_ZERO_OBJECT(pData);
  48418. pData->format = format;
  48419. pData->channels = channels;
  48420. pData->pTail = &pData->head;
  48421. return MA_SUCCESS;
  48422. }
  48423. MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks)
  48424. {
  48425. ma_paged_audio_buffer_page* pPage;
  48426. if (pData == NULL) {
  48427. return;
  48428. }
  48429. /* All pages need to be freed. */
  48430. pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pData->head.pNext);
  48431. while (pPage != NULL) {
  48432. ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPage->pNext);
  48433. ma_free(pPage, pAllocationCallbacks);
  48434. pPage = pNext;
  48435. }
  48436. }
  48437. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData)
  48438. {
  48439. if (pData == NULL) {
  48440. return NULL;
  48441. }
  48442. return &pData->head;
  48443. }
  48444. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData)
  48445. {
  48446. if (pData == NULL) {
  48447. return NULL;
  48448. }
  48449. return pData->pTail;
  48450. }
  48451. MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength)
  48452. {
  48453. ma_paged_audio_buffer_page* pPage;
  48454. if (pLength == NULL) {
  48455. return MA_INVALID_ARGS;
  48456. }
  48457. *pLength = 0;
  48458. if (pData == NULL) {
  48459. return MA_INVALID_ARGS;
  48460. }
  48461. /* Calculate the length from the linked list. */
  48462. for (pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pData->head.pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPage->pNext)) {
  48463. *pLength += pPage->sizeInFrames;
  48464. }
  48465. return MA_SUCCESS;
  48466. }
  48467. 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)
  48468. {
  48469. ma_paged_audio_buffer_page* pPage;
  48470. ma_uint64 allocationSize;
  48471. if (ppPage == NULL) {
  48472. return MA_INVALID_ARGS;
  48473. }
  48474. *ppPage = NULL;
  48475. if (pData == NULL) {
  48476. return MA_INVALID_ARGS;
  48477. }
  48478. allocationSize = sizeof(*pPage) + (pageSizeInFrames * ma_get_bytes_per_frame(pData->format, pData->channels));
  48479. if (allocationSize > MA_SIZE_MAX) {
  48480. return MA_OUT_OF_MEMORY; /* Too big. */
  48481. }
  48482. pPage = (ma_paged_audio_buffer_page*)ma_malloc((size_t)allocationSize, pAllocationCallbacks); /* Safe cast to size_t. */
  48483. if (pPage == NULL) {
  48484. return MA_OUT_OF_MEMORY;
  48485. }
  48486. pPage->pNext = NULL;
  48487. pPage->sizeInFrames = pageSizeInFrames;
  48488. if (pInitialData != NULL) {
  48489. ma_copy_pcm_frames(pPage->pAudioData, pInitialData, pageSizeInFrames, pData->format, pData->channels);
  48490. }
  48491. *ppPage = pPage;
  48492. return MA_SUCCESS;
  48493. }
  48494. 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)
  48495. {
  48496. if (pData == NULL || pPage == NULL) {
  48497. return MA_INVALID_ARGS;
  48498. }
  48499. /* It's assumed the page is not attached to the list. */
  48500. ma_free(pPage, pAllocationCallbacks);
  48501. return MA_SUCCESS;
  48502. }
  48503. MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage)
  48504. {
  48505. if (pData == NULL || pPage == NULL) {
  48506. return MA_INVALID_ARGS;
  48507. }
  48508. /* 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. */
  48509. /* First thing to do is update the tail. */
  48510. for (;;) {
  48511. ma_paged_audio_buffer_page* pOldTail = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pData->pTail);
  48512. ma_paged_audio_buffer_page* pNewTail = pPage;
  48513. if (ma_atomic_compare_exchange_weak_ptr((volatile void**)&pData->pTail, (void**)&pOldTail, pNewTail)) {
  48514. /* 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. */
  48515. ma_atomic_exchange_ptr(&pOldTail->pNext, pPage);
  48516. break; /* Done. */
  48517. }
  48518. }
  48519. return MA_SUCCESS;
  48520. }
  48521. 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)
  48522. {
  48523. ma_result result;
  48524. ma_paged_audio_buffer_page* pPage;
  48525. result = ma_paged_audio_buffer_data_allocate_page(pData, pageSizeInFrames, pInitialData, pAllocationCallbacks, &pPage);
  48526. if (result != MA_SUCCESS) {
  48527. return result;
  48528. }
  48529. return ma_paged_audio_buffer_data_append_page(pData, pPage); /* <-- Should never fail. */
  48530. }
  48531. MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData)
  48532. {
  48533. ma_paged_audio_buffer_config config;
  48534. MA_ZERO_OBJECT(&config);
  48535. config.pData = pData;
  48536. return config;
  48537. }
  48538. static ma_result ma_paged_audio_buffer__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  48539. {
  48540. return ma_paged_audio_buffer_read_pcm_frames((ma_paged_audio_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead);
  48541. }
  48542. static ma_result ma_paged_audio_buffer__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  48543. {
  48544. return ma_paged_audio_buffer_seek_to_pcm_frame((ma_paged_audio_buffer*)pDataSource, frameIndex);
  48545. }
  48546. 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)
  48547. {
  48548. ma_paged_audio_buffer* pPagedAudioBuffer = (ma_paged_audio_buffer*)pDataSource;
  48549. *pFormat = pPagedAudioBuffer->pData->format;
  48550. *pChannels = pPagedAudioBuffer->pData->channels;
  48551. *pSampleRate = 0; /* There is no notion of a sample rate with audio buffers. */
  48552. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pPagedAudioBuffer->pData->channels);
  48553. return MA_SUCCESS;
  48554. }
  48555. static ma_result ma_paged_audio_buffer__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  48556. {
  48557. return ma_paged_audio_buffer_get_cursor_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pCursor);
  48558. }
  48559. static ma_result ma_paged_audio_buffer__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  48560. {
  48561. return ma_paged_audio_buffer_get_length_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pLength);
  48562. }
  48563. static ma_data_source_vtable g_ma_paged_audio_buffer_data_source_vtable =
  48564. {
  48565. ma_paged_audio_buffer__data_source_on_read,
  48566. ma_paged_audio_buffer__data_source_on_seek,
  48567. ma_paged_audio_buffer__data_source_on_get_data_format,
  48568. ma_paged_audio_buffer__data_source_on_get_cursor,
  48569. ma_paged_audio_buffer__data_source_on_get_length,
  48570. NULL, /* onSetLooping */
  48571. 0
  48572. };
  48573. MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer)
  48574. {
  48575. ma_result result;
  48576. ma_data_source_config dataSourceConfig;
  48577. if (pPagedAudioBuffer == NULL) {
  48578. return MA_INVALID_ARGS;
  48579. }
  48580. MA_ZERO_OBJECT(pPagedAudioBuffer);
  48581. /* A config is required for the format and channel count. */
  48582. if (pConfig == NULL) {
  48583. return MA_INVALID_ARGS;
  48584. }
  48585. if (pConfig->pData == NULL) {
  48586. return MA_INVALID_ARGS; /* No underlying data specified. */
  48587. }
  48588. dataSourceConfig = ma_data_source_config_init();
  48589. dataSourceConfig.vtable = &g_ma_paged_audio_buffer_data_source_vtable;
  48590. result = ma_data_source_init(&dataSourceConfig, &pPagedAudioBuffer->ds);
  48591. if (result != MA_SUCCESS) {
  48592. return result;
  48593. }
  48594. pPagedAudioBuffer->pData = pConfig->pData;
  48595. pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pConfig->pData);
  48596. pPagedAudioBuffer->relativeCursor = 0;
  48597. pPagedAudioBuffer->absoluteCursor = 0;
  48598. return MA_SUCCESS;
  48599. }
  48600. MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer)
  48601. {
  48602. if (pPagedAudioBuffer == NULL) {
  48603. return;
  48604. }
  48605. /* Nothing to do. The data needs to be deleted separately. */
  48606. }
  48607. MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  48608. {
  48609. ma_result result = MA_SUCCESS;
  48610. ma_uint64 totalFramesRead = 0;
  48611. ma_format format;
  48612. ma_uint32 channels;
  48613. if (pPagedAudioBuffer == NULL) {
  48614. return MA_INVALID_ARGS;
  48615. }
  48616. format = pPagedAudioBuffer->pData->format;
  48617. channels = pPagedAudioBuffer->pData->channels;
  48618. while (totalFramesRead < frameCount) {
  48619. /* Read from the current page. The buffer should never be in a state where this is NULL. */
  48620. ma_uint64 framesRemainingInCurrentPage;
  48621. ma_uint64 framesRemainingToRead = frameCount - totalFramesRead;
  48622. ma_uint64 framesToReadThisIteration;
  48623. MA_ASSERT(pPagedAudioBuffer->pCurrent != NULL);
  48624. framesRemainingInCurrentPage = pPagedAudioBuffer->pCurrent->sizeInFrames - pPagedAudioBuffer->relativeCursor;
  48625. framesToReadThisIteration = ma_min(framesRemainingInCurrentPage, framesRemainingToRead);
  48626. 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);
  48627. totalFramesRead += framesToReadThisIteration;
  48628. pPagedAudioBuffer->absoluteCursor += framesToReadThisIteration;
  48629. pPagedAudioBuffer->relativeCursor += framesToReadThisIteration;
  48630. /* Move to the next page if necessary. If there's no more pages, we need to return MA_AT_END. */
  48631. MA_ASSERT(pPagedAudioBuffer->relativeCursor <= pPagedAudioBuffer->pCurrent->sizeInFrames);
  48632. if (pPagedAudioBuffer->relativeCursor == pPagedAudioBuffer->pCurrent->sizeInFrames) {
  48633. /* We reached the end of the page. Need to move to the next. If there's no more pages, we're done. */
  48634. ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPagedAudioBuffer->pCurrent->pNext);
  48635. if (pNext == NULL) {
  48636. result = MA_AT_END;
  48637. break; /* We've reached the end. */
  48638. } else {
  48639. pPagedAudioBuffer->pCurrent = pNext;
  48640. pPagedAudioBuffer->relativeCursor = 0;
  48641. }
  48642. }
  48643. }
  48644. if (pFramesRead != NULL) {
  48645. *pFramesRead = totalFramesRead;
  48646. }
  48647. return result;
  48648. }
  48649. MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex)
  48650. {
  48651. if (pPagedAudioBuffer == NULL) {
  48652. return MA_INVALID_ARGS;
  48653. }
  48654. if (frameIndex == pPagedAudioBuffer->absoluteCursor) {
  48655. return MA_SUCCESS; /* Nothing to do. */
  48656. }
  48657. if (frameIndex < pPagedAudioBuffer->absoluteCursor) {
  48658. /* Moving backwards. Need to move the cursor back to the start, and then move forward. */
  48659. pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData);
  48660. pPagedAudioBuffer->absoluteCursor = 0;
  48661. pPagedAudioBuffer->relativeCursor = 0;
  48662. /* Fall through to the forward seeking section below. */
  48663. }
  48664. if (frameIndex > pPagedAudioBuffer->absoluteCursor) {
  48665. /* Moving forward. */
  48666. ma_paged_audio_buffer_page* pPage;
  48667. ma_uint64 runningCursor = 0;
  48668. for (pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData)->pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(&pPage->pNext)) {
  48669. ma_uint64 pageRangeBeg = runningCursor;
  48670. ma_uint64 pageRangeEnd = pageRangeBeg + pPage->sizeInFrames;
  48671. if (frameIndex >= pageRangeBeg) {
  48672. if (frameIndex < pageRangeEnd || (frameIndex == pageRangeEnd && pPage == (ma_paged_audio_buffer_page*)ma_atomic_load_ptr(ma_paged_audio_buffer_data_get_tail(pPagedAudioBuffer->pData)))) { /* A small edge case - allow seeking to the very end of the buffer. */
  48673. /* We found the page. */
  48674. pPagedAudioBuffer->pCurrent = pPage;
  48675. pPagedAudioBuffer->absoluteCursor = frameIndex;
  48676. pPagedAudioBuffer->relativeCursor = frameIndex - pageRangeBeg;
  48677. return MA_SUCCESS;
  48678. }
  48679. }
  48680. runningCursor = pageRangeEnd;
  48681. }
  48682. /* Getting here means we tried seeking too far forward. Don't change any state. */
  48683. return MA_BAD_SEEK;
  48684. }
  48685. return MA_SUCCESS;
  48686. }
  48687. MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor)
  48688. {
  48689. if (pCursor == NULL) {
  48690. return MA_INVALID_ARGS;
  48691. }
  48692. *pCursor = 0; /* Safety. */
  48693. if (pPagedAudioBuffer == NULL) {
  48694. return MA_INVALID_ARGS;
  48695. }
  48696. *pCursor = pPagedAudioBuffer->absoluteCursor;
  48697. return MA_SUCCESS;
  48698. }
  48699. MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength)
  48700. {
  48701. return ma_paged_audio_buffer_data_get_length_in_pcm_frames(pPagedAudioBuffer->pData, pLength);
  48702. }
  48703. /**************************************************************************************************************************************************************
  48704. VFS
  48705. **************************************************************************************************************************************************************/
  48706. MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48707. {
  48708. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48709. if (pFile == NULL) {
  48710. return MA_INVALID_ARGS;
  48711. }
  48712. *pFile = NULL;
  48713. if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
  48714. return MA_INVALID_ARGS;
  48715. }
  48716. if (pCallbacks->onOpen == NULL) {
  48717. return MA_NOT_IMPLEMENTED;
  48718. }
  48719. return pCallbacks->onOpen(pVFS, pFilePath, openMode, pFile);
  48720. }
  48721. MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48722. {
  48723. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48724. if (pFile == NULL) {
  48725. return MA_INVALID_ARGS;
  48726. }
  48727. *pFile = NULL;
  48728. if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
  48729. return MA_INVALID_ARGS;
  48730. }
  48731. if (pCallbacks->onOpenW == NULL) {
  48732. return MA_NOT_IMPLEMENTED;
  48733. }
  48734. return pCallbacks->onOpenW(pVFS, pFilePath, openMode, pFile);
  48735. }
  48736. MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file)
  48737. {
  48738. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48739. if (pVFS == NULL || file == NULL) {
  48740. return MA_INVALID_ARGS;
  48741. }
  48742. if (pCallbacks->onClose == NULL) {
  48743. return MA_NOT_IMPLEMENTED;
  48744. }
  48745. return pCallbacks->onClose(pVFS, file);
  48746. }
  48747. MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  48748. {
  48749. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48750. ma_result result;
  48751. size_t bytesRead = 0;
  48752. if (pBytesRead != NULL) {
  48753. *pBytesRead = 0;
  48754. }
  48755. if (pVFS == NULL || file == NULL || pDst == NULL) {
  48756. return MA_INVALID_ARGS;
  48757. }
  48758. if (pCallbacks->onRead == NULL) {
  48759. return MA_NOT_IMPLEMENTED;
  48760. }
  48761. result = pCallbacks->onRead(pVFS, file, pDst, sizeInBytes, &bytesRead);
  48762. if (pBytesRead != NULL) {
  48763. *pBytesRead = bytesRead;
  48764. }
  48765. if (result == MA_SUCCESS && bytesRead == 0 && sizeInBytes > 0) {
  48766. result = MA_AT_END;
  48767. }
  48768. return result;
  48769. }
  48770. MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  48771. {
  48772. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48773. if (pBytesWritten != NULL) {
  48774. *pBytesWritten = 0;
  48775. }
  48776. if (pVFS == NULL || file == NULL || pSrc == NULL) {
  48777. return MA_INVALID_ARGS;
  48778. }
  48779. if (pCallbacks->onWrite == NULL) {
  48780. return MA_NOT_IMPLEMENTED;
  48781. }
  48782. return pCallbacks->onWrite(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  48783. }
  48784. MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  48785. {
  48786. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48787. if (pVFS == NULL || file == NULL) {
  48788. return MA_INVALID_ARGS;
  48789. }
  48790. if (pCallbacks->onSeek == NULL) {
  48791. return MA_NOT_IMPLEMENTED;
  48792. }
  48793. return pCallbacks->onSeek(pVFS, file, offset, origin);
  48794. }
  48795. MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  48796. {
  48797. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48798. if (pCursor == NULL) {
  48799. return MA_INVALID_ARGS;
  48800. }
  48801. *pCursor = 0;
  48802. if (pVFS == NULL || file == NULL) {
  48803. return MA_INVALID_ARGS;
  48804. }
  48805. if (pCallbacks->onTell == NULL) {
  48806. return MA_NOT_IMPLEMENTED;
  48807. }
  48808. return pCallbacks->onTell(pVFS, file, pCursor);
  48809. }
  48810. MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  48811. {
  48812. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  48813. if (pInfo == NULL) {
  48814. return MA_INVALID_ARGS;
  48815. }
  48816. MA_ZERO_OBJECT(pInfo);
  48817. if (pVFS == NULL || file == NULL) {
  48818. return MA_INVALID_ARGS;
  48819. }
  48820. if (pCallbacks->onInfo == NULL) {
  48821. return MA_NOT_IMPLEMENTED;
  48822. }
  48823. return pCallbacks->onInfo(pVFS, file, pInfo);
  48824. }
  48825. #if !defined(MA_USE_WIN32_FILEIO) && (defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO) && !defined(MA_POSIX))
  48826. #define MA_USE_WIN32_FILEIO
  48827. #endif
  48828. #if defined(MA_USE_WIN32_FILEIO)
  48829. /*
  48830. We need to dynamically load SetFilePointer or SetFilePointerEx because older versions of Windows do
  48831. not have the Ex version. We therefore need to do some dynamic branching depending on what's available.
  48832. We load these when we load our first file from the default VFS. It's left open for the life of the
  48833. program and is left to the OS to uninitialize when the program terminates.
  48834. */
  48835. typedef DWORD (__stdcall * ma_SetFilePointer_proc)(HANDLE hFile, LONG lDistanceToMove, LONG* lpDistanceToMoveHigh, DWORD dwMoveMethod);
  48836. typedef BOOL (__stdcall * ma_SetFilePointerEx_proc)(HANDLE hFile, LARGE_INTEGER liDistanceToMove, LARGE_INTEGER* lpNewFilePointer, DWORD dwMoveMethod);
  48837. static ma_handle hKernel32DLL = NULL;
  48838. static ma_SetFilePointer_proc ma_SetFilePointer = NULL;
  48839. static ma_SetFilePointerEx_proc ma_SetFilePointerEx = NULL;
  48840. static void ma_win32_fileio_init(void)
  48841. {
  48842. if (hKernel32DLL == NULL) {
  48843. hKernel32DLL = ma_dlopen(NULL, "kernel32.dll");
  48844. if (hKernel32DLL != NULL) {
  48845. ma_SetFilePointer = (ma_SetFilePointer_proc) ma_dlsym(NULL, hKernel32DLL, "SetFilePointer");
  48846. ma_SetFilePointerEx = (ma_SetFilePointerEx_proc)ma_dlsym(NULL, hKernel32DLL, "SetFilePointerEx");
  48847. }
  48848. }
  48849. }
  48850. static void ma_default_vfs__get_open_settings_win32(ma_uint32 openMode, DWORD* pDesiredAccess, DWORD* pShareMode, DWORD* pCreationDisposition)
  48851. {
  48852. *pDesiredAccess = 0;
  48853. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  48854. *pDesiredAccess |= GENERIC_READ;
  48855. }
  48856. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  48857. *pDesiredAccess |= GENERIC_WRITE;
  48858. }
  48859. *pShareMode = 0;
  48860. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  48861. *pShareMode |= FILE_SHARE_READ;
  48862. }
  48863. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  48864. *pCreationDisposition = CREATE_ALWAYS; /* Opening in write mode. Truncate. */
  48865. } else {
  48866. *pCreationDisposition = OPEN_EXISTING; /* Opening in read mode. File must exist. */
  48867. }
  48868. }
  48869. static ma_result ma_default_vfs_open__win32(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48870. {
  48871. HANDLE hFile;
  48872. DWORD dwDesiredAccess;
  48873. DWORD dwShareMode;
  48874. DWORD dwCreationDisposition;
  48875. (void)pVFS;
  48876. /* Load some Win32 symbols dynamically so we can dynamically check for the existence of SetFilePointerEx. */
  48877. ma_win32_fileio_init();
  48878. ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition);
  48879. hFile = CreateFileA(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  48880. if (hFile == INVALID_HANDLE_VALUE) {
  48881. return ma_result_from_GetLastError(GetLastError());
  48882. }
  48883. *pFile = hFile;
  48884. return MA_SUCCESS;
  48885. }
  48886. static ma_result ma_default_vfs_open_w__win32(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  48887. {
  48888. HANDLE hFile;
  48889. DWORD dwDesiredAccess;
  48890. DWORD dwShareMode;
  48891. DWORD dwCreationDisposition;
  48892. (void)pVFS;
  48893. /* Load some Win32 symbols dynamically so we can dynamically check for the existence of SetFilePointerEx. */
  48894. ma_win32_fileio_init();
  48895. ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition);
  48896. hFile = CreateFileW(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  48897. if (hFile == INVALID_HANDLE_VALUE) {
  48898. return ma_result_from_GetLastError(GetLastError());
  48899. }
  48900. *pFile = hFile;
  48901. return MA_SUCCESS;
  48902. }
  48903. static ma_result ma_default_vfs_close__win32(ma_vfs* pVFS, ma_vfs_file file)
  48904. {
  48905. (void)pVFS;
  48906. if (CloseHandle((HANDLE)file) == 0) {
  48907. return ma_result_from_GetLastError(GetLastError());
  48908. }
  48909. return MA_SUCCESS;
  48910. }
  48911. static ma_result ma_default_vfs_read__win32(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  48912. {
  48913. ma_result result = MA_SUCCESS;
  48914. size_t totalBytesRead;
  48915. (void)pVFS;
  48916. totalBytesRead = 0;
  48917. while (totalBytesRead < sizeInBytes) {
  48918. size_t bytesRemaining;
  48919. DWORD bytesToRead;
  48920. DWORD bytesRead;
  48921. BOOL readResult;
  48922. bytesRemaining = sizeInBytes - totalBytesRead;
  48923. if (bytesRemaining >= 0xFFFFFFFF) {
  48924. bytesToRead = 0xFFFFFFFF;
  48925. } else {
  48926. bytesToRead = (DWORD)bytesRemaining;
  48927. }
  48928. readResult = ReadFile((HANDLE)file, ma_offset_ptr(pDst, totalBytesRead), bytesToRead, &bytesRead, NULL);
  48929. if (readResult == 1 && bytesRead == 0) {
  48930. result = MA_AT_END;
  48931. break; /* EOF */
  48932. }
  48933. totalBytesRead += bytesRead;
  48934. if (bytesRead < bytesToRead) {
  48935. break; /* EOF */
  48936. }
  48937. if (readResult == 0) {
  48938. result = ma_result_from_GetLastError(GetLastError());
  48939. break;
  48940. }
  48941. }
  48942. if (pBytesRead != NULL) {
  48943. *pBytesRead = totalBytesRead;
  48944. }
  48945. return result;
  48946. }
  48947. static ma_result ma_default_vfs_write__win32(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  48948. {
  48949. ma_result result = MA_SUCCESS;
  48950. size_t totalBytesWritten;
  48951. (void)pVFS;
  48952. totalBytesWritten = 0;
  48953. while (totalBytesWritten < sizeInBytes) {
  48954. size_t bytesRemaining;
  48955. DWORD bytesToWrite;
  48956. DWORD bytesWritten;
  48957. BOOL writeResult;
  48958. bytesRemaining = sizeInBytes - totalBytesWritten;
  48959. if (bytesRemaining >= 0xFFFFFFFF) {
  48960. bytesToWrite = 0xFFFFFFFF;
  48961. } else {
  48962. bytesToWrite = (DWORD)bytesRemaining;
  48963. }
  48964. writeResult = WriteFile((HANDLE)file, ma_offset_ptr(pSrc, totalBytesWritten), bytesToWrite, &bytesWritten, NULL);
  48965. totalBytesWritten += bytesWritten;
  48966. if (writeResult == 0) {
  48967. result = ma_result_from_GetLastError(GetLastError());
  48968. break;
  48969. }
  48970. }
  48971. if (pBytesWritten != NULL) {
  48972. *pBytesWritten = totalBytesWritten;
  48973. }
  48974. return result;
  48975. }
  48976. static ma_result ma_default_vfs_seek__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  48977. {
  48978. LARGE_INTEGER liDistanceToMove;
  48979. DWORD dwMoveMethod;
  48980. BOOL result;
  48981. (void)pVFS;
  48982. liDistanceToMove.QuadPart = offset;
  48983. /* */ if (origin == ma_seek_origin_current) {
  48984. dwMoveMethod = FILE_CURRENT;
  48985. } else if (origin == ma_seek_origin_end) {
  48986. dwMoveMethod = FILE_END;
  48987. } else {
  48988. dwMoveMethod = FILE_BEGIN;
  48989. }
  48990. if (ma_SetFilePointerEx != NULL) {
  48991. result = ma_SetFilePointerEx((HANDLE)file, liDistanceToMove, NULL, dwMoveMethod);
  48992. } else if (ma_SetFilePointer != NULL) {
  48993. /* No SetFilePointerEx() so restrict to 31 bits. */
  48994. if (origin > 0x7FFFFFFF) {
  48995. return MA_OUT_OF_RANGE;
  48996. }
  48997. result = ma_SetFilePointer((HANDLE)file, (LONG)liDistanceToMove.QuadPart, NULL, dwMoveMethod);
  48998. } else {
  48999. return MA_NOT_IMPLEMENTED;
  49000. }
  49001. if (result == 0) {
  49002. return ma_result_from_GetLastError(GetLastError());
  49003. }
  49004. return MA_SUCCESS;
  49005. }
  49006. static ma_result ma_default_vfs_tell__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49007. {
  49008. LARGE_INTEGER liZero;
  49009. LARGE_INTEGER liTell;
  49010. BOOL result;
  49011. (void)pVFS;
  49012. liZero.QuadPart = 0;
  49013. if (ma_SetFilePointerEx != NULL) {
  49014. result = ma_SetFilePointerEx((HANDLE)file, liZero, &liTell, FILE_CURRENT);
  49015. } else if (ma_SetFilePointer != NULL) {
  49016. LONG tell;
  49017. result = ma_SetFilePointer((HANDLE)file, (LONG)liZero.QuadPart, &tell, FILE_CURRENT);
  49018. liTell.QuadPart = tell;
  49019. } else {
  49020. return MA_NOT_IMPLEMENTED;
  49021. }
  49022. if (result == 0) {
  49023. return ma_result_from_GetLastError(GetLastError());
  49024. }
  49025. if (pCursor != NULL) {
  49026. *pCursor = liTell.QuadPart;
  49027. }
  49028. return MA_SUCCESS;
  49029. }
  49030. static ma_result ma_default_vfs_info__win32(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49031. {
  49032. BY_HANDLE_FILE_INFORMATION fi;
  49033. BOOL result;
  49034. (void)pVFS;
  49035. result = GetFileInformationByHandle((HANDLE)file, &fi);
  49036. if (result == 0) {
  49037. return ma_result_from_GetLastError(GetLastError());
  49038. }
  49039. pInfo->sizeInBytes = ((ma_uint64)fi.nFileSizeHigh << 32) | ((ma_uint64)fi.nFileSizeLow);
  49040. return MA_SUCCESS;
  49041. }
  49042. #else
  49043. static ma_result ma_default_vfs_open__stdio(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49044. {
  49045. ma_result result;
  49046. FILE* pFileStd;
  49047. const char* pOpenModeStr;
  49048. MA_ASSERT(pFilePath != NULL);
  49049. MA_ASSERT(openMode != 0);
  49050. MA_ASSERT(pFile != NULL);
  49051. (void)pVFS;
  49052. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  49053. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  49054. pOpenModeStr = "r+";
  49055. } else {
  49056. pOpenModeStr = "rb";
  49057. }
  49058. } else {
  49059. pOpenModeStr = "wb";
  49060. }
  49061. result = ma_fopen(&pFileStd, pFilePath, pOpenModeStr);
  49062. if (result != MA_SUCCESS) {
  49063. return result;
  49064. }
  49065. *pFile = pFileStd;
  49066. return MA_SUCCESS;
  49067. }
  49068. static ma_result ma_default_vfs_open_w__stdio(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49069. {
  49070. ma_result result;
  49071. FILE* pFileStd;
  49072. const wchar_t* pOpenModeStr;
  49073. MA_ASSERT(pFilePath != NULL);
  49074. MA_ASSERT(openMode != 0);
  49075. MA_ASSERT(pFile != NULL);
  49076. (void)pVFS;
  49077. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  49078. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  49079. pOpenModeStr = L"r+";
  49080. } else {
  49081. pOpenModeStr = L"rb";
  49082. }
  49083. } else {
  49084. pOpenModeStr = L"wb";
  49085. }
  49086. result = ma_wfopen(&pFileStd, pFilePath, pOpenModeStr, (pVFS != NULL) ? &((ma_default_vfs*)pVFS)->allocationCallbacks : NULL);
  49087. if (result != MA_SUCCESS) {
  49088. return result;
  49089. }
  49090. *pFile = pFileStd;
  49091. return MA_SUCCESS;
  49092. }
  49093. static ma_result ma_default_vfs_close__stdio(ma_vfs* pVFS, ma_vfs_file file)
  49094. {
  49095. MA_ASSERT(file != NULL);
  49096. (void)pVFS;
  49097. fclose((FILE*)file);
  49098. return MA_SUCCESS;
  49099. }
  49100. static ma_result ma_default_vfs_read__stdio(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  49101. {
  49102. size_t result;
  49103. MA_ASSERT(file != NULL);
  49104. MA_ASSERT(pDst != NULL);
  49105. (void)pVFS;
  49106. result = fread(pDst, 1, sizeInBytes, (FILE*)file);
  49107. if (pBytesRead != NULL) {
  49108. *pBytesRead = result;
  49109. }
  49110. if (result != sizeInBytes) {
  49111. if (result == 0 && feof((FILE*)file)) {
  49112. return MA_AT_END;
  49113. } else {
  49114. return ma_result_from_errno(ferror((FILE*)file));
  49115. }
  49116. }
  49117. return MA_SUCCESS;
  49118. }
  49119. static ma_result ma_default_vfs_write__stdio(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  49120. {
  49121. size_t result;
  49122. MA_ASSERT(file != NULL);
  49123. MA_ASSERT(pSrc != NULL);
  49124. (void)pVFS;
  49125. result = fwrite(pSrc, 1, sizeInBytes, (FILE*)file);
  49126. if (pBytesWritten != NULL) {
  49127. *pBytesWritten = result;
  49128. }
  49129. if (result != sizeInBytes) {
  49130. return ma_result_from_errno(ferror((FILE*)file));
  49131. }
  49132. return MA_SUCCESS;
  49133. }
  49134. static ma_result ma_default_vfs_seek__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  49135. {
  49136. int result;
  49137. int whence;
  49138. MA_ASSERT(file != NULL);
  49139. (void)pVFS;
  49140. if (origin == ma_seek_origin_start) {
  49141. whence = SEEK_SET;
  49142. } else if (origin == ma_seek_origin_end) {
  49143. whence = SEEK_END;
  49144. } else {
  49145. whence = SEEK_CUR;
  49146. }
  49147. #if defined(_WIN32)
  49148. #if defined(_MSC_VER) && _MSC_VER > 1200
  49149. result = _fseeki64((FILE*)file, offset, whence);
  49150. #else
  49151. /* No _fseeki64() so restrict to 31 bits. */
  49152. if (origin > 0x7FFFFFFF) {
  49153. return MA_OUT_OF_RANGE;
  49154. }
  49155. result = fseek((FILE*)file, (int)offset, whence);
  49156. #endif
  49157. #else
  49158. result = fseek((FILE*)file, (long int)offset, whence);
  49159. #endif
  49160. if (result != 0) {
  49161. return MA_ERROR;
  49162. }
  49163. return MA_SUCCESS;
  49164. }
  49165. static ma_result ma_default_vfs_tell__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49166. {
  49167. ma_int64 result;
  49168. MA_ASSERT(file != NULL);
  49169. MA_ASSERT(pCursor != NULL);
  49170. (void)pVFS;
  49171. #if defined(_WIN32)
  49172. #if defined(_MSC_VER) && _MSC_VER > 1200
  49173. result = _ftelli64((FILE*)file);
  49174. #else
  49175. result = ftell((FILE*)file);
  49176. #endif
  49177. #else
  49178. result = ftell((FILE*)file);
  49179. #endif
  49180. *pCursor = result;
  49181. return MA_SUCCESS;
  49182. }
  49183. #if !defined(_MSC_VER) && !((defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)) && !defined(MA_BSD)
  49184. int fileno(FILE *stream);
  49185. #endif
  49186. static ma_result ma_default_vfs_info__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49187. {
  49188. int fd;
  49189. struct stat info;
  49190. MA_ASSERT(file != NULL);
  49191. MA_ASSERT(pInfo != NULL);
  49192. (void)pVFS;
  49193. #if defined(_MSC_VER)
  49194. fd = _fileno((FILE*)file);
  49195. #else
  49196. fd = fileno((FILE*)file);
  49197. #endif
  49198. if (fstat(fd, &info) != 0) {
  49199. return ma_result_from_errno(errno);
  49200. }
  49201. pInfo->sizeInBytes = info.st_size;
  49202. return MA_SUCCESS;
  49203. }
  49204. #endif
  49205. static ma_result ma_default_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49206. {
  49207. if (pFile == NULL) {
  49208. return MA_INVALID_ARGS;
  49209. }
  49210. *pFile = NULL;
  49211. if (pFilePath == NULL || openMode == 0) {
  49212. return MA_INVALID_ARGS;
  49213. }
  49214. #if defined(MA_USE_WIN32_FILEIO)
  49215. return ma_default_vfs_open__win32(pVFS, pFilePath, openMode, pFile);
  49216. #else
  49217. return ma_default_vfs_open__stdio(pVFS, pFilePath, openMode, pFile);
  49218. #endif
  49219. }
  49220. static ma_result ma_default_vfs_open_w(ma_vfs* pVFS, const wchar_t* 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_w__win32(pVFS, pFilePath, openMode, pFile);
  49231. #else
  49232. return ma_default_vfs_open_w__stdio(pVFS, pFilePath, openMode, pFile);
  49233. #endif
  49234. }
  49235. static ma_result ma_default_vfs_close(ma_vfs* pVFS, ma_vfs_file file)
  49236. {
  49237. if (file == NULL) {
  49238. return MA_INVALID_ARGS;
  49239. }
  49240. #if defined(MA_USE_WIN32_FILEIO)
  49241. return ma_default_vfs_close__win32(pVFS, file);
  49242. #else
  49243. return ma_default_vfs_close__stdio(pVFS, file);
  49244. #endif
  49245. }
  49246. static ma_result ma_default_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  49247. {
  49248. if (pBytesRead != NULL) {
  49249. *pBytesRead = 0;
  49250. }
  49251. if (file == NULL || pDst == NULL) {
  49252. return MA_INVALID_ARGS;
  49253. }
  49254. #if defined(MA_USE_WIN32_FILEIO)
  49255. return ma_default_vfs_read__win32(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49256. #else
  49257. return ma_default_vfs_read__stdio(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49258. #endif
  49259. }
  49260. static ma_result ma_default_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  49261. {
  49262. if (pBytesWritten != NULL) {
  49263. *pBytesWritten = 0;
  49264. }
  49265. if (file == NULL || pSrc == NULL) {
  49266. return MA_INVALID_ARGS;
  49267. }
  49268. #if defined(MA_USE_WIN32_FILEIO)
  49269. return ma_default_vfs_write__win32(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49270. #else
  49271. return ma_default_vfs_write__stdio(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49272. #endif
  49273. }
  49274. static ma_result ma_default_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  49275. {
  49276. if (file == NULL) {
  49277. return MA_INVALID_ARGS;
  49278. }
  49279. #if defined(MA_USE_WIN32_FILEIO)
  49280. return ma_default_vfs_seek__win32(pVFS, file, offset, origin);
  49281. #else
  49282. return ma_default_vfs_seek__stdio(pVFS, file, offset, origin);
  49283. #endif
  49284. }
  49285. static ma_result ma_default_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49286. {
  49287. if (pCursor == NULL) {
  49288. return MA_INVALID_ARGS;
  49289. }
  49290. *pCursor = 0;
  49291. if (file == NULL) {
  49292. return MA_INVALID_ARGS;
  49293. }
  49294. #if defined(MA_USE_WIN32_FILEIO)
  49295. return ma_default_vfs_tell__win32(pVFS, file, pCursor);
  49296. #else
  49297. return ma_default_vfs_tell__stdio(pVFS, file, pCursor);
  49298. #endif
  49299. }
  49300. static ma_result ma_default_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49301. {
  49302. if (pInfo == NULL) {
  49303. return MA_INVALID_ARGS;
  49304. }
  49305. MA_ZERO_OBJECT(pInfo);
  49306. if (file == NULL) {
  49307. return MA_INVALID_ARGS;
  49308. }
  49309. #if defined(MA_USE_WIN32_FILEIO)
  49310. return ma_default_vfs_info__win32(pVFS, file, pInfo);
  49311. #else
  49312. return ma_default_vfs_info__stdio(pVFS, file, pInfo);
  49313. #endif
  49314. }
  49315. MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks)
  49316. {
  49317. if (pVFS == NULL) {
  49318. return MA_INVALID_ARGS;
  49319. }
  49320. pVFS->cb.onOpen = ma_default_vfs_open;
  49321. pVFS->cb.onOpenW = ma_default_vfs_open_w;
  49322. pVFS->cb.onClose = ma_default_vfs_close;
  49323. pVFS->cb.onRead = ma_default_vfs_read;
  49324. pVFS->cb.onWrite = ma_default_vfs_write;
  49325. pVFS->cb.onSeek = ma_default_vfs_seek;
  49326. pVFS->cb.onTell = ma_default_vfs_tell;
  49327. pVFS->cb.onInfo = ma_default_vfs_info;
  49328. ma_allocation_callbacks_init_copy(&pVFS->allocationCallbacks, pAllocationCallbacks);
  49329. return MA_SUCCESS;
  49330. }
  49331. MA_API ma_result ma_vfs_or_default_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49332. {
  49333. if (pVFS != NULL) {
  49334. return ma_vfs_open(pVFS, pFilePath, openMode, pFile);
  49335. } else {
  49336. return ma_default_vfs_open(pVFS, pFilePath, openMode, pFile);
  49337. }
  49338. }
  49339. MA_API ma_result ma_vfs_or_default_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  49340. {
  49341. if (pVFS != NULL) {
  49342. return ma_vfs_open_w(pVFS, pFilePath, openMode, pFile);
  49343. } else {
  49344. return ma_default_vfs_open_w(pVFS, pFilePath, openMode, pFile);
  49345. }
  49346. }
  49347. MA_API ma_result ma_vfs_or_default_close(ma_vfs* pVFS, ma_vfs_file file)
  49348. {
  49349. if (pVFS != NULL) {
  49350. return ma_vfs_close(pVFS, file);
  49351. } else {
  49352. return ma_default_vfs_close(pVFS, file);
  49353. }
  49354. }
  49355. MA_API ma_result ma_vfs_or_default_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  49356. {
  49357. if (pVFS != NULL) {
  49358. return ma_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49359. } else {
  49360. return ma_default_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead);
  49361. }
  49362. }
  49363. 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)
  49364. {
  49365. if (pVFS != NULL) {
  49366. return ma_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49367. } else {
  49368. return ma_default_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  49369. }
  49370. }
  49371. MA_API ma_result ma_vfs_or_default_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  49372. {
  49373. if (pVFS != NULL) {
  49374. return ma_vfs_seek(pVFS, file, offset, origin);
  49375. } else {
  49376. return ma_default_vfs_seek(pVFS, file, offset, origin);
  49377. }
  49378. }
  49379. MA_API ma_result ma_vfs_or_default_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  49380. {
  49381. if (pVFS != NULL) {
  49382. return ma_vfs_tell(pVFS, file, pCursor);
  49383. } else {
  49384. return ma_default_vfs_tell(pVFS, file, pCursor);
  49385. }
  49386. }
  49387. MA_API ma_result ma_vfs_or_default_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  49388. {
  49389. if (pVFS != NULL) {
  49390. return ma_vfs_info(pVFS, file, pInfo);
  49391. } else {
  49392. return ma_default_vfs_info(pVFS, file, pInfo);
  49393. }
  49394. }
  49395. 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)
  49396. {
  49397. ma_result result;
  49398. ma_vfs_file file;
  49399. ma_file_info info;
  49400. void* pData;
  49401. size_t bytesRead;
  49402. if (ppData != NULL) {
  49403. *ppData = NULL;
  49404. }
  49405. if (pSize != NULL) {
  49406. *pSize = 0;
  49407. }
  49408. if (ppData == NULL) {
  49409. return MA_INVALID_ARGS;
  49410. }
  49411. if (pFilePath != NULL) {
  49412. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  49413. } else {
  49414. result = ma_vfs_or_default_open_w(pVFS, pFilePathW, MA_OPEN_MODE_READ, &file);
  49415. }
  49416. if (result != MA_SUCCESS) {
  49417. return result;
  49418. }
  49419. result = ma_vfs_or_default_info(pVFS, file, &info);
  49420. if (result != MA_SUCCESS) {
  49421. ma_vfs_or_default_close(pVFS, file);
  49422. return result;
  49423. }
  49424. if (info.sizeInBytes > MA_SIZE_MAX) {
  49425. ma_vfs_or_default_close(pVFS, file);
  49426. return MA_TOO_BIG;
  49427. }
  49428. pData = ma_malloc((size_t)info.sizeInBytes, pAllocationCallbacks); /* Safe cast. */
  49429. if (pData == NULL) {
  49430. ma_vfs_or_default_close(pVFS, file);
  49431. return result;
  49432. }
  49433. result = ma_vfs_or_default_read(pVFS, file, pData, (size_t)info.sizeInBytes, &bytesRead); /* Safe cast. */
  49434. ma_vfs_or_default_close(pVFS, file);
  49435. if (result != MA_SUCCESS) {
  49436. ma_free(pData, pAllocationCallbacks);
  49437. return result;
  49438. }
  49439. if (pSize != NULL) {
  49440. *pSize = bytesRead;
  49441. }
  49442. MA_ASSERT(ppData != NULL);
  49443. *ppData = pData;
  49444. return MA_SUCCESS;
  49445. }
  49446. 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)
  49447. {
  49448. return ma_vfs_open_and_read_file_ex(pVFS, pFilePath, NULL, ppData, pSize, pAllocationCallbacks);
  49449. }
  49450. 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)
  49451. {
  49452. return ma_vfs_open_and_read_file_ex(pVFS, NULL, pFilePath, ppData, pSize, pAllocationCallbacks);
  49453. }
  49454. /**************************************************************************************************************************************************************
  49455. Decoding and Encoding Headers. These are auto-generated from a tool.
  49456. **************************************************************************************************************************************************************/
  49457. #if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
  49458. /* dr_wav_h begin */
  49459. #ifndef ma_dr_wav_h
  49460. #define ma_dr_wav_h
  49461. #ifdef __cplusplus
  49462. extern "C" {
  49463. #endif
  49464. #define MA_DR_WAV_STRINGIFY(x) #x
  49465. #define MA_DR_WAV_XSTRINGIFY(x) MA_DR_WAV_STRINGIFY(x)
  49466. #define MA_DR_WAV_VERSION_MAJOR 0
  49467. #define MA_DR_WAV_VERSION_MINOR 13
  49468. #define MA_DR_WAV_VERSION_REVISION 13
  49469. #define MA_DR_WAV_VERSION_STRING MA_DR_WAV_XSTRINGIFY(MA_DR_WAV_VERSION_MAJOR) "." MA_DR_WAV_XSTRINGIFY(MA_DR_WAV_VERSION_MINOR) "." MA_DR_WAV_XSTRINGIFY(MA_DR_WAV_VERSION_REVISION)
  49470. #include <stddef.h>
  49471. #define MA_DR_WAVE_FORMAT_PCM 0x1
  49472. #define MA_DR_WAVE_FORMAT_ADPCM 0x2
  49473. #define MA_DR_WAVE_FORMAT_IEEE_FLOAT 0x3
  49474. #define MA_DR_WAVE_FORMAT_ALAW 0x6
  49475. #define MA_DR_WAVE_FORMAT_MULAW 0x7
  49476. #define MA_DR_WAVE_FORMAT_DVI_ADPCM 0x11
  49477. #define MA_DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE
  49478. #define MA_DR_WAV_SEQUENTIAL 0x00000001
  49479. #define MA_DR_WAV_WITH_METADATA 0x00000002
  49480. MA_API void ma_dr_wav_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
  49481. MA_API const char* ma_dr_wav_version_string(void);
  49482. typedef enum
  49483. {
  49484. ma_dr_wav_seek_origin_start,
  49485. ma_dr_wav_seek_origin_current
  49486. } ma_dr_wav_seek_origin;
  49487. typedef enum
  49488. {
  49489. ma_dr_wav_container_riff,
  49490. ma_dr_wav_container_rifx,
  49491. ma_dr_wav_container_w64,
  49492. ma_dr_wav_container_rf64,
  49493. ma_dr_wav_container_aiff
  49494. } ma_dr_wav_container;
  49495. typedef struct
  49496. {
  49497. union
  49498. {
  49499. ma_uint8 fourcc[4];
  49500. ma_uint8 guid[16];
  49501. } id;
  49502. ma_uint64 sizeInBytes;
  49503. unsigned int paddingSize;
  49504. } ma_dr_wav_chunk_header;
  49505. typedef struct
  49506. {
  49507. ma_uint16 formatTag;
  49508. ma_uint16 channels;
  49509. ma_uint32 sampleRate;
  49510. ma_uint32 avgBytesPerSec;
  49511. ma_uint16 blockAlign;
  49512. ma_uint16 bitsPerSample;
  49513. ma_uint16 extendedSize;
  49514. ma_uint16 validBitsPerSample;
  49515. ma_uint32 channelMask;
  49516. ma_uint8 subFormat[16];
  49517. } ma_dr_wav_fmt;
  49518. MA_API ma_uint16 ma_dr_wav_fmt_get_format(const ma_dr_wav_fmt* pFMT);
  49519. typedef size_t (* ma_dr_wav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  49520. typedef size_t (* ma_dr_wav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite);
  49521. typedef ma_bool32 (* ma_dr_wav_seek_proc)(void* pUserData, int offset, ma_dr_wav_seek_origin origin);
  49522. typedef ma_uint64 (* ma_dr_wav_chunk_proc)(void* pChunkUserData, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pReadSeekUserData, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_container container, const ma_dr_wav_fmt* pFMT);
  49523. typedef struct
  49524. {
  49525. const ma_uint8* data;
  49526. size_t dataSize;
  49527. size_t currentReadPos;
  49528. } ma_dr_wav__memory_stream;
  49529. typedef struct
  49530. {
  49531. void** ppData;
  49532. size_t* pDataSize;
  49533. size_t dataSize;
  49534. size_t dataCapacity;
  49535. size_t currentWritePos;
  49536. } ma_dr_wav__memory_stream_write;
  49537. typedef struct
  49538. {
  49539. ma_dr_wav_container container;
  49540. ma_uint32 format;
  49541. ma_uint32 channels;
  49542. ma_uint32 sampleRate;
  49543. ma_uint32 bitsPerSample;
  49544. } ma_dr_wav_data_format;
  49545. typedef enum
  49546. {
  49547. ma_dr_wav_metadata_type_none = 0,
  49548. ma_dr_wav_metadata_type_unknown = 1 << 0,
  49549. ma_dr_wav_metadata_type_smpl = 1 << 1,
  49550. ma_dr_wav_metadata_type_inst = 1 << 2,
  49551. ma_dr_wav_metadata_type_cue = 1 << 3,
  49552. ma_dr_wav_metadata_type_acid = 1 << 4,
  49553. ma_dr_wav_metadata_type_bext = 1 << 5,
  49554. ma_dr_wav_metadata_type_list_label = 1 << 6,
  49555. ma_dr_wav_metadata_type_list_note = 1 << 7,
  49556. ma_dr_wav_metadata_type_list_labelled_cue_region = 1 << 8,
  49557. ma_dr_wav_metadata_type_list_info_software = 1 << 9,
  49558. ma_dr_wav_metadata_type_list_info_copyright = 1 << 10,
  49559. ma_dr_wav_metadata_type_list_info_title = 1 << 11,
  49560. ma_dr_wav_metadata_type_list_info_artist = 1 << 12,
  49561. ma_dr_wav_metadata_type_list_info_comment = 1 << 13,
  49562. ma_dr_wav_metadata_type_list_info_date = 1 << 14,
  49563. ma_dr_wav_metadata_type_list_info_genre = 1 << 15,
  49564. ma_dr_wav_metadata_type_list_info_album = 1 << 16,
  49565. ma_dr_wav_metadata_type_list_info_tracknumber = 1 << 17,
  49566. ma_dr_wav_metadata_type_list_all_info_strings = ma_dr_wav_metadata_type_list_info_software
  49567. | ma_dr_wav_metadata_type_list_info_copyright
  49568. | ma_dr_wav_metadata_type_list_info_title
  49569. | ma_dr_wav_metadata_type_list_info_artist
  49570. | ma_dr_wav_metadata_type_list_info_comment
  49571. | ma_dr_wav_metadata_type_list_info_date
  49572. | ma_dr_wav_metadata_type_list_info_genre
  49573. | ma_dr_wav_metadata_type_list_info_album
  49574. | ma_dr_wav_metadata_type_list_info_tracknumber,
  49575. ma_dr_wav_metadata_type_list_all_adtl = ma_dr_wav_metadata_type_list_label
  49576. | ma_dr_wav_metadata_type_list_note
  49577. | ma_dr_wav_metadata_type_list_labelled_cue_region,
  49578. ma_dr_wav_metadata_type_all = -2,
  49579. ma_dr_wav_metadata_type_all_including_unknown = -1
  49580. } ma_dr_wav_metadata_type;
  49581. typedef enum
  49582. {
  49583. ma_dr_wav_smpl_loop_type_forward = 0,
  49584. ma_dr_wav_smpl_loop_type_pingpong = 1,
  49585. ma_dr_wav_smpl_loop_type_backward = 2
  49586. } ma_dr_wav_smpl_loop_type;
  49587. typedef struct
  49588. {
  49589. ma_uint32 cuePointId;
  49590. ma_uint32 type;
  49591. ma_uint32 firstSampleByteOffset;
  49592. ma_uint32 lastSampleByteOffset;
  49593. ma_uint32 sampleFraction;
  49594. ma_uint32 playCount;
  49595. } ma_dr_wav_smpl_loop;
  49596. typedef struct
  49597. {
  49598. ma_uint32 manufacturerId;
  49599. ma_uint32 productId;
  49600. ma_uint32 samplePeriodNanoseconds;
  49601. ma_uint32 midiUnityNote;
  49602. ma_uint32 midiPitchFraction;
  49603. ma_uint32 smpteFormat;
  49604. ma_uint32 smpteOffset;
  49605. ma_uint32 sampleLoopCount;
  49606. ma_uint32 samplerSpecificDataSizeInBytes;
  49607. ma_dr_wav_smpl_loop* pLoops;
  49608. ma_uint8* pSamplerSpecificData;
  49609. } ma_dr_wav_smpl;
  49610. typedef struct
  49611. {
  49612. ma_int8 midiUnityNote;
  49613. ma_int8 fineTuneCents;
  49614. ma_int8 gainDecibels;
  49615. ma_int8 lowNote;
  49616. ma_int8 highNote;
  49617. ma_int8 lowVelocity;
  49618. ma_int8 highVelocity;
  49619. } ma_dr_wav_inst;
  49620. typedef struct
  49621. {
  49622. ma_uint32 id;
  49623. ma_uint32 playOrderPosition;
  49624. ma_uint8 dataChunkId[4];
  49625. ma_uint32 chunkStart;
  49626. ma_uint32 blockStart;
  49627. ma_uint32 sampleByteOffset;
  49628. } ma_dr_wav_cue_point;
  49629. typedef struct
  49630. {
  49631. ma_uint32 cuePointCount;
  49632. ma_dr_wav_cue_point *pCuePoints;
  49633. } ma_dr_wav_cue;
  49634. typedef enum
  49635. {
  49636. ma_dr_wav_acid_flag_one_shot = 1,
  49637. ma_dr_wav_acid_flag_root_note_set = 2,
  49638. ma_dr_wav_acid_flag_stretch = 4,
  49639. ma_dr_wav_acid_flag_disk_based = 8,
  49640. ma_dr_wav_acid_flag_acidizer = 16
  49641. } ma_dr_wav_acid_flag;
  49642. typedef struct
  49643. {
  49644. ma_uint32 flags;
  49645. ma_uint16 midiUnityNote;
  49646. ma_uint16 reserved1;
  49647. float reserved2;
  49648. ma_uint32 numBeats;
  49649. ma_uint16 meterDenominator;
  49650. ma_uint16 meterNumerator;
  49651. float tempo;
  49652. } ma_dr_wav_acid;
  49653. typedef struct
  49654. {
  49655. ma_uint32 cuePointId;
  49656. ma_uint32 stringLength;
  49657. char* pString;
  49658. } ma_dr_wav_list_label_or_note;
  49659. typedef struct
  49660. {
  49661. char* pDescription;
  49662. char* pOriginatorName;
  49663. char* pOriginatorReference;
  49664. char pOriginationDate[10];
  49665. char pOriginationTime[8];
  49666. ma_uint64 timeReference;
  49667. ma_uint16 version;
  49668. char* pCodingHistory;
  49669. ma_uint32 codingHistorySize;
  49670. ma_uint8* pUMID;
  49671. ma_uint16 loudnessValue;
  49672. ma_uint16 loudnessRange;
  49673. ma_uint16 maxTruePeakLevel;
  49674. ma_uint16 maxMomentaryLoudness;
  49675. ma_uint16 maxShortTermLoudness;
  49676. } ma_dr_wav_bext;
  49677. typedef struct
  49678. {
  49679. ma_uint32 stringLength;
  49680. char* pString;
  49681. } ma_dr_wav_list_info_text;
  49682. typedef struct
  49683. {
  49684. ma_uint32 cuePointId;
  49685. ma_uint32 sampleLength;
  49686. ma_uint8 purposeId[4];
  49687. ma_uint16 country;
  49688. ma_uint16 language;
  49689. ma_uint16 dialect;
  49690. ma_uint16 codePage;
  49691. ma_uint32 stringLength;
  49692. char* pString;
  49693. } ma_dr_wav_list_labelled_cue_region;
  49694. typedef enum
  49695. {
  49696. ma_dr_wav_metadata_location_invalid,
  49697. ma_dr_wav_metadata_location_top_level,
  49698. ma_dr_wav_metadata_location_inside_info_list,
  49699. ma_dr_wav_metadata_location_inside_adtl_list
  49700. } ma_dr_wav_metadata_location;
  49701. typedef struct
  49702. {
  49703. ma_uint8 id[4];
  49704. ma_dr_wav_metadata_location chunkLocation;
  49705. ma_uint32 dataSizeInBytes;
  49706. ma_uint8* pData;
  49707. } ma_dr_wav_unknown_metadata;
  49708. typedef struct
  49709. {
  49710. ma_dr_wav_metadata_type type;
  49711. union
  49712. {
  49713. ma_dr_wav_cue cue;
  49714. ma_dr_wav_smpl smpl;
  49715. ma_dr_wav_acid acid;
  49716. ma_dr_wav_inst inst;
  49717. ma_dr_wav_bext bext;
  49718. ma_dr_wav_list_label_or_note labelOrNote;
  49719. ma_dr_wav_list_labelled_cue_region labelledCueRegion;
  49720. ma_dr_wav_list_info_text infoText;
  49721. ma_dr_wav_unknown_metadata unknown;
  49722. } data;
  49723. } ma_dr_wav_metadata;
  49724. typedef struct
  49725. {
  49726. ma_dr_wav_read_proc onRead;
  49727. ma_dr_wav_write_proc onWrite;
  49728. ma_dr_wav_seek_proc onSeek;
  49729. void* pUserData;
  49730. ma_allocation_callbacks allocationCallbacks;
  49731. ma_dr_wav_container container;
  49732. ma_dr_wav_fmt fmt;
  49733. ma_uint32 sampleRate;
  49734. ma_uint16 channels;
  49735. ma_uint16 bitsPerSample;
  49736. ma_uint16 translatedFormatTag;
  49737. ma_uint64 totalPCMFrameCount;
  49738. ma_uint64 dataChunkDataSize;
  49739. ma_uint64 dataChunkDataPos;
  49740. ma_uint64 bytesRemaining;
  49741. ma_uint64 readCursorInPCMFrames;
  49742. ma_uint64 dataChunkDataSizeTargetWrite;
  49743. ma_bool32 isSequentialWrite;
  49744. ma_dr_wav_metadata* pMetadata;
  49745. ma_uint32 metadataCount;
  49746. ma_dr_wav__memory_stream memoryStream;
  49747. ma_dr_wav__memory_stream_write memoryStreamWrite;
  49748. struct
  49749. {
  49750. ma_uint32 bytesRemainingInBlock;
  49751. ma_uint16 predictor[2];
  49752. ma_int32 delta[2];
  49753. ma_int32 cachedFrames[4];
  49754. ma_uint32 cachedFrameCount;
  49755. ma_int32 prevFrames[2][2];
  49756. } msadpcm;
  49757. struct
  49758. {
  49759. ma_uint32 bytesRemainingInBlock;
  49760. ma_int32 predictor[2];
  49761. ma_int32 stepIndex[2];
  49762. ma_int32 cachedFrames[16];
  49763. ma_uint32 cachedFrameCount;
  49764. } ima;
  49765. struct
  49766. {
  49767. ma_bool8 isLE;
  49768. ma_bool8 isUnsigned;
  49769. } aiff;
  49770. } ma_dr_wav;
  49771. MA_API ma_bool32 ma_dr_wav_init(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  49772. MA_API ma_bool32 ma_dr_wav_init_ex(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, ma_dr_wav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49773. MA_API ma_bool32 ma_dr_wav_init_with_metadata(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49774. MA_API ma_bool32 ma_dr_wav_init_write(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  49775. MA_API ma_bool32 ma_dr_wav_init_write_sequential(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  49776. MA_API ma_bool32 ma_dr_wav_init_write_sequential_pcm_frames(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  49777. MA_API ma_bool32 ma_dr_wav_init_write_with_metadata(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount);
  49778. MA_API ma_uint64 ma_dr_wav_target_write_size_bytes(const ma_dr_wav_data_format* pFormat, ma_uint64 totalFrameCount, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount);
  49779. MA_API ma_dr_wav_metadata* ma_dr_wav_take_ownership_of_metadata(ma_dr_wav* pWav);
  49780. MA_API ma_result ma_dr_wav_uninit(ma_dr_wav* pWav);
  49781. MA_API size_t ma_dr_wav_read_raw(ma_dr_wav* pWav, size_t bytesToRead, void* pBufferOut);
  49782. MA_API ma_uint64 ma_dr_wav_read_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut);
  49783. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut);
  49784. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut);
  49785. MA_API ma_bool32 ma_dr_wav_seek_to_pcm_frame(ma_dr_wav* pWav, ma_uint64 targetFrameIndex);
  49786. MA_API ma_result ma_dr_wav_get_cursor_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pCursor);
  49787. MA_API ma_result ma_dr_wav_get_length_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pLength);
  49788. MA_API size_t ma_dr_wav_write_raw(ma_dr_wav* pWav, size_t bytesToWrite, const void* pData);
  49789. MA_API ma_uint64 ma_dr_wav_write_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData);
  49790. MA_API ma_uint64 ma_dr_wav_write_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData);
  49791. MA_API ma_uint64 ma_dr_wav_write_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData);
  49792. #ifndef MA_DR_WAV_NO_CONVERSION_API
  49793. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut);
  49794. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut);
  49795. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut);
  49796. MA_API void ma_dr_wav_u8_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount);
  49797. MA_API void ma_dr_wav_s24_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount);
  49798. MA_API void ma_dr_wav_s32_to_s16(ma_int16* pOut, const ma_int32* pIn, size_t sampleCount);
  49799. MA_API void ma_dr_wav_f32_to_s16(ma_int16* pOut, const float* pIn, size_t sampleCount);
  49800. MA_API void ma_dr_wav_f64_to_s16(ma_int16* pOut, const double* pIn, size_t sampleCount);
  49801. MA_API void ma_dr_wav_alaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount);
  49802. MA_API void ma_dr_wav_mulaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount);
  49803. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut);
  49804. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32le(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut);
  49805. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32be(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut);
  49806. MA_API void ma_dr_wav_u8_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount);
  49807. MA_API void ma_dr_wav_s16_to_f32(float* pOut, const ma_int16* pIn, size_t sampleCount);
  49808. MA_API void ma_dr_wav_s24_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount);
  49809. MA_API void ma_dr_wav_s32_to_f32(float* pOut, const ma_int32* pIn, size_t sampleCount);
  49810. MA_API void ma_dr_wav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount);
  49811. MA_API void ma_dr_wav_alaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount);
  49812. MA_API void ma_dr_wav_mulaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount);
  49813. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut);
  49814. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut);
  49815. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut);
  49816. MA_API void ma_dr_wav_u8_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount);
  49817. MA_API void ma_dr_wav_s16_to_s32(ma_int32* pOut, const ma_int16* pIn, size_t sampleCount);
  49818. MA_API void ma_dr_wav_s24_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount);
  49819. MA_API void ma_dr_wav_f32_to_s32(ma_int32* pOut, const float* pIn, size_t sampleCount);
  49820. MA_API void ma_dr_wav_f64_to_s32(ma_int32* pOut, const double* pIn, size_t sampleCount);
  49821. MA_API void ma_dr_wav_alaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount);
  49822. MA_API void ma_dr_wav_mulaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount);
  49823. #endif
  49824. #ifndef MA_DR_WAV_NO_STDIO
  49825. MA_API ma_bool32 ma_dr_wav_init_file(ma_dr_wav* pWav, const char* filename, const ma_allocation_callbacks* pAllocationCallbacks);
  49826. MA_API ma_bool32 ma_dr_wav_init_file_ex(ma_dr_wav* pWav, const char* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49827. MA_API ma_bool32 ma_dr_wav_init_file_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_allocation_callbacks* pAllocationCallbacks);
  49828. MA_API ma_bool32 ma_dr_wav_init_file_ex_w(ma_dr_wav* pWav, const wchar_t* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49829. MA_API ma_bool32 ma_dr_wav_init_file_with_metadata(ma_dr_wav* pWav, const char* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49830. MA_API ma_bool32 ma_dr_wav_init_file_with_metadata_w(ma_dr_wav* pWav, const wchar_t* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49831. MA_API ma_bool32 ma_dr_wav_init_file_write(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks);
  49832. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks);
  49833. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  49834. MA_API ma_bool32 ma_dr_wav_init_file_write_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks);
  49835. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks);
  49836. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  49837. #endif
  49838. MA_API ma_bool32 ma_dr_wav_init_memory(ma_dr_wav* pWav, const void* data, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks);
  49839. MA_API ma_bool32 ma_dr_wav_init_memory_ex(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49840. MA_API ma_bool32 ma_dr_wav_init_memory_with_metadata(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks);
  49841. MA_API ma_bool32 ma_dr_wav_init_memory_write(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks);
  49842. MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks);
  49843. MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential_pcm_frames(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  49844. #ifndef MA_DR_WAV_NO_CONVERSION_API
  49845. MA_API ma_int16* ma_dr_wav_open_and_read_pcm_frames_s16(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49846. MA_API float* ma_dr_wav_open_and_read_pcm_frames_f32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49847. MA_API ma_int32* ma_dr_wav_open_and_read_pcm_frames_s32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49848. #ifndef MA_DR_WAV_NO_STDIO
  49849. MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49850. MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49851. MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49852. MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49853. MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49854. MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49855. #endif
  49856. MA_API ma_int16* ma_dr_wav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49857. MA_API float* ma_dr_wav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49858. MA_API ma_int32* ma_dr_wav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks);
  49859. #endif
  49860. MA_API void ma_dr_wav_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  49861. MA_API ma_uint16 ma_dr_wav_bytes_to_u16(const ma_uint8* data);
  49862. MA_API ma_int16 ma_dr_wav_bytes_to_s16(const ma_uint8* data);
  49863. MA_API ma_uint32 ma_dr_wav_bytes_to_u32(const ma_uint8* data);
  49864. MA_API ma_int32 ma_dr_wav_bytes_to_s32(const ma_uint8* data);
  49865. MA_API ma_uint64 ma_dr_wav_bytes_to_u64(const ma_uint8* data);
  49866. MA_API ma_int64 ma_dr_wav_bytes_to_s64(const ma_uint8* data);
  49867. MA_API float ma_dr_wav_bytes_to_f32(const ma_uint8* data);
  49868. MA_API ma_bool32 ma_dr_wav_guid_equal(const ma_uint8 a[16], const ma_uint8 b[16]);
  49869. MA_API ma_bool32 ma_dr_wav_fourcc_equal(const ma_uint8* a, const char* b);
  49870. #ifdef __cplusplus
  49871. }
  49872. #endif
  49873. #endif
  49874. /* dr_wav_h end */
  49875. #endif /* MA_NO_WAV */
  49876. #if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
  49877. /* dr_flac_h begin */
  49878. #ifndef ma_dr_flac_h
  49879. #define ma_dr_flac_h
  49880. #ifdef __cplusplus
  49881. extern "C" {
  49882. #endif
  49883. #define MA_DR_FLAC_STRINGIFY(x) #x
  49884. #define MA_DR_FLAC_XSTRINGIFY(x) MA_DR_FLAC_STRINGIFY(x)
  49885. #define MA_DR_FLAC_VERSION_MAJOR 0
  49886. #define MA_DR_FLAC_VERSION_MINOR 12
  49887. #define MA_DR_FLAC_VERSION_REVISION 42
  49888. #define MA_DR_FLAC_VERSION_STRING MA_DR_FLAC_XSTRINGIFY(MA_DR_FLAC_VERSION_MAJOR) "." MA_DR_FLAC_XSTRINGIFY(MA_DR_FLAC_VERSION_MINOR) "." MA_DR_FLAC_XSTRINGIFY(MA_DR_FLAC_VERSION_REVISION)
  49889. #include <stddef.h>
  49890. #if defined(_MSC_VER) && _MSC_VER >= 1700
  49891. #define MA_DR_FLAC_DEPRECATED __declspec(deprecated)
  49892. #elif (defined(__GNUC__) && __GNUC__ >= 4)
  49893. #define MA_DR_FLAC_DEPRECATED __attribute__((deprecated))
  49894. #elif defined(__has_feature)
  49895. #if __has_feature(attribute_deprecated)
  49896. #define MA_DR_FLAC_DEPRECATED __attribute__((deprecated))
  49897. #else
  49898. #define MA_DR_FLAC_DEPRECATED
  49899. #endif
  49900. #else
  49901. #define MA_DR_FLAC_DEPRECATED
  49902. #endif
  49903. MA_API void ma_dr_flac_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
  49904. MA_API const char* ma_dr_flac_version_string(void);
  49905. #ifndef MA_DR_FLAC_BUFFER_SIZE
  49906. #define MA_DR_FLAC_BUFFER_SIZE 4096
  49907. #endif
  49908. #ifdef MA_64BIT
  49909. typedef ma_uint64 ma_dr_flac_cache_t;
  49910. #else
  49911. typedef ma_uint32 ma_dr_flac_cache_t;
  49912. #endif
  49913. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
  49914. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_PADDING 1
  49915. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_APPLICATION 2
  49916. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
  49917. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
  49918. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_CUESHEET 5
  49919. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_PICTURE 6
  49920. #define MA_DR_FLAC_METADATA_BLOCK_TYPE_INVALID 127
  49921. #define MA_DR_FLAC_PICTURE_TYPE_OTHER 0
  49922. #define MA_DR_FLAC_PICTURE_TYPE_FILE_ICON 1
  49923. #define MA_DR_FLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
  49924. #define MA_DR_FLAC_PICTURE_TYPE_COVER_FRONT 3
  49925. #define MA_DR_FLAC_PICTURE_TYPE_COVER_BACK 4
  49926. #define MA_DR_FLAC_PICTURE_TYPE_LEAFLET_PAGE 5
  49927. #define MA_DR_FLAC_PICTURE_TYPE_MEDIA 6
  49928. #define MA_DR_FLAC_PICTURE_TYPE_LEAD_ARTIST 7
  49929. #define MA_DR_FLAC_PICTURE_TYPE_ARTIST 8
  49930. #define MA_DR_FLAC_PICTURE_TYPE_CONDUCTOR 9
  49931. #define MA_DR_FLAC_PICTURE_TYPE_BAND 10
  49932. #define MA_DR_FLAC_PICTURE_TYPE_COMPOSER 11
  49933. #define MA_DR_FLAC_PICTURE_TYPE_LYRICIST 12
  49934. #define MA_DR_FLAC_PICTURE_TYPE_RECORDING_LOCATION 13
  49935. #define MA_DR_FLAC_PICTURE_TYPE_DURING_RECORDING 14
  49936. #define MA_DR_FLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
  49937. #define MA_DR_FLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
  49938. #define MA_DR_FLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
  49939. #define MA_DR_FLAC_PICTURE_TYPE_ILLUSTRATION 18
  49940. #define MA_DR_FLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
  49941. #define MA_DR_FLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
  49942. typedef enum
  49943. {
  49944. ma_dr_flac_container_native,
  49945. ma_dr_flac_container_ogg,
  49946. ma_dr_flac_container_unknown
  49947. } ma_dr_flac_container;
  49948. typedef enum
  49949. {
  49950. ma_dr_flac_seek_origin_start,
  49951. ma_dr_flac_seek_origin_current
  49952. } ma_dr_flac_seek_origin;
  49953. typedef struct
  49954. {
  49955. ma_uint64 firstPCMFrame;
  49956. ma_uint64 flacFrameOffset;
  49957. ma_uint16 pcmFrameCount;
  49958. } ma_dr_flac_seekpoint;
  49959. typedef struct
  49960. {
  49961. ma_uint16 minBlockSizeInPCMFrames;
  49962. ma_uint16 maxBlockSizeInPCMFrames;
  49963. ma_uint32 minFrameSizeInPCMFrames;
  49964. ma_uint32 maxFrameSizeInPCMFrames;
  49965. ma_uint32 sampleRate;
  49966. ma_uint8 channels;
  49967. ma_uint8 bitsPerSample;
  49968. ma_uint64 totalPCMFrameCount;
  49969. ma_uint8 md5[16];
  49970. } ma_dr_flac_streaminfo;
  49971. typedef struct
  49972. {
  49973. ma_uint32 type;
  49974. const void* pRawData;
  49975. ma_uint32 rawDataSize;
  49976. union
  49977. {
  49978. ma_dr_flac_streaminfo streaminfo;
  49979. struct
  49980. {
  49981. int unused;
  49982. } padding;
  49983. struct
  49984. {
  49985. ma_uint32 id;
  49986. const void* pData;
  49987. ma_uint32 dataSize;
  49988. } application;
  49989. struct
  49990. {
  49991. ma_uint32 seekpointCount;
  49992. const ma_dr_flac_seekpoint* pSeekpoints;
  49993. } seektable;
  49994. struct
  49995. {
  49996. ma_uint32 vendorLength;
  49997. const char* vendor;
  49998. ma_uint32 commentCount;
  49999. const void* pComments;
  50000. } vorbis_comment;
  50001. struct
  50002. {
  50003. char catalog[128];
  50004. ma_uint64 leadInSampleCount;
  50005. ma_bool32 isCD;
  50006. ma_uint8 trackCount;
  50007. const void* pTrackData;
  50008. } cuesheet;
  50009. struct
  50010. {
  50011. ma_uint32 type;
  50012. ma_uint32 mimeLength;
  50013. const char* mime;
  50014. ma_uint32 descriptionLength;
  50015. const char* description;
  50016. ma_uint32 width;
  50017. ma_uint32 height;
  50018. ma_uint32 colorDepth;
  50019. ma_uint32 indexColorCount;
  50020. ma_uint32 pictureDataSize;
  50021. const ma_uint8* pPictureData;
  50022. } picture;
  50023. } data;
  50024. } ma_dr_flac_metadata;
  50025. typedef size_t (* ma_dr_flac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  50026. typedef ma_bool32 (* ma_dr_flac_seek_proc)(void* pUserData, int offset, ma_dr_flac_seek_origin origin);
  50027. typedef void (* ma_dr_flac_meta_proc)(void* pUserData, ma_dr_flac_metadata* pMetadata);
  50028. typedef struct
  50029. {
  50030. const ma_uint8* data;
  50031. size_t dataSize;
  50032. size_t currentReadPos;
  50033. } ma_dr_flac__memory_stream;
  50034. typedef struct
  50035. {
  50036. ma_dr_flac_read_proc onRead;
  50037. ma_dr_flac_seek_proc onSeek;
  50038. void* pUserData;
  50039. size_t unalignedByteCount;
  50040. ma_dr_flac_cache_t unalignedCache;
  50041. ma_uint32 nextL2Line;
  50042. ma_uint32 consumedBits;
  50043. ma_dr_flac_cache_t cacheL2[MA_DR_FLAC_BUFFER_SIZE/sizeof(ma_dr_flac_cache_t)];
  50044. ma_dr_flac_cache_t cache;
  50045. ma_uint16 crc16;
  50046. ma_dr_flac_cache_t crc16Cache;
  50047. ma_uint32 crc16CacheIgnoredBytes;
  50048. } ma_dr_flac_bs;
  50049. typedef struct
  50050. {
  50051. ma_uint8 subframeType;
  50052. ma_uint8 wastedBitsPerSample;
  50053. ma_uint8 lpcOrder;
  50054. ma_int32* pSamplesS32;
  50055. } ma_dr_flac_subframe;
  50056. typedef struct
  50057. {
  50058. ma_uint64 pcmFrameNumber;
  50059. ma_uint32 flacFrameNumber;
  50060. ma_uint32 sampleRate;
  50061. ma_uint16 blockSizeInPCMFrames;
  50062. ma_uint8 channelAssignment;
  50063. ma_uint8 bitsPerSample;
  50064. ma_uint8 crc8;
  50065. } ma_dr_flac_frame_header;
  50066. typedef struct
  50067. {
  50068. ma_dr_flac_frame_header header;
  50069. ma_uint32 pcmFramesRemaining;
  50070. ma_dr_flac_subframe subframes[8];
  50071. } ma_dr_flac_frame;
  50072. typedef struct
  50073. {
  50074. ma_dr_flac_meta_proc onMeta;
  50075. void* pUserDataMD;
  50076. ma_allocation_callbacks allocationCallbacks;
  50077. ma_uint32 sampleRate;
  50078. ma_uint8 channels;
  50079. ma_uint8 bitsPerSample;
  50080. ma_uint16 maxBlockSizeInPCMFrames;
  50081. ma_uint64 totalPCMFrameCount;
  50082. ma_dr_flac_container container;
  50083. ma_uint32 seekpointCount;
  50084. ma_dr_flac_frame currentFLACFrame;
  50085. ma_uint64 currentPCMFrame;
  50086. ma_uint64 firstFLACFramePosInBytes;
  50087. ma_dr_flac__memory_stream memoryStream;
  50088. ma_int32* pDecodedSamples;
  50089. ma_dr_flac_seekpoint* pSeekpoints;
  50090. void* _oggbs;
  50091. ma_bool32 _noSeekTableSeek : 1;
  50092. ma_bool32 _noBinarySearchSeek : 1;
  50093. ma_bool32 _noBruteForceSeek : 1;
  50094. ma_dr_flac_bs bs;
  50095. ma_uint8 pExtraData[1];
  50096. } ma_dr_flac;
  50097. MA_API ma_dr_flac* ma_dr_flac_open(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50098. MA_API ma_dr_flac* ma_dr_flac_open_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50099. MA_API ma_dr_flac* ma_dr_flac_open_with_metadata(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50100. MA_API ma_dr_flac* ma_dr_flac_open_with_metadata_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50101. MA_API void ma_dr_flac_close(ma_dr_flac* pFlac);
  50102. MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s32(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int32* pBufferOut);
  50103. MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s16(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int16* pBufferOut);
  50104. MA_API ma_uint64 ma_dr_flac_read_pcm_frames_f32(ma_dr_flac* pFlac, ma_uint64 framesToRead, float* pBufferOut);
  50105. MA_API ma_bool32 ma_dr_flac_seek_to_pcm_frame(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex);
  50106. #ifndef MA_DR_FLAC_NO_STDIO
  50107. MA_API ma_dr_flac* ma_dr_flac_open_file(const char* pFileName, const ma_allocation_callbacks* pAllocationCallbacks);
  50108. MA_API ma_dr_flac* ma_dr_flac_open_file_w(const wchar_t* pFileName, const ma_allocation_callbacks* pAllocationCallbacks);
  50109. MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata(const char* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50110. MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata_w(const wchar_t* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50111. #endif
  50112. MA_API ma_dr_flac* ma_dr_flac_open_memory(const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks);
  50113. MA_API ma_dr_flac* ma_dr_flac_open_memory_with_metadata(const void* pData, size_t dataSize, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50114. MA_API ma_int32* ma_dr_flac_open_and_read_pcm_frames_s32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50115. MA_API ma_int16* ma_dr_flac_open_and_read_pcm_frames_s16(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50116. MA_API float* ma_dr_flac_open_and_read_pcm_frames_f32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50117. #ifndef MA_DR_FLAC_NO_STDIO
  50118. MA_API ma_int32* ma_dr_flac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50119. MA_API ma_int16* ma_dr_flac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50120. MA_API float* ma_dr_flac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50121. #endif
  50122. MA_API ma_int32* ma_dr_flac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50123. MA_API ma_int16* ma_dr_flac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50124. MA_API float* ma_dr_flac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50125. MA_API void ma_dr_flac_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  50126. typedef struct
  50127. {
  50128. ma_uint32 countRemaining;
  50129. const char* pRunningData;
  50130. } ma_dr_flac_vorbis_comment_iterator;
  50131. MA_API void ma_dr_flac_init_vorbis_comment_iterator(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32 commentCount, const void* pComments);
  50132. MA_API const char* ma_dr_flac_next_vorbis_comment(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32* pCommentLengthOut);
  50133. typedef struct
  50134. {
  50135. ma_uint32 countRemaining;
  50136. const char* pRunningData;
  50137. } ma_dr_flac_cuesheet_track_iterator;
  50138. typedef struct
  50139. {
  50140. ma_uint64 offset;
  50141. ma_uint8 index;
  50142. ma_uint8 reserved[3];
  50143. } ma_dr_flac_cuesheet_track_index;
  50144. typedef struct
  50145. {
  50146. ma_uint64 offset;
  50147. ma_uint8 trackNumber;
  50148. char ISRC[12];
  50149. ma_bool8 isAudio;
  50150. ma_bool8 preEmphasis;
  50151. ma_uint8 indexCount;
  50152. const ma_dr_flac_cuesheet_track_index* pIndexPoints;
  50153. } ma_dr_flac_cuesheet_track;
  50154. MA_API void ma_dr_flac_init_cuesheet_track_iterator(ma_dr_flac_cuesheet_track_iterator* pIter, ma_uint32 trackCount, const void* pTrackData);
  50155. MA_API ma_bool32 ma_dr_flac_next_cuesheet_track(ma_dr_flac_cuesheet_track_iterator* pIter, ma_dr_flac_cuesheet_track* pCuesheetTrack);
  50156. #ifdef __cplusplus
  50157. }
  50158. #endif
  50159. #endif
  50160. /* dr_flac_h end */
  50161. #endif /* MA_NO_FLAC */
  50162. #if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
  50163. /* dr_mp3_h begin */
  50164. #ifndef ma_dr_mp3_h
  50165. #define ma_dr_mp3_h
  50166. #ifdef __cplusplus
  50167. extern "C" {
  50168. #endif
  50169. #define MA_DR_MP3_STRINGIFY(x) #x
  50170. #define MA_DR_MP3_XSTRINGIFY(x) MA_DR_MP3_STRINGIFY(x)
  50171. #define MA_DR_MP3_VERSION_MAJOR 0
  50172. #define MA_DR_MP3_VERSION_MINOR 6
  50173. #define MA_DR_MP3_VERSION_REVISION 38
  50174. #define MA_DR_MP3_VERSION_STRING MA_DR_MP3_XSTRINGIFY(MA_DR_MP3_VERSION_MAJOR) "." MA_DR_MP3_XSTRINGIFY(MA_DR_MP3_VERSION_MINOR) "." MA_DR_MP3_XSTRINGIFY(MA_DR_MP3_VERSION_REVISION)
  50175. #include <stddef.h>
  50176. #define MA_DR_MP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152
  50177. #define MA_DR_MP3_MAX_SAMPLES_PER_FRAME (MA_DR_MP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2)
  50178. MA_API void ma_dr_mp3_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
  50179. MA_API const char* ma_dr_mp3_version_string(void);
  50180. typedef struct
  50181. {
  50182. int frame_bytes, channels, hz, layer, bitrate_kbps;
  50183. } ma_dr_mp3dec_frame_info;
  50184. typedef struct
  50185. {
  50186. float mdct_overlap[2][9*32], qmf_state[15*2*32];
  50187. int reserv, free_format_bytes;
  50188. ma_uint8 header[4], reserv_buf[511];
  50189. } ma_dr_mp3dec;
  50190. MA_API void ma_dr_mp3dec_init(ma_dr_mp3dec *dec);
  50191. MA_API int ma_dr_mp3dec_decode_frame(ma_dr_mp3dec *dec, const ma_uint8 *mp3, int mp3_bytes, void *pcm, ma_dr_mp3dec_frame_info *info);
  50192. MA_API void ma_dr_mp3dec_f32_to_s16(const float *in, ma_int16 *out, size_t num_samples);
  50193. typedef enum
  50194. {
  50195. ma_dr_mp3_seek_origin_start,
  50196. ma_dr_mp3_seek_origin_current
  50197. } ma_dr_mp3_seek_origin;
  50198. typedef struct
  50199. {
  50200. ma_uint64 seekPosInBytes;
  50201. ma_uint64 pcmFrameIndex;
  50202. ma_uint16 mp3FramesToDiscard;
  50203. ma_uint16 pcmFramesToDiscard;
  50204. } ma_dr_mp3_seek_point;
  50205. typedef size_t (* ma_dr_mp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  50206. typedef ma_bool32 (* ma_dr_mp3_seek_proc)(void* pUserData, int offset, ma_dr_mp3_seek_origin origin);
  50207. typedef struct
  50208. {
  50209. ma_uint32 channels;
  50210. ma_uint32 sampleRate;
  50211. } ma_dr_mp3_config;
  50212. typedef struct
  50213. {
  50214. ma_dr_mp3dec decoder;
  50215. ma_uint32 channels;
  50216. ma_uint32 sampleRate;
  50217. ma_dr_mp3_read_proc onRead;
  50218. ma_dr_mp3_seek_proc onSeek;
  50219. void* pUserData;
  50220. ma_allocation_callbacks allocationCallbacks;
  50221. ma_uint32 mp3FrameChannels;
  50222. ma_uint32 mp3FrameSampleRate;
  50223. ma_uint32 pcmFramesConsumedInMP3Frame;
  50224. ma_uint32 pcmFramesRemainingInMP3Frame;
  50225. ma_uint8 pcmFrames[sizeof(float)*MA_DR_MP3_MAX_SAMPLES_PER_FRAME];
  50226. ma_uint64 currentPCMFrame;
  50227. ma_uint64 streamCursor;
  50228. ma_dr_mp3_seek_point* pSeekPoints;
  50229. ma_uint32 seekPointCount;
  50230. size_t dataSize;
  50231. size_t dataCapacity;
  50232. size_t dataConsumed;
  50233. ma_uint8* pData;
  50234. ma_bool32 atEnd : 1;
  50235. struct
  50236. {
  50237. const ma_uint8* pData;
  50238. size_t dataSize;
  50239. size_t currentReadPos;
  50240. } memory;
  50241. } ma_dr_mp3;
  50242. MA_API ma_bool32 ma_dr_mp3_init(ma_dr_mp3* pMP3, ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks);
  50243. MA_API ma_bool32 ma_dr_mp3_init_memory(ma_dr_mp3* pMP3, const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks);
  50244. #ifndef MA_DR_MP3_NO_STDIO
  50245. MA_API ma_bool32 ma_dr_mp3_init_file(ma_dr_mp3* pMP3, const char* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks);
  50246. MA_API ma_bool32 ma_dr_mp3_init_file_w(ma_dr_mp3* pMP3, const wchar_t* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks);
  50247. #endif
  50248. MA_API void ma_dr_mp3_uninit(ma_dr_mp3* pMP3);
  50249. MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_f32(ma_dr_mp3* pMP3, ma_uint64 framesToRead, float* pBufferOut);
  50250. MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_s16(ma_dr_mp3* pMP3, ma_uint64 framesToRead, ma_int16* pBufferOut);
  50251. MA_API ma_bool32 ma_dr_mp3_seek_to_pcm_frame(ma_dr_mp3* pMP3, ma_uint64 frameIndex);
  50252. MA_API ma_uint64 ma_dr_mp3_get_pcm_frame_count(ma_dr_mp3* pMP3);
  50253. MA_API ma_uint64 ma_dr_mp3_get_mp3_frame_count(ma_dr_mp3* pMP3);
  50254. MA_API ma_bool32 ma_dr_mp3_get_mp3_and_pcm_frame_count(ma_dr_mp3* pMP3, ma_uint64* pMP3FrameCount, ma_uint64* pPCMFrameCount);
  50255. MA_API ma_bool32 ma_dr_mp3_calculate_seek_points(ma_dr_mp3* pMP3, ma_uint32* pSeekPointCount, ma_dr_mp3_seek_point* pSeekPoints);
  50256. MA_API ma_bool32 ma_dr_mp3_bind_seek_table(ma_dr_mp3* pMP3, ma_uint32 seekPointCount, ma_dr_mp3_seek_point* pSeekPoints);
  50257. MA_API float* ma_dr_mp3_open_and_read_pcm_frames_f32(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50258. MA_API ma_int16* ma_dr_mp3_open_and_read_pcm_frames_s16(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50259. MA_API float* ma_dr_mp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50260. MA_API ma_int16* ma_dr_mp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50261. #ifndef MA_DR_MP3_NO_STDIO
  50262. MA_API float* ma_dr_mp3_open_file_and_read_pcm_frames_f32(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50263. MA_API ma_int16* ma_dr_mp3_open_file_and_read_pcm_frames_s16(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks);
  50264. #endif
  50265. MA_API void* ma_dr_mp3_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  50266. MA_API void ma_dr_mp3_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  50267. #ifdef __cplusplus
  50268. }
  50269. #endif
  50270. #endif
  50271. /* dr_mp3_h end */
  50272. #endif /* MA_NO_MP3 */
  50273. /**************************************************************************************************************************************************************
  50274. Decoding
  50275. **************************************************************************************************************************************************************/
  50276. #ifndef MA_NO_DECODING
  50277. static ma_result ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  50278. {
  50279. MA_ASSERT(pDecoder != NULL);
  50280. return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead, pBytesRead);
  50281. }
  50282. static ma_result ma_decoder_seek_bytes(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin)
  50283. {
  50284. MA_ASSERT(pDecoder != NULL);
  50285. return pDecoder->onSeek(pDecoder, byteOffset, origin);
  50286. }
  50287. static ma_result ma_decoder_tell_bytes(ma_decoder* pDecoder, ma_int64* pCursor)
  50288. {
  50289. MA_ASSERT(pDecoder != NULL);
  50290. if (pDecoder->onTell == NULL) {
  50291. return MA_NOT_IMPLEMENTED;
  50292. }
  50293. return pDecoder->onTell(pDecoder, pCursor);
  50294. }
  50295. MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount)
  50296. {
  50297. ma_decoding_backend_config config;
  50298. MA_ZERO_OBJECT(&config);
  50299. config.preferredFormat = preferredFormat;
  50300. config.seekPointCount = seekPointCount;
  50301. return config;
  50302. }
  50303. MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate)
  50304. {
  50305. ma_decoder_config config;
  50306. MA_ZERO_OBJECT(&config);
  50307. config.format = outputFormat;
  50308. config.channels = outputChannels;
  50309. config.sampleRate = outputSampleRate;
  50310. config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate doesn't matter here. */
  50311. config.encodingFormat = ma_encoding_format_unknown;
  50312. /* Note that we are intentionally leaving the channel map empty here which will cause the default channel map to be used. */
  50313. return config;
  50314. }
  50315. MA_API ma_decoder_config ma_decoder_config_init_default()
  50316. {
  50317. return ma_decoder_config_init(ma_format_unknown, 0, 0);
  50318. }
  50319. MA_API ma_decoder_config ma_decoder_config_init_copy(const ma_decoder_config* pConfig)
  50320. {
  50321. ma_decoder_config config;
  50322. if (pConfig != NULL) {
  50323. config = *pConfig;
  50324. } else {
  50325. MA_ZERO_OBJECT(&config);
  50326. }
  50327. return config;
  50328. }
  50329. static ma_result ma_decoder__init_data_converter(ma_decoder* pDecoder, const ma_decoder_config* pConfig)
  50330. {
  50331. ma_result result;
  50332. ma_data_converter_config converterConfig;
  50333. ma_format internalFormat;
  50334. ma_uint32 internalChannels;
  50335. ma_uint32 internalSampleRate;
  50336. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  50337. MA_ASSERT(pDecoder != NULL);
  50338. MA_ASSERT(pConfig != NULL);
  50339. result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, &internalSampleRate, internalChannelMap, ma_countof(internalChannelMap));
  50340. if (result != MA_SUCCESS) {
  50341. return result; /* Failed to retrieve the internal data format. */
  50342. }
  50343. /* Make sure we're not asking for too many channels. */
  50344. if (pConfig->channels > MA_MAX_CHANNELS) {
  50345. return MA_INVALID_ARGS;
  50346. }
  50347. /* The internal channels should have already been validated at a higher level, but we'll do it again explicitly here for safety. */
  50348. if (internalChannels > MA_MAX_CHANNELS) {
  50349. return MA_INVALID_ARGS;
  50350. }
  50351. /* Output format. */
  50352. if (pConfig->format == ma_format_unknown) {
  50353. pDecoder->outputFormat = internalFormat;
  50354. } else {
  50355. pDecoder->outputFormat = pConfig->format;
  50356. }
  50357. if (pConfig->channels == 0) {
  50358. pDecoder->outputChannels = internalChannels;
  50359. } else {
  50360. pDecoder->outputChannels = pConfig->channels;
  50361. }
  50362. if (pConfig->sampleRate == 0) {
  50363. pDecoder->outputSampleRate = internalSampleRate;
  50364. } else {
  50365. pDecoder->outputSampleRate = pConfig->sampleRate;
  50366. }
  50367. converterConfig = ma_data_converter_config_init(
  50368. internalFormat, pDecoder->outputFormat,
  50369. internalChannels, pDecoder->outputChannels,
  50370. internalSampleRate, pDecoder->outputSampleRate
  50371. );
  50372. converterConfig.pChannelMapIn = internalChannelMap;
  50373. converterConfig.pChannelMapOut = pConfig->pChannelMap;
  50374. converterConfig.channelMixMode = pConfig->channelMixMode;
  50375. converterConfig.ditherMode = pConfig->ditherMode;
  50376. converterConfig.allowDynamicSampleRate = MA_FALSE; /* Never allow dynamic sample rate conversion. Setting this to true will disable passthrough optimizations. */
  50377. converterConfig.resampling = pConfig->resampling;
  50378. result = ma_data_converter_init(&converterConfig, &pDecoder->allocationCallbacks, &pDecoder->converter);
  50379. if (result != MA_SUCCESS) {
  50380. return result;
  50381. }
  50382. /*
  50383. Now that we have the decoder we need to determine whether or not we need a heap-allocated cache. We'll
  50384. need this if the data converter does not support calculation of the required input frame count. To
  50385. determine support for this we'll just run a test.
  50386. */
  50387. {
  50388. ma_uint64 unused;
  50389. result = ma_data_converter_get_required_input_frame_count(&pDecoder->converter, 1, &unused);
  50390. if (result != MA_SUCCESS) {
  50391. /*
  50392. We were unable to calculate the required input frame count which means we'll need to use
  50393. a heap-allocated cache.
  50394. */
  50395. ma_uint64 inputCacheCapSizeInBytes;
  50396. pDecoder->inputCacheCap = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(internalFormat, internalChannels);
  50397. /* Not strictly necessary, but keeping here for safety in case we change the default value of pDecoder->inputCacheCap. */
  50398. inputCacheCapSizeInBytes = pDecoder->inputCacheCap * ma_get_bytes_per_frame(internalFormat, internalChannels);
  50399. if (inputCacheCapSizeInBytes > MA_SIZE_MAX) {
  50400. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  50401. return MA_OUT_OF_MEMORY;
  50402. }
  50403. pDecoder->pInputCache = ma_malloc((size_t)inputCacheCapSizeInBytes, &pDecoder->allocationCallbacks); /* Safe cast to size_t. */
  50404. if (pDecoder->pInputCache == NULL) {
  50405. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  50406. return MA_OUT_OF_MEMORY;
  50407. }
  50408. }
  50409. }
  50410. return MA_SUCCESS;
  50411. }
  50412. static ma_result ma_decoder_internal_on_read__custom(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  50413. {
  50414. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  50415. MA_ASSERT(pDecoder != NULL);
  50416. return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead, pBytesRead);
  50417. }
  50418. static ma_result ma_decoder_internal_on_seek__custom(void* pUserData, ma_int64 offset, ma_seek_origin origin)
  50419. {
  50420. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  50421. MA_ASSERT(pDecoder != NULL);
  50422. return ma_decoder_seek_bytes(pDecoder, offset, origin);
  50423. }
  50424. static ma_result ma_decoder_internal_on_tell__custom(void* pUserData, ma_int64* pCursor)
  50425. {
  50426. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  50427. MA_ASSERT(pDecoder != NULL);
  50428. return ma_decoder_tell_bytes(pDecoder, pCursor);
  50429. }
  50430. static ma_result ma_decoder_init_from_vtable__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50431. {
  50432. ma_result result;
  50433. ma_decoding_backend_config backendConfig;
  50434. ma_data_source* pBackend;
  50435. MA_ASSERT(pVTable != NULL);
  50436. MA_ASSERT(pConfig != NULL);
  50437. MA_ASSERT(pDecoder != NULL);
  50438. if (pVTable->onInit == NULL) {
  50439. return MA_NOT_IMPLEMENTED;
  50440. }
  50441. backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount);
  50442. 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);
  50443. if (result != MA_SUCCESS) {
  50444. return result; /* Failed to initialize the backend from this vtable. */
  50445. }
  50446. /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */
  50447. pDecoder->pBackend = pBackend;
  50448. pDecoder->pBackendVTable = pVTable;
  50449. pDecoder->pBackendUserData = pConfig->pCustomBackendUserData;
  50450. return MA_SUCCESS;
  50451. }
  50452. static ma_result ma_decoder_init_from_file__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50453. {
  50454. ma_result result;
  50455. ma_decoding_backend_config backendConfig;
  50456. ma_data_source* pBackend;
  50457. MA_ASSERT(pVTable != NULL);
  50458. MA_ASSERT(pConfig != NULL);
  50459. MA_ASSERT(pDecoder != NULL);
  50460. if (pVTable->onInitFile == NULL) {
  50461. return MA_NOT_IMPLEMENTED;
  50462. }
  50463. backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount);
  50464. result = pVTable->onInitFile(pVTableUserData, pFilePath, &backendConfig, &pDecoder->allocationCallbacks, &pBackend);
  50465. if (result != MA_SUCCESS) {
  50466. return result; /* Failed to initialize the backend from this vtable. */
  50467. }
  50468. /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */
  50469. pDecoder->pBackend = pBackend;
  50470. pDecoder->pBackendVTable = pVTable;
  50471. pDecoder->pBackendUserData = pConfig->pCustomBackendUserData;
  50472. return MA_SUCCESS;
  50473. }
  50474. static ma_result ma_decoder_init_from_file_w__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50475. {
  50476. ma_result result;
  50477. ma_decoding_backend_config backendConfig;
  50478. ma_data_source* pBackend;
  50479. MA_ASSERT(pVTable != NULL);
  50480. MA_ASSERT(pConfig != NULL);
  50481. MA_ASSERT(pDecoder != NULL);
  50482. if (pVTable->onInitFileW == NULL) {
  50483. return MA_NOT_IMPLEMENTED;
  50484. }
  50485. backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount);
  50486. result = pVTable->onInitFileW(pVTableUserData, pFilePath, &backendConfig, &pDecoder->allocationCallbacks, &pBackend);
  50487. if (result != MA_SUCCESS) {
  50488. return result; /* Failed to initialize the backend from this vtable. */
  50489. }
  50490. /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */
  50491. pDecoder->pBackend = pBackend;
  50492. pDecoder->pBackendVTable = pVTable;
  50493. pDecoder->pBackendUserData = pConfig->pCustomBackendUserData;
  50494. return MA_SUCCESS;
  50495. }
  50496. static ma_result ma_decoder_init_from_memory__internal(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50497. {
  50498. ma_result result;
  50499. ma_decoding_backend_config backendConfig;
  50500. ma_data_source* pBackend;
  50501. MA_ASSERT(pVTable != NULL);
  50502. MA_ASSERT(pConfig != NULL);
  50503. MA_ASSERT(pDecoder != NULL);
  50504. if (pVTable->onInitMemory == NULL) {
  50505. return MA_NOT_IMPLEMENTED;
  50506. }
  50507. backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount);
  50508. result = pVTable->onInitMemory(pVTableUserData, pData, dataSize, &backendConfig, &pDecoder->allocationCallbacks, &pBackend);
  50509. if (result != MA_SUCCESS) {
  50510. return result; /* Failed to initialize the backend from this vtable. */
  50511. }
  50512. /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */
  50513. pDecoder->pBackend = pBackend;
  50514. pDecoder->pBackendVTable = pVTable;
  50515. pDecoder->pBackendUserData = pConfig->pCustomBackendUserData;
  50516. return MA_SUCCESS;
  50517. }
  50518. static ma_result ma_decoder_init_custom__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50519. {
  50520. ma_result result = MA_NO_BACKEND;
  50521. size_t ivtable;
  50522. MA_ASSERT(pConfig != NULL);
  50523. MA_ASSERT(pDecoder != NULL);
  50524. if (pConfig->ppCustomBackendVTables == NULL) {
  50525. return MA_NO_BACKEND;
  50526. }
  50527. /* The order each backend is listed is what defines the priority. */
  50528. for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) {
  50529. const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable];
  50530. if (pVTable != NULL) {
  50531. result = ma_decoder_init_from_vtable__internal(pVTable, pConfig->pCustomBackendUserData, pConfig, pDecoder);
  50532. if (result == MA_SUCCESS) {
  50533. return MA_SUCCESS;
  50534. } else {
  50535. /* 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. */
  50536. result = ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start);
  50537. if (result != MA_SUCCESS) {
  50538. return result; /* Failed to seek back to the start. */
  50539. }
  50540. }
  50541. } else {
  50542. /* No vtable. */
  50543. }
  50544. }
  50545. /* Getting here means we couldn't find a backend. */
  50546. return MA_NO_BACKEND;
  50547. }
  50548. static ma_result ma_decoder_init_custom_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50549. {
  50550. ma_result result = MA_NO_BACKEND;
  50551. size_t ivtable;
  50552. MA_ASSERT(pConfig != NULL);
  50553. MA_ASSERT(pDecoder != NULL);
  50554. if (pConfig->ppCustomBackendVTables == NULL) {
  50555. return MA_NO_BACKEND;
  50556. }
  50557. /* The order each backend is listed is what defines the priority. */
  50558. for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) {
  50559. const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable];
  50560. if (pVTable != NULL) {
  50561. result = ma_decoder_init_from_file__internal(pVTable, pConfig->pCustomBackendUserData, pFilePath, pConfig, pDecoder);
  50562. if (result == MA_SUCCESS) {
  50563. return MA_SUCCESS;
  50564. }
  50565. } else {
  50566. /* No vtable. */
  50567. }
  50568. }
  50569. /* Getting here means we couldn't find a backend. */
  50570. return MA_NO_BACKEND;
  50571. }
  50572. static ma_result ma_decoder_init_custom_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50573. {
  50574. ma_result result = MA_NO_BACKEND;
  50575. size_t ivtable;
  50576. MA_ASSERT(pConfig != NULL);
  50577. MA_ASSERT(pDecoder != NULL);
  50578. if (pConfig->ppCustomBackendVTables == NULL) {
  50579. return MA_NO_BACKEND;
  50580. }
  50581. /* The order each backend is listed is what defines the priority. */
  50582. for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) {
  50583. const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable];
  50584. if (pVTable != NULL) {
  50585. result = ma_decoder_init_from_file_w__internal(pVTable, pConfig->pCustomBackendUserData, pFilePath, pConfig, pDecoder);
  50586. if (result == MA_SUCCESS) {
  50587. return MA_SUCCESS;
  50588. }
  50589. } else {
  50590. /* No vtable. */
  50591. }
  50592. }
  50593. /* Getting here means we couldn't find a backend. */
  50594. return MA_NO_BACKEND;
  50595. }
  50596. static ma_result ma_decoder_init_custom_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50597. {
  50598. ma_result result = MA_NO_BACKEND;
  50599. size_t ivtable;
  50600. MA_ASSERT(pConfig != NULL);
  50601. MA_ASSERT(pDecoder != NULL);
  50602. if (pConfig->ppCustomBackendVTables == NULL) {
  50603. return MA_NO_BACKEND;
  50604. }
  50605. /* The order each backend is listed is what defines the priority. */
  50606. for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) {
  50607. const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable];
  50608. if (pVTable != NULL) {
  50609. result = ma_decoder_init_from_memory__internal(pVTable, pConfig->pCustomBackendUserData, pData, dataSize, pConfig, pDecoder);
  50610. if (result == MA_SUCCESS) {
  50611. return MA_SUCCESS;
  50612. }
  50613. } else {
  50614. /* No vtable. */
  50615. }
  50616. }
  50617. /* Getting here means we couldn't find a backend. */
  50618. return MA_NO_BACKEND;
  50619. }
  50620. /* WAV */
  50621. #ifdef ma_dr_wav_h
  50622. #define MA_HAS_WAV
  50623. typedef struct
  50624. {
  50625. ma_data_source_base ds;
  50626. ma_read_proc onRead;
  50627. ma_seek_proc onSeek;
  50628. ma_tell_proc onTell;
  50629. void* pReadSeekTellUserData;
  50630. ma_format format; /* Can be f32, s16 or s32. */
  50631. #if !defined(MA_NO_WAV)
  50632. ma_dr_wav dr;
  50633. #endif
  50634. } ma_wav;
  50635. 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);
  50636. 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);
  50637. 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);
  50638. 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);
  50639. MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks);
  50640. MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  50641. MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex);
  50642. 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);
  50643. MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor);
  50644. MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength);
  50645. static ma_result ma_wav_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50646. {
  50647. return ma_wav_read_pcm_frames((ma_wav*)pDataSource, pFramesOut, frameCount, pFramesRead);
  50648. }
  50649. static ma_result ma_wav_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  50650. {
  50651. return ma_wav_seek_to_pcm_frame((ma_wav*)pDataSource, frameIndex);
  50652. }
  50653. 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)
  50654. {
  50655. return ma_wav_get_data_format((ma_wav*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  50656. }
  50657. static ma_result ma_wav_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  50658. {
  50659. return ma_wav_get_cursor_in_pcm_frames((ma_wav*)pDataSource, pCursor);
  50660. }
  50661. static ma_result ma_wav_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  50662. {
  50663. return ma_wav_get_length_in_pcm_frames((ma_wav*)pDataSource, pLength);
  50664. }
  50665. static ma_data_source_vtable g_ma_wav_ds_vtable =
  50666. {
  50667. ma_wav_ds_read,
  50668. ma_wav_ds_seek,
  50669. ma_wav_ds_get_data_format,
  50670. ma_wav_ds_get_cursor,
  50671. ma_wav_ds_get_length,
  50672. NULL, /* onSetLooping */
  50673. 0
  50674. };
  50675. #if !defined(MA_NO_WAV)
  50676. static size_t ma_wav_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  50677. {
  50678. ma_wav* pWav = (ma_wav*)pUserData;
  50679. ma_result result;
  50680. size_t bytesRead;
  50681. MA_ASSERT(pWav != NULL);
  50682. result = pWav->onRead(pWav->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  50683. (void)result;
  50684. return bytesRead;
  50685. }
  50686. static ma_bool32 ma_wav_dr_callback__seek(void* pUserData, int offset, ma_dr_wav_seek_origin origin)
  50687. {
  50688. ma_wav* pWav = (ma_wav*)pUserData;
  50689. ma_result result;
  50690. ma_seek_origin maSeekOrigin;
  50691. MA_ASSERT(pWav != NULL);
  50692. maSeekOrigin = ma_seek_origin_start;
  50693. if (origin == ma_dr_wav_seek_origin_current) {
  50694. maSeekOrigin = ma_seek_origin_current;
  50695. }
  50696. result = pWav->onSeek(pWav->pReadSeekTellUserData, offset, maSeekOrigin);
  50697. if (result != MA_SUCCESS) {
  50698. return MA_FALSE;
  50699. }
  50700. return MA_TRUE;
  50701. }
  50702. #endif
  50703. static ma_result ma_wav_init_internal(const ma_decoding_backend_config* pConfig, ma_wav* pWav)
  50704. {
  50705. ma_result result;
  50706. ma_data_source_config dataSourceConfig;
  50707. if (pWav == NULL) {
  50708. return MA_INVALID_ARGS;
  50709. }
  50710. MA_ZERO_OBJECT(pWav);
  50711. pWav->format = ma_format_unknown; /* Use closest match to source file by default. */
  50712. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) {
  50713. pWav->format = pConfig->preferredFormat;
  50714. } else {
  50715. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  50716. }
  50717. dataSourceConfig = ma_data_source_config_init();
  50718. dataSourceConfig.vtable = &g_ma_wav_ds_vtable;
  50719. result = ma_data_source_init(&dataSourceConfig, &pWav->ds);
  50720. if (result != MA_SUCCESS) {
  50721. return result; /* Failed to initialize the base data source. */
  50722. }
  50723. return MA_SUCCESS;
  50724. }
  50725. static ma_result ma_wav_post_init(ma_wav* pWav)
  50726. {
  50727. /*
  50728. If an explicit format was not specified, try picking the closest match based on the internal
  50729. format. The format needs to be supported by miniaudio.
  50730. */
  50731. if (pWav->format == ma_format_unknown) {
  50732. switch (pWav->dr.translatedFormatTag)
  50733. {
  50734. case MA_DR_WAVE_FORMAT_PCM:
  50735. {
  50736. if (pWav->dr.bitsPerSample == 8) {
  50737. pWav->format = ma_format_u8;
  50738. } else if (pWav->dr.bitsPerSample == 16) {
  50739. pWav->format = ma_format_s16;
  50740. } else if (pWav->dr.bitsPerSample == 24) {
  50741. pWav->format = ma_format_s24;
  50742. } else if (pWav->dr.bitsPerSample == 32) {
  50743. pWav->format = ma_format_s32;
  50744. }
  50745. } break;
  50746. case MA_DR_WAVE_FORMAT_IEEE_FLOAT:
  50747. {
  50748. if (pWav->dr.bitsPerSample == 32) {
  50749. pWav->format = ma_format_f32;
  50750. }
  50751. } break;
  50752. default: break;
  50753. }
  50754. /* Fall back to f32 if we couldn't find anything. */
  50755. if (pWav->format == ma_format_unknown) {
  50756. pWav->format = ma_format_f32;
  50757. }
  50758. }
  50759. return MA_SUCCESS;
  50760. }
  50761. 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)
  50762. {
  50763. ma_result result;
  50764. result = ma_wav_init_internal(pConfig, pWav);
  50765. if (result != MA_SUCCESS) {
  50766. return result;
  50767. }
  50768. if (onRead == NULL || onSeek == NULL) {
  50769. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  50770. }
  50771. pWav->onRead = onRead;
  50772. pWav->onSeek = onSeek;
  50773. pWav->onTell = onTell;
  50774. pWav->pReadSeekTellUserData = pReadSeekTellUserData;
  50775. #if !defined(MA_NO_WAV)
  50776. {
  50777. ma_bool32 wavResult;
  50778. wavResult = ma_dr_wav_init(&pWav->dr, ma_wav_dr_callback__read, ma_wav_dr_callback__seek, pWav, pAllocationCallbacks);
  50779. if (wavResult != MA_TRUE) {
  50780. return MA_INVALID_FILE;
  50781. }
  50782. ma_wav_post_init(pWav);
  50783. return MA_SUCCESS;
  50784. }
  50785. #else
  50786. {
  50787. /* wav is disabled. */
  50788. (void)pAllocationCallbacks;
  50789. return MA_NOT_IMPLEMENTED;
  50790. }
  50791. #endif
  50792. }
  50793. 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)
  50794. {
  50795. ma_result result;
  50796. result = ma_wav_init_internal(pConfig, pWav);
  50797. if (result != MA_SUCCESS) {
  50798. return result;
  50799. }
  50800. #if !defined(MA_NO_WAV)
  50801. {
  50802. ma_bool32 wavResult;
  50803. wavResult = ma_dr_wav_init_file(&pWav->dr, pFilePath, pAllocationCallbacks);
  50804. if (wavResult != MA_TRUE) {
  50805. return MA_INVALID_FILE;
  50806. }
  50807. ma_wav_post_init(pWav);
  50808. return MA_SUCCESS;
  50809. }
  50810. #else
  50811. {
  50812. /* wav is disabled. */
  50813. (void)pFilePath;
  50814. (void)pAllocationCallbacks;
  50815. return MA_NOT_IMPLEMENTED;
  50816. }
  50817. #endif
  50818. }
  50819. 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)
  50820. {
  50821. ma_result result;
  50822. result = ma_wav_init_internal(pConfig, pWav);
  50823. if (result != MA_SUCCESS) {
  50824. return result;
  50825. }
  50826. #if !defined(MA_NO_WAV)
  50827. {
  50828. ma_bool32 wavResult;
  50829. wavResult = ma_dr_wav_init_file_w(&pWav->dr, pFilePath, pAllocationCallbacks);
  50830. if (wavResult != MA_TRUE) {
  50831. return MA_INVALID_FILE;
  50832. }
  50833. ma_wav_post_init(pWav);
  50834. return MA_SUCCESS;
  50835. }
  50836. #else
  50837. {
  50838. /* wav is disabled. */
  50839. (void)pFilePath;
  50840. (void)pAllocationCallbacks;
  50841. return MA_NOT_IMPLEMENTED;
  50842. }
  50843. #endif
  50844. }
  50845. 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)
  50846. {
  50847. ma_result result;
  50848. result = ma_wav_init_internal(pConfig, pWav);
  50849. if (result != MA_SUCCESS) {
  50850. return result;
  50851. }
  50852. #if !defined(MA_NO_WAV)
  50853. {
  50854. ma_bool32 wavResult;
  50855. wavResult = ma_dr_wav_init_memory(&pWav->dr, pData, dataSize, pAllocationCallbacks);
  50856. if (wavResult != MA_TRUE) {
  50857. return MA_INVALID_FILE;
  50858. }
  50859. ma_wav_post_init(pWav);
  50860. return MA_SUCCESS;
  50861. }
  50862. #else
  50863. {
  50864. /* wav is disabled. */
  50865. (void)pData;
  50866. (void)dataSize;
  50867. (void)pAllocationCallbacks;
  50868. return MA_NOT_IMPLEMENTED;
  50869. }
  50870. #endif
  50871. }
  50872. MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks)
  50873. {
  50874. if (pWav == NULL) {
  50875. return;
  50876. }
  50877. (void)pAllocationCallbacks;
  50878. #if !defined(MA_NO_WAV)
  50879. {
  50880. ma_dr_wav_uninit(&pWav->dr);
  50881. }
  50882. #else
  50883. {
  50884. /* wav is disabled. Should never hit this since initialization would have failed. */
  50885. MA_ASSERT(MA_FALSE);
  50886. }
  50887. #endif
  50888. ma_data_source_uninit(&pWav->ds);
  50889. }
  50890. MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50891. {
  50892. if (pFramesRead != NULL) {
  50893. *pFramesRead = 0;
  50894. }
  50895. if (frameCount == 0) {
  50896. return MA_INVALID_ARGS;
  50897. }
  50898. if (pWav == NULL) {
  50899. return MA_INVALID_ARGS;
  50900. }
  50901. #if !defined(MA_NO_WAV)
  50902. {
  50903. /* We always use floating point format. */
  50904. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  50905. ma_uint64 totalFramesRead = 0;
  50906. ma_format format;
  50907. ma_wav_get_data_format(pWav, &format, NULL, NULL, NULL, 0);
  50908. switch (format)
  50909. {
  50910. case ma_format_f32:
  50911. {
  50912. totalFramesRead = ma_dr_wav_read_pcm_frames_f32(&pWav->dr, frameCount, (float*)pFramesOut);
  50913. } break;
  50914. case ma_format_s16:
  50915. {
  50916. totalFramesRead = ma_dr_wav_read_pcm_frames_s16(&pWav->dr, frameCount, (ma_int16*)pFramesOut);
  50917. } break;
  50918. case ma_format_s32:
  50919. {
  50920. totalFramesRead = ma_dr_wav_read_pcm_frames_s32(&pWav->dr, frameCount, (ma_int32*)pFramesOut);
  50921. } break;
  50922. /* Fallback to a raw read. */
  50923. case ma_format_unknown: return MA_INVALID_OPERATION; /* <-- this should never be hit because initialization would just fall back to a supported format. */
  50924. default:
  50925. {
  50926. totalFramesRead = ma_dr_wav_read_pcm_frames(&pWav->dr, frameCount, pFramesOut);
  50927. } break;
  50928. }
  50929. /* In the future we'll update ma_dr_wav to return MA_AT_END for us. */
  50930. if (totalFramesRead == 0) {
  50931. result = MA_AT_END;
  50932. }
  50933. if (pFramesRead != NULL) {
  50934. *pFramesRead = totalFramesRead;
  50935. }
  50936. if (result == MA_SUCCESS && totalFramesRead == 0) {
  50937. result = MA_AT_END;
  50938. }
  50939. return result;
  50940. }
  50941. #else
  50942. {
  50943. /* wav is disabled. Should never hit this since initialization would have failed. */
  50944. MA_ASSERT(MA_FALSE);
  50945. (void)pFramesOut;
  50946. (void)frameCount;
  50947. (void)pFramesRead;
  50948. return MA_NOT_IMPLEMENTED;
  50949. }
  50950. #endif
  50951. }
  50952. MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex)
  50953. {
  50954. if (pWav == NULL) {
  50955. return MA_INVALID_ARGS;
  50956. }
  50957. #if !defined(MA_NO_WAV)
  50958. {
  50959. ma_bool32 wavResult;
  50960. wavResult = ma_dr_wav_seek_to_pcm_frame(&pWav->dr, frameIndex);
  50961. if (wavResult != MA_TRUE) {
  50962. return MA_ERROR;
  50963. }
  50964. return MA_SUCCESS;
  50965. }
  50966. #else
  50967. {
  50968. /* wav is disabled. Should never hit this since initialization would have failed. */
  50969. MA_ASSERT(MA_FALSE);
  50970. (void)frameIndex;
  50971. return MA_NOT_IMPLEMENTED;
  50972. }
  50973. #endif
  50974. }
  50975. 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)
  50976. {
  50977. /* Defaults for safety. */
  50978. if (pFormat != NULL) {
  50979. *pFormat = ma_format_unknown;
  50980. }
  50981. if (pChannels != NULL) {
  50982. *pChannels = 0;
  50983. }
  50984. if (pSampleRate != NULL) {
  50985. *pSampleRate = 0;
  50986. }
  50987. if (pChannelMap != NULL) {
  50988. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  50989. }
  50990. if (pWav == NULL) {
  50991. return MA_INVALID_OPERATION;
  50992. }
  50993. if (pFormat != NULL) {
  50994. *pFormat = pWav->format;
  50995. }
  50996. #if !defined(MA_NO_WAV)
  50997. {
  50998. if (pChannels != NULL) {
  50999. *pChannels = pWav->dr.channels;
  51000. }
  51001. if (pSampleRate != NULL) {
  51002. *pSampleRate = pWav->dr.sampleRate;
  51003. }
  51004. if (pChannelMap != NULL) {
  51005. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pWav->dr.channels);
  51006. }
  51007. return MA_SUCCESS;
  51008. }
  51009. #else
  51010. {
  51011. /* wav is disabled. Should never hit this since initialization would have failed. */
  51012. MA_ASSERT(MA_FALSE);
  51013. return MA_NOT_IMPLEMENTED;
  51014. }
  51015. #endif
  51016. }
  51017. MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor)
  51018. {
  51019. if (pCursor == NULL) {
  51020. return MA_INVALID_ARGS;
  51021. }
  51022. *pCursor = 0; /* Safety. */
  51023. if (pWav == NULL) {
  51024. return MA_INVALID_ARGS;
  51025. }
  51026. #if !defined(MA_NO_WAV)
  51027. {
  51028. ma_result wavResult = ma_dr_wav_get_cursor_in_pcm_frames(&pWav->dr, pCursor);
  51029. if (wavResult != MA_SUCCESS) {
  51030. return (ma_result)wavResult; /* ma_dr_wav result codes map to miniaudio's. */
  51031. }
  51032. return MA_SUCCESS;
  51033. }
  51034. #else
  51035. {
  51036. /* wav is disabled. Should never hit this since initialization would have failed. */
  51037. MA_ASSERT(MA_FALSE);
  51038. return MA_NOT_IMPLEMENTED;
  51039. }
  51040. #endif
  51041. }
  51042. MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength)
  51043. {
  51044. if (pLength == NULL) {
  51045. return MA_INVALID_ARGS;
  51046. }
  51047. *pLength = 0; /* Safety. */
  51048. if (pWav == NULL) {
  51049. return MA_INVALID_ARGS;
  51050. }
  51051. #if !defined(MA_NO_WAV)
  51052. {
  51053. ma_result wavResult = ma_dr_wav_get_length_in_pcm_frames(&pWav->dr, pLength);
  51054. if (wavResult != MA_SUCCESS) {
  51055. return (ma_result)wavResult; /* ma_dr_wav result codes map to miniaudio's. */
  51056. }
  51057. return MA_SUCCESS;
  51058. }
  51059. #else
  51060. {
  51061. /* wav is disabled. Should never hit this since initialization would have failed. */
  51062. MA_ASSERT(MA_FALSE);
  51063. return MA_NOT_IMPLEMENTED;
  51064. }
  51065. #endif
  51066. }
  51067. 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)
  51068. {
  51069. ma_result result;
  51070. ma_wav* pWav;
  51071. (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. */
  51072. /* For now we're just allocating the decoder backend on the heap. */
  51073. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51074. if (pWav == NULL) {
  51075. return MA_OUT_OF_MEMORY;
  51076. }
  51077. result = ma_wav_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pWav);
  51078. if (result != MA_SUCCESS) {
  51079. ma_free(pWav, pAllocationCallbacks);
  51080. return result;
  51081. }
  51082. *ppBackend = pWav;
  51083. return MA_SUCCESS;
  51084. }
  51085. 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)
  51086. {
  51087. ma_result result;
  51088. ma_wav* pWav;
  51089. (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. */
  51090. /* For now we're just allocating the decoder backend on the heap. */
  51091. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51092. if (pWav == NULL) {
  51093. return MA_OUT_OF_MEMORY;
  51094. }
  51095. result = ma_wav_init_file(pFilePath, pConfig, pAllocationCallbacks, pWav);
  51096. if (result != MA_SUCCESS) {
  51097. ma_free(pWav, pAllocationCallbacks);
  51098. return result;
  51099. }
  51100. *ppBackend = pWav;
  51101. return MA_SUCCESS;
  51102. }
  51103. 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)
  51104. {
  51105. ma_result result;
  51106. ma_wav* pWav;
  51107. (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. */
  51108. /* For now we're just allocating the decoder backend on the heap. */
  51109. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51110. if (pWav == NULL) {
  51111. return MA_OUT_OF_MEMORY;
  51112. }
  51113. result = ma_wav_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pWav);
  51114. if (result != MA_SUCCESS) {
  51115. ma_free(pWav, pAllocationCallbacks);
  51116. return result;
  51117. }
  51118. *ppBackend = pWav;
  51119. return MA_SUCCESS;
  51120. }
  51121. 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)
  51122. {
  51123. ma_result result;
  51124. ma_wav* pWav;
  51125. (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. */
  51126. /* For now we're just allocating the decoder backend on the heap. */
  51127. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  51128. if (pWav == NULL) {
  51129. return MA_OUT_OF_MEMORY;
  51130. }
  51131. result = ma_wav_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pWav);
  51132. if (result != MA_SUCCESS) {
  51133. ma_free(pWav, pAllocationCallbacks);
  51134. return result;
  51135. }
  51136. *ppBackend = pWav;
  51137. return MA_SUCCESS;
  51138. }
  51139. static void ma_decoding_backend_uninit__wav(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  51140. {
  51141. ma_wav* pWav = (ma_wav*)pBackend;
  51142. (void)pUserData;
  51143. ma_wav_uninit(pWav, pAllocationCallbacks);
  51144. ma_free(pWav, pAllocationCallbacks);
  51145. }
  51146. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_wav =
  51147. {
  51148. ma_decoding_backend_init__wav,
  51149. ma_decoding_backend_init_file__wav,
  51150. ma_decoding_backend_init_file_w__wav,
  51151. ma_decoding_backend_init_memory__wav,
  51152. ma_decoding_backend_uninit__wav
  51153. };
  51154. static ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51155. {
  51156. return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_wav, NULL, pConfig, pDecoder);
  51157. }
  51158. static ma_result ma_decoder_init_wav_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51159. {
  51160. return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_wav, NULL, pFilePath, pConfig, pDecoder);
  51161. }
  51162. static ma_result ma_decoder_init_wav_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51163. {
  51164. return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_wav, NULL, pFilePath, pConfig, pDecoder);
  51165. }
  51166. static ma_result ma_decoder_init_wav_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51167. {
  51168. return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_wav, NULL, pData, dataSize, pConfig, pDecoder);
  51169. }
  51170. #endif /* ma_dr_wav_h */
  51171. /* FLAC */
  51172. #ifdef ma_dr_flac_h
  51173. #define MA_HAS_FLAC
  51174. typedef struct
  51175. {
  51176. ma_data_source_base ds;
  51177. ma_read_proc onRead;
  51178. ma_seek_proc onSeek;
  51179. ma_tell_proc onTell;
  51180. void* pReadSeekTellUserData;
  51181. ma_format format; /* Can be f32, s16 or s32. */
  51182. #if !defined(MA_NO_FLAC)
  51183. ma_dr_flac* dr;
  51184. #endif
  51185. } ma_flac;
  51186. 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);
  51187. 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);
  51188. 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);
  51189. 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);
  51190. MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks);
  51191. MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  51192. MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex);
  51193. 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);
  51194. MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor);
  51195. MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength);
  51196. static ma_result ma_flac_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51197. {
  51198. return ma_flac_read_pcm_frames((ma_flac*)pDataSource, pFramesOut, frameCount, pFramesRead);
  51199. }
  51200. static ma_result ma_flac_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  51201. {
  51202. return ma_flac_seek_to_pcm_frame((ma_flac*)pDataSource, frameIndex);
  51203. }
  51204. 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)
  51205. {
  51206. return ma_flac_get_data_format((ma_flac*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  51207. }
  51208. static ma_result ma_flac_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  51209. {
  51210. return ma_flac_get_cursor_in_pcm_frames((ma_flac*)pDataSource, pCursor);
  51211. }
  51212. static ma_result ma_flac_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  51213. {
  51214. return ma_flac_get_length_in_pcm_frames((ma_flac*)pDataSource, pLength);
  51215. }
  51216. static ma_data_source_vtable g_ma_flac_ds_vtable =
  51217. {
  51218. ma_flac_ds_read,
  51219. ma_flac_ds_seek,
  51220. ma_flac_ds_get_data_format,
  51221. ma_flac_ds_get_cursor,
  51222. ma_flac_ds_get_length,
  51223. NULL, /* onSetLooping */
  51224. 0
  51225. };
  51226. #if !defined(MA_NO_FLAC)
  51227. static size_t ma_flac_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  51228. {
  51229. ma_flac* pFlac = (ma_flac*)pUserData;
  51230. ma_result result;
  51231. size_t bytesRead;
  51232. MA_ASSERT(pFlac != NULL);
  51233. result = pFlac->onRead(pFlac->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  51234. (void)result;
  51235. return bytesRead;
  51236. }
  51237. static ma_bool32 ma_flac_dr_callback__seek(void* pUserData, int offset, ma_dr_flac_seek_origin origin)
  51238. {
  51239. ma_flac* pFlac = (ma_flac*)pUserData;
  51240. ma_result result;
  51241. ma_seek_origin maSeekOrigin;
  51242. MA_ASSERT(pFlac != NULL);
  51243. maSeekOrigin = ma_seek_origin_start;
  51244. if (origin == ma_dr_flac_seek_origin_current) {
  51245. maSeekOrigin = ma_seek_origin_current;
  51246. }
  51247. result = pFlac->onSeek(pFlac->pReadSeekTellUserData, offset, maSeekOrigin);
  51248. if (result != MA_SUCCESS) {
  51249. return MA_FALSE;
  51250. }
  51251. return MA_TRUE;
  51252. }
  51253. #endif
  51254. static ma_result ma_flac_init_internal(const ma_decoding_backend_config* pConfig, ma_flac* pFlac)
  51255. {
  51256. ma_result result;
  51257. ma_data_source_config dataSourceConfig;
  51258. if (pFlac == NULL) {
  51259. return MA_INVALID_ARGS;
  51260. }
  51261. MA_ZERO_OBJECT(pFlac);
  51262. pFlac->format = ma_format_f32; /* f32 by default. */
  51263. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) {
  51264. pFlac->format = pConfig->preferredFormat;
  51265. } else {
  51266. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  51267. }
  51268. dataSourceConfig = ma_data_source_config_init();
  51269. dataSourceConfig.vtable = &g_ma_flac_ds_vtable;
  51270. result = ma_data_source_init(&dataSourceConfig, &pFlac->ds);
  51271. if (result != MA_SUCCESS) {
  51272. return result; /* Failed to initialize the base data source. */
  51273. }
  51274. return MA_SUCCESS;
  51275. }
  51276. 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)
  51277. {
  51278. ma_result result;
  51279. result = ma_flac_init_internal(pConfig, pFlac);
  51280. if (result != MA_SUCCESS) {
  51281. return result;
  51282. }
  51283. if (onRead == NULL || onSeek == NULL) {
  51284. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  51285. }
  51286. pFlac->onRead = onRead;
  51287. pFlac->onSeek = onSeek;
  51288. pFlac->onTell = onTell;
  51289. pFlac->pReadSeekTellUserData = pReadSeekTellUserData;
  51290. #if !defined(MA_NO_FLAC)
  51291. {
  51292. pFlac->dr = ma_dr_flac_open(ma_flac_dr_callback__read, ma_flac_dr_callback__seek, pFlac, pAllocationCallbacks);
  51293. if (pFlac->dr == NULL) {
  51294. return MA_INVALID_FILE;
  51295. }
  51296. return MA_SUCCESS;
  51297. }
  51298. #else
  51299. {
  51300. /* flac is disabled. */
  51301. (void)pAllocationCallbacks;
  51302. return MA_NOT_IMPLEMENTED;
  51303. }
  51304. #endif
  51305. }
  51306. 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)
  51307. {
  51308. ma_result result;
  51309. result = ma_flac_init_internal(pConfig, pFlac);
  51310. if (result != MA_SUCCESS) {
  51311. return result;
  51312. }
  51313. #if !defined(MA_NO_FLAC)
  51314. {
  51315. pFlac->dr = ma_dr_flac_open_file(pFilePath, pAllocationCallbacks);
  51316. if (pFlac->dr == NULL) {
  51317. return MA_INVALID_FILE;
  51318. }
  51319. return MA_SUCCESS;
  51320. }
  51321. #else
  51322. {
  51323. /* flac is disabled. */
  51324. (void)pFilePath;
  51325. (void)pAllocationCallbacks;
  51326. return MA_NOT_IMPLEMENTED;
  51327. }
  51328. #endif
  51329. }
  51330. 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)
  51331. {
  51332. ma_result result;
  51333. result = ma_flac_init_internal(pConfig, pFlac);
  51334. if (result != MA_SUCCESS) {
  51335. return result;
  51336. }
  51337. #if !defined(MA_NO_FLAC)
  51338. {
  51339. pFlac->dr = ma_dr_flac_open_file_w(pFilePath, pAllocationCallbacks);
  51340. if (pFlac->dr == NULL) {
  51341. return MA_INVALID_FILE;
  51342. }
  51343. return MA_SUCCESS;
  51344. }
  51345. #else
  51346. {
  51347. /* flac is disabled. */
  51348. (void)pFilePath;
  51349. (void)pAllocationCallbacks;
  51350. return MA_NOT_IMPLEMENTED;
  51351. }
  51352. #endif
  51353. }
  51354. 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)
  51355. {
  51356. ma_result result;
  51357. result = ma_flac_init_internal(pConfig, pFlac);
  51358. if (result != MA_SUCCESS) {
  51359. return result;
  51360. }
  51361. #if !defined(MA_NO_FLAC)
  51362. {
  51363. pFlac->dr = ma_dr_flac_open_memory(pData, dataSize, pAllocationCallbacks);
  51364. if (pFlac->dr == NULL) {
  51365. return MA_INVALID_FILE;
  51366. }
  51367. return MA_SUCCESS;
  51368. }
  51369. #else
  51370. {
  51371. /* flac is disabled. */
  51372. (void)pData;
  51373. (void)dataSize;
  51374. (void)pAllocationCallbacks;
  51375. return MA_NOT_IMPLEMENTED;
  51376. }
  51377. #endif
  51378. }
  51379. MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks)
  51380. {
  51381. if (pFlac == NULL) {
  51382. return;
  51383. }
  51384. (void)pAllocationCallbacks;
  51385. #if !defined(MA_NO_FLAC)
  51386. {
  51387. ma_dr_flac_close(pFlac->dr);
  51388. }
  51389. #else
  51390. {
  51391. /* flac is disabled. Should never hit this since initialization would have failed. */
  51392. MA_ASSERT(MA_FALSE);
  51393. }
  51394. #endif
  51395. ma_data_source_uninit(&pFlac->ds);
  51396. }
  51397. MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51398. {
  51399. if (pFramesRead != NULL) {
  51400. *pFramesRead = 0;
  51401. }
  51402. if (frameCount == 0) {
  51403. return MA_INVALID_ARGS;
  51404. }
  51405. if (pFlac == NULL) {
  51406. return MA_INVALID_ARGS;
  51407. }
  51408. #if !defined(MA_NO_FLAC)
  51409. {
  51410. /* We always use floating point format. */
  51411. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  51412. ma_uint64 totalFramesRead = 0;
  51413. ma_format format;
  51414. ma_flac_get_data_format(pFlac, &format, NULL, NULL, NULL, 0);
  51415. switch (format)
  51416. {
  51417. case ma_format_f32:
  51418. {
  51419. totalFramesRead = ma_dr_flac_read_pcm_frames_f32(pFlac->dr, frameCount, (float*)pFramesOut);
  51420. } break;
  51421. case ma_format_s16:
  51422. {
  51423. totalFramesRead = ma_dr_flac_read_pcm_frames_s16(pFlac->dr, frameCount, (ma_int16*)pFramesOut);
  51424. } break;
  51425. case ma_format_s32:
  51426. {
  51427. totalFramesRead = ma_dr_flac_read_pcm_frames_s32(pFlac->dr, frameCount, (ma_int32*)pFramesOut);
  51428. } break;
  51429. case ma_format_u8:
  51430. case ma_format_s24:
  51431. case ma_format_unknown:
  51432. default:
  51433. {
  51434. return MA_INVALID_OPERATION;
  51435. };
  51436. }
  51437. /* In the future we'll update ma_dr_flac to return MA_AT_END for us. */
  51438. if (totalFramesRead == 0) {
  51439. result = MA_AT_END;
  51440. }
  51441. if (pFramesRead != NULL) {
  51442. *pFramesRead = totalFramesRead;
  51443. }
  51444. if (result == MA_SUCCESS && totalFramesRead == 0) {
  51445. result = MA_AT_END;
  51446. }
  51447. return result;
  51448. }
  51449. #else
  51450. {
  51451. /* flac is disabled. Should never hit this since initialization would have failed. */
  51452. MA_ASSERT(MA_FALSE);
  51453. (void)pFramesOut;
  51454. (void)frameCount;
  51455. (void)pFramesRead;
  51456. return MA_NOT_IMPLEMENTED;
  51457. }
  51458. #endif
  51459. }
  51460. MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex)
  51461. {
  51462. if (pFlac == NULL) {
  51463. return MA_INVALID_ARGS;
  51464. }
  51465. #if !defined(MA_NO_FLAC)
  51466. {
  51467. ma_bool32 flacResult;
  51468. flacResult = ma_dr_flac_seek_to_pcm_frame(pFlac->dr, frameIndex);
  51469. if (flacResult != MA_TRUE) {
  51470. return MA_ERROR;
  51471. }
  51472. return MA_SUCCESS;
  51473. }
  51474. #else
  51475. {
  51476. /* flac is disabled. Should never hit this since initialization would have failed. */
  51477. MA_ASSERT(MA_FALSE);
  51478. (void)frameIndex;
  51479. return MA_NOT_IMPLEMENTED;
  51480. }
  51481. #endif
  51482. }
  51483. 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)
  51484. {
  51485. /* Defaults for safety. */
  51486. if (pFormat != NULL) {
  51487. *pFormat = ma_format_unknown;
  51488. }
  51489. if (pChannels != NULL) {
  51490. *pChannels = 0;
  51491. }
  51492. if (pSampleRate != NULL) {
  51493. *pSampleRate = 0;
  51494. }
  51495. if (pChannelMap != NULL) {
  51496. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  51497. }
  51498. if (pFlac == NULL) {
  51499. return MA_INVALID_OPERATION;
  51500. }
  51501. if (pFormat != NULL) {
  51502. *pFormat = pFlac->format;
  51503. }
  51504. #if !defined(MA_NO_FLAC)
  51505. {
  51506. if (pChannels != NULL) {
  51507. *pChannels = pFlac->dr->channels;
  51508. }
  51509. if (pSampleRate != NULL) {
  51510. *pSampleRate = pFlac->dr->sampleRate;
  51511. }
  51512. if (pChannelMap != NULL) {
  51513. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pFlac->dr->channels);
  51514. }
  51515. return MA_SUCCESS;
  51516. }
  51517. #else
  51518. {
  51519. /* flac is disabled. Should never hit this since initialization would have failed. */
  51520. MA_ASSERT(MA_FALSE);
  51521. return MA_NOT_IMPLEMENTED;
  51522. }
  51523. #endif
  51524. }
  51525. MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor)
  51526. {
  51527. if (pCursor == NULL) {
  51528. return MA_INVALID_ARGS;
  51529. }
  51530. *pCursor = 0; /* Safety. */
  51531. if (pFlac == NULL) {
  51532. return MA_INVALID_ARGS;
  51533. }
  51534. #if !defined(MA_NO_FLAC)
  51535. {
  51536. *pCursor = pFlac->dr->currentPCMFrame;
  51537. return MA_SUCCESS;
  51538. }
  51539. #else
  51540. {
  51541. /* flac is disabled. Should never hit this since initialization would have failed. */
  51542. MA_ASSERT(MA_FALSE);
  51543. return MA_NOT_IMPLEMENTED;
  51544. }
  51545. #endif
  51546. }
  51547. MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength)
  51548. {
  51549. if (pLength == NULL) {
  51550. return MA_INVALID_ARGS;
  51551. }
  51552. *pLength = 0; /* Safety. */
  51553. if (pFlac == NULL) {
  51554. return MA_INVALID_ARGS;
  51555. }
  51556. #if !defined(MA_NO_FLAC)
  51557. {
  51558. *pLength = pFlac->dr->totalPCMFrameCount;
  51559. return MA_SUCCESS;
  51560. }
  51561. #else
  51562. {
  51563. /* flac is disabled. Should never hit this since initialization would have failed. */
  51564. MA_ASSERT(MA_FALSE);
  51565. return MA_NOT_IMPLEMENTED;
  51566. }
  51567. #endif
  51568. }
  51569. 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)
  51570. {
  51571. ma_result result;
  51572. ma_flac* pFlac;
  51573. (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. */
  51574. /* For now we're just allocating the decoder backend on the heap. */
  51575. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51576. if (pFlac == NULL) {
  51577. return MA_OUT_OF_MEMORY;
  51578. }
  51579. result = ma_flac_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pFlac);
  51580. if (result != MA_SUCCESS) {
  51581. ma_free(pFlac, pAllocationCallbacks);
  51582. return result;
  51583. }
  51584. *ppBackend = pFlac;
  51585. return MA_SUCCESS;
  51586. }
  51587. 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)
  51588. {
  51589. ma_result result;
  51590. ma_flac* pFlac;
  51591. (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. */
  51592. /* For now we're just allocating the decoder backend on the heap. */
  51593. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51594. if (pFlac == NULL) {
  51595. return MA_OUT_OF_MEMORY;
  51596. }
  51597. result = ma_flac_init_file(pFilePath, pConfig, pAllocationCallbacks, pFlac);
  51598. if (result != MA_SUCCESS) {
  51599. ma_free(pFlac, pAllocationCallbacks);
  51600. return result;
  51601. }
  51602. *ppBackend = pFlac;
  51603. return MA_SUCCESS;
  51604. }
  51605. 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)
  51606. {
  51607. ma_result result;
  51608. ma_flac* pFlac;
  51609. (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. */
  51610. /* For now we're just allocating the decoder backend on the heap. */
  51611. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51612. if (pFlac == NULL) {
  51613. return MA_OUT_OF_MEMORY;
  51614. }
  51615. result = ma_flac_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pFlac);
  51616. if (result != MA_SUCCESS) {
  51617. ma_free(pFlac, pAllocationCallbacks);
  51618. return result;
  51619. }
  51620. *ppBackend = pFlac;
  51621. return MA_SUCCESS;
  51622. }
  51623. 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)
  51624. {
  51625. ma_result result;
  51626. ma_flac* pFlac;
  51627. (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. */
  51628. /* For now we're just allocating the decoder backend on the heap. */
  51629. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  51630. if (pFlac == NULL) {
  51631. return MA_OUT_OF_MEMORY;
  51632. }
  51633. result = ma_flac_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pFlac);
  51634. if (result != MA_SUCCESS) {
  51635. ma_free(pFlac, pAllocationCallbacks);
  51636. return result;
  51637. }
  51638. *ppBackend = pFlac;
  51639. return MA_SUCCESS;
  51640. }
  51641. static void ma_decoding_backend_uninit__flac(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  51642. {
  51643. ma_flac* pFlac = (ma_flac*)pBackend;
  51644. (void)pUserData;
  51645. ma_flac_uninit(pFlac, pAllocationCallbacks);
  51646. ma_free(pFlac, pAllocationCallbacks);
  51647. }
  51648. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_flac =
  51649. {
  51650. ma_decoding_backend_init__flac,
  51651. ma_decoding_backend_init_file__flac,
  51652. ma_decoding_backend_init_file_w__flac,
  51653. ma_decoding_backend_init_memory__flac,
  51654. ma_decoding_backend_uninit__flac
  51655. };
  51656. static ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51657. {
  51658. return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_flac, NULL, pConfig, pDecoder);
  51659. }
  51660. static ma_result ma_decoder_init_flac_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51661. {
  51662. return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_flac, NULL, pFilePath, pConfig, pDecoder);
  51663. }
  51664. static ma_result ma_decoder_init_flac_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51665. {
  51666. return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_flac, NULL, pFilePath, pConfig, pDecoder);
  51667. }
  51668. static ma_result ma_decoder_init_flac_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51669. {
  51670. return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_flac, NULL, pData, dataSize, pConfig, pDecoder);
  51671. }
  51672. #endif /* ma_dr_flac_h */
  51673. /* MP3 */
  51674. #ifdef ma_dr_mp3_h
  51675. #define MA_HAS_MP3
  51676. typedef struct
  51677. {
  51678. ma_data_source_base ds;
  51679. ma_read_proc onRead;
  51680. ma_seek_proc onSeek;
  51681. ma_tell_proc onTell;
  51682. void* pReadSeekTellUserData;
  51683. ma_format format; /* Can be f32 or s16. */
  51684. #if !defined(MA_NO_MP3)
  51685. ma_dr_mp3 dr;
  51686. ma_uint32 seekPointCount;
  51687. ma_dr_mp3_seek_point* pSeekPoints; /* Only used if seek table generation is used. */
  51688. #endif
  51689. } ma_mp3;
  51690. 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);
  51691. 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);
  51692. 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);
  51693. 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);
  51694. MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks);
  51695. MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  51696. MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex);
  51697. 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);
  51698. MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor);
  51699. MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength);
  51700. static ma_result ma_mp3_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51701. {
  51702. return ma_mp3_read_pcm_frames((ma_mp3*)pDataSource, pFramesOut, frameCount, pFramesRead);
  51703. }
  51704. static ma_result ma_mp3_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  51705. {
  51706. return ma_mp3_seek_to_pcm_frame((ma_mp3*)pDataSource, frameIndex);
  51707. }
  51708. 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)
  51709. {
  51710. return ma_mp3_get_data_format((ma_mp3*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  51711. }
  51712. static ma_result ma_mp3_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  51713. {
  51714. return ma_mp3_get_cursor_in_pcm_frames((ma_mp3*)pDataSource, pCursor);
  51715. }
  51716. static ma_result ma_mp3_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  51717. {
  51718. return ma_mp3_get_length_in_pcm_frames((ma_mp3*)pDataSource, pLength);
  51719. }
  51720. static ma_data_source_vtable g_ma_mp3_ds_vtable =
  51721. {
  51722. ma_mp3_ds_read,
  51723. ma_mp3_ds_seek,
  51724. ma_mp3_ds_get_data_format,
  51725. ma_mp3_ds_get_cursor,
  51726. ma_mp3_ds_get_length,
  51727. NULL, /* onSetLooping */
  51728. 0
  51729. };
  51730. #if !defined(MA_NO_MP3)
  51731. static size_t ma_mp3_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  51732. {
  51733. ma_mp3* pMP3 = (ma_mp3*)pUserData;
  51734. ma_result result;
  51735. size_t bytesRead;
  51736. MA_ASSERT(pMP3 != NULL);
  51737. result = pMP3->onRead(pMP3->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  51738. (void)result;
  51739. return bytesRead;
  51740. }
  51741. static ma_bool32 ma_mp3_dr_callback__seek(void* pUserData, int offset, ma_dr_mp3_seek_origin origin)
  51742. {
  51743. ma_mp3* pMP3 = (ma_mp3*)pUserData;
  51744. ma_result result;
  51745. ma_seek_origin maSeekOrigin;
  51746. MA_ASSERT(pMP3 != NULL);
  51747. maSeekOrigin = ma_seek_origin_start;
  51748. if (origin == ma_dr_mp3_seek_origin_current) {
  51749. maSeekOrigin = ma_seek_origin_current;
  51750. }
  51751. result = pMP3->onSeek(pMP3->pReadSeekTellUserData, offset, maSeekOrigin);
  51752. if (result != MA_SUCCESS) {
  51753. return MA_FALSE;
  51754. }
  51755. return MA_TRUE;
  51756. }
  51757. #endif
  51758. static ma_result ma_mp3_init_internal(const ma_decoding_backend_config* pConfig, ma_mp3* pMP3)
  51759. {
  51760. ma_result result;
  51761. ma_data_source_config dataSourceConfig;
  51762. if (pMP3 == NULL) {
  51763. return MA_INVALID_ARGS;
  51764. }
  51765. MA_ZERO_OBJECT(pMP3);
  51766. pMP3->format = ma_format_f32; /* f32 by default. */
  51767. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16)) {
  51768. pMP3->format = pConfig->preferredFormat;
  51769. } else {
  51770. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  51771. }
  51772. dataSourceConfig = ma_data_source_config_init();
  51773. dataSourceConfig.vtable = &g_ma_mp3_ds_vtable;
  51774. result = ma_data_source_init(&dataSourceConfig, &pMP3->ds);
  51775. if (result != MA_SUCCESS) {
  51776. return result; /* Failed to initialize the base data source. */
  51777. }
  51778. return MA_SUCCESS;
  51779. }
  51780. static ma_result ma_mp3_generate_seek_table(ma_mp3* pMP3, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks)
  51781. {
  51782. ma_bool32 mp3Result;
  51783. ma_uint32 seekPointCount = 0;
  51784. ma_dr_mp3_seek_point* pSeekPoints = NULL;
  51785. MA_ASSERT(pMP3 != NULL);
  51786. MA_ASSERT(pConfig != NULL);
  51787. seekPointCount = pConfig->seekPointCount;
  51788. if (seekPointCount > 0) {
  51789. pSeekPoints = (ma_dr_mp3_seek_point*)ma_malloc(sizeof(*pMP3->pSeekPoints) * seekPointCount, pAllocationCallbacks);
  51790. if (pSeekPoints == NULL) {
  51791. return MA_OUT_OF_MEMORY;
  51792. }
  51793. }
  51794. mp3Result = ma_dr_mp3_calculate_seek_points(&pMP3->dr, &seekPointCount, pSeekPoints);
  51795. if (mp3Result != MA_TRUE) {
  51796. ma_free(pSeekPoints, pAllocationCallbacks);
  51797. return MA_ERROR;
  51798. }
  51799. mp3Result = ma_dr_mp3_bind_seek_table(&pMP3->dr, seekPointCount, pSeekPoints);
  51800. if (mp3Result != MA_TRUE) {
  51801. ma_free(pSeekPoints, pAllocationCallbacks);
  51802. return MA_ERROR;
  51803. }
  51804. pMP3->seekPointCount = seekPointCount;
  51805. pMP3->pSeekPoints = pSeekPoints;
  51806. return MA_SUCCESS;
  51807. }
  51808. static ma_result ma_mp3_post_init(ma_mp3* pMP3, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks)
  51809. {
  51810. ma_result result;
  51811. result = ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  51812. if (result != MA_SUCCESS) {
  51813. return result;
  51814. }
  51815. return MA_SUCCESS;
  51816. }
  51817. 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)
  51818. {
  51819. ma_result result;
  51820. result = ma_mp3_init_internal(pConfig, pMP3);
  51821. if (result != MA_SUCCESS) {
  51822. return result;
  51823. }
  51824. if (onRead == NULL || onSeek == NULL) {
  51825. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  51826. }
  51827. pMP3->onRead = onRead;
  51828. pMP3->onSeek = onSeek;
  51829. pMP3->onTell = onTell;
  51830. pMP3->pReadSeekTellUserData = pReadSeekTellUserData;
  51831. #if !defined(MA_NO_MP3)
  51832. {
  51833. ma_bool32 mp3Result;
  51834. mp3Result = ma_dr_mp3_init(&pMP3->dr, ma_mp3_dr_callback__read, ma_mp3_dr_callback__seek, pMP3, pAllocationCallbacks);
  51835. if (mp3Result != MA_TRUE) {
  51836. return MA_INVALID_FILE;
  51837. }
  51838. ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks);
  51839. return MA_SUCCESS;
  51840. }
  51841. #else
  51842. {
  51843. /* mp3 is disabled. */
  51844. (void)pAllocationCallbacks;
  51845. return MA_NOT_IMPLEMENTED;
  51846. }
  51847. #endif
  51848. }
  51849. 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)
  51850. {
  51851. ma_result result;
  51852. result = ma_mp3_init_internal(pConfig, pMP3);
  51853. if (result != MA_SUCCESS) {
  51854. return result;
  51855. }
  51856. #if !defined(MA_NO_MP3)
  51857. {
  51858. ma_bool32 mp3Result;
  51859. mp3Result = ma_dr_mp3_init_file(&pMP3->dr, pFilePath, pAllocationCallbacks);
  51860. if (mp3Result != MA_TRUE) {
  51861. return MA_INVALID_FILE;
  51862. }
  51863. ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks);
  51864. return MA_SUCCESS;
  51865. }
  51866. #else
  51867. {
  51868. /* mp3 is disabled. */
  51869. (void)pFilePath;
  51870. (void)pAllocationCallbacks;
  51871. return MA_NOT_IMPLEMENTED;
  51872. }
  51873. #endif
  51874. }
  51875. 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)
  51876. {
  51877. ma_result result;
  51878. result = ma_mp3_init_internal(pConfig, pMP3);
  51879. if (result != MA_SUCCESS) {
  51880. return result;
  51881. }
  51882. #if !defined(MA_NO_MP3)
  51883. {
  51884. ma_bool32 mp3Result;
  51885. mp3Result = ma_dr_mp3_init_file_w(&pMP3->dr, pFilePath, pAllocationCallbacks);
  51886. if (mp3Result != MA_TRUE) {
  51887. return MA_INVALID_FILE;
  51888. }
  51889. ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks);
  51890. return MA_SUCCESS;
  51891. }
  51892. #else
  51893. {
  51894. /* mp3 is disabled. */
  51895. (void)pFilePath;
  51896. (void)pAllocationCallbacks;
  51897. return MA_NOT_IMPLEMENTED;
  51898. }
  51899. #endif
  51900. }
  51901. 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)
  51902. {
  51903. ma_result result;
  51904. result = ma_mp3_init_internal(pConfig, pMP3);
  51905. if (result != MA_SUCCESS) {
  51906. return result;
  51907. }
  51908. #if !defined(MA_NO_MP3)
  51909. {
  51910. ma_bool32 mp3Result;
  51911. mp3Result = ma_dr_mp3_init_memory(&pMP3->dr, pData, dataSize, pAllocationCallbacks);
  51912. if (mp3Result != MA_TRUE) {
  51913. return MA_INVALID_FILE;
  51914. }
  51915. ma_mp3_post_init(pMP3, pConfig, pAllocationCallbacks);
  51916. return MA_SUCCESS;
  51917. }
  51918. #else
  51919. {
  51920. /* mp3 is disabled. */
  51921. (void)pData;
  51922. (void)dataSize;
  51923. (void)pAllocationCallbacks;
  51924. return MA_NOT_IMPLEMENTED;
  51925. }
  51926. #endif
  51927. }
  51928. MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks)
  51929. {
  51930. if (pMP3 == NULL) {
  51931. return;
  51932. }
  51933. #if !defined(MA_NO_MP3)
  51934. {
  51935. ma_dr_mp3_uninit(&pMP3->dr);
  51936. }
  51937. #else
  51938. {
  51939. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  51940. MA_ASSERT(MA_FALSE);
  51941. }
  51942. #endif
  51943. /* Seek points need to be freed after the MP3 decoder has been uninitialized to ensure they're no longer being referenced. */
  51944. ma_free(pMP3->pSeekPoints, pAllocationCallbacks);
  51945. ma_data_source_uninit(&pMP3->ds);
  51946. }
  51947. MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51948. {
  51949. if (pFramesRead != NULL) {
  51950. *pFramesRead = 0;
  51951. }
  51952. if (frameCount == 0) {
  51953. return MA_INVALID_ARGS;
  51954. }
  51955. if (pMP3 == NULL) {
  51956. return MA_INVALID_ARGS;
  51957. }
  51958. #if !defined(MA_NO_MP3)
  51959. {
  51960. /* We always use floating point format. */
  51961. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  51962. ma_uint64 totalFramesRead = 0;
  51963. ma_format format;
  51964. ma_mp3_get_data_format(pMP3, &format, NULL, NULL, NULL, 0);
  51965. switch (format)
  51966. {
  51967. case ma_format_f32:
  51968. {
  51969. totalFramesRead = ma_dr_mp3_read_pcm_frames_f32(&pMP3->dr, frameCount, (float*)pFramesOut);
  51970. } break;
  51971. case ma_format_s16:
  51972. {
  51973. totalFramesRead = ma_dr_mp3_read_pcm_frames_s16(&pMP3->dr, frameCount, (ma_int16*)pFramesOut);
  51974. } break;
  51975. case ma_format_u8:
  51976. case ma_format_s24:
  51977. case ma_format_s32:
  51978. case ma_format_unknown:
  51979. default:
  51980. {
  51981. return MA_INVALID_OPERATION;
  51982. };
  51983. }
  51984. /* In the future we'll update ma_dr_mp3 to return MA_AT_END for us. */
  51985. if (totalFramesRead == 0) {
  51986. result = MA_AT_END;
  51987. }
  51988. if (pFramesRead != NULL) {
  51989. *pFramesRead = totalFramesRead;
  51990. }
  51991. return result;
  51992. }
  51993. #else
  51994. {
  51995. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  51996. MA_ASSERT(MA_FALSE);
  51997. (void)pFramesOut;
  51998. (void)frameCount;
  51999. (void)pFramesRead;
  52000. return MA_NOT_IMPLEMENTED;
  52001. }
  52002. #endif
  52003. }
  52004. MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex)
  52005. {
  52006. if (pMP3 == NULL) {
  52007. return MA_INVALID_ARGS;
  52008. }
  52009. #if !defined(MA_NO_MP3)
  52010. {
  52011. ma_bool32 mp3Result;
  52012. mp3Result = ma_dr_mp3_seek_to_pcm_frame(&pMP3->dr, frameIndex);
  52013. if (mp3Result != MA_TRUE) {
  52014. return MA_ERROR;
  52015. }
  52016. return MA_SUCCESS;
  52017. }
  52018. #else
  52019. {
  52020. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52021. MA_ASSERT(MA_FALSE);
  52022. (void)frameIndex;
  52023. return MA_NOT_IMPLEMENTED;
  52024. }
  52025. #endif
  52026. }
  52027. 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)
  52028. {
  52029. /* Defaults for safety. */
  52030. if (pFormat != NULL) {
  52031. *pFormat = ma_format_unknown;
  52032. }
  52033. if (pChannels != NULL) {
  52034. *pChannels = 0;
  52035. }
  52036. if (pSampleRate != NULL) {
  52037. *pSampleRate = 0;
  52038. }
  52039. if (pChannelMap != NULL) {
  52040. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  52041. }
  52042. if (pMP3 == NULL) {
  52043. return MA_INVALID_OPERATION;
  52044. }
  52045. if (pFormat != NULL) {
  52046. *pFormat = pMP3->format;
  52047. }
  52048. #if !defined(MA_NO_MP3)
  52049. {
  52050. if (pChannels != NULL) {
  52051. *pChannels = pMP3->dr.channels;
  52052. }
  52053. if (pSampleRate != NULL) {
  52054. *pSampleRate = pMP3->dr.sampleRate;
  52055. }
  52056. if (pChannelMap != NULL) {
  52057. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pMP3->dr.channels);
  52058. }
  52059. return MA_SUCCESS;
  52060. }
  52061. #else
  52062. {
  52063. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52064. MA_ASSERT(MA_FALSE);
  52065. return MA_NOT_IMPLEMENTED;
  52066. }
  52067. #endif
  52068. }
  52069. MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor)
  52070. {
  52071. if (pCursor == NULL) {
  52072. return MA_INVALID_ARGS;
  52073. }
  52074. *pCursor = 0; /* Safety. */
  52075. if (pMP3 == NULL) {
  52076. return MA_INVALID_ARGS;
  52077. }
  52078. #if !defined(MA_NO_MP3)
  52079. {
  52080. *pCursor = pMP3->dr.currentPCMFrame;
  52081. return MA_SUCCESS;
  52082. }
  52083. #else
  52084. {
  52085. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52086. MA_ASSERT(MA_FALSE);
  52087. return MA_NOT_IMPLEMENTED;
  52088. }
  52089. #endif
  52090. }
  52091. MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength)
  52092. {
  52093. if (pLength == NULL) {
  52094. return MA_INVALID_ARGS;
  52095. }
  52096. *pLength = 0; /* Safety. */
  52097. if (pMP3 == NULL) {
  52098. return MA_INVALID_ARGS;
  52099. }
  52100. #if !defined(MA_NO_MP3)
  52101. {
  52102. *pLength = ma_dr_mp3_get_pcm_frame_count(&pMP3->dr);
  52103. return MA_SUCCESS;
  52104. }
  52105. #else
  52106. {
  52107. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  52108. MA_ASSERT(MA_FALSE);
  52109. return MA_NOT_IMPLEMENTED;
  52110. }
  52111. #endif
  52112. }
  52113. 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)
  52114. {
  52115. ma_result result;
  52116. ma_mp3* pMP3;
  52117. (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. */
  52118. /* For now we're just allocating the decoder backend on the heap. */
  52119. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52120. if (pMP3 == NULL) {
  52121. return MA_OUT_OF_MEMORY;
  52122. }
  52123. result = ma_mp3_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pMP3);
  52124. if (result != MA_SUCCESS) {
  52125. ma_free(pMP3, pAllocationCallbacks);
  52126. return result;
  52127. }
  52128. *ppBackend = pMP3;
  52129. return MA_SUCCESS;
  52130. }
  52131. 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)
  52132. {
  52133. ma_result result;
  52134. ma_mp3* pMP3;
  52135. (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. */
  52136. /* For now we're just allocating the decoder backend on the heap. */
  52137. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52138. if (pMP3 == NULL) {
  52139. return MA_OUT_OF_MEMORY;
  52140. }
  52141. result = ma_mp3_init_file(pFilePath, pConfig, pAllocationCallbacks, pMP3);
  52142. if (result != MA_SUCCESS) {
  52143. ma_free(pMP3, pAllocationCallbacks);
  52144. return result;
  52145. }
  52146. *ppBackend = pMP3;
  52147. return MA_SUCCESS;
  52148. }
  52149. 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)
  52150. {
  52151. ma_result result;
  52152. ma_mp3* pMP3;
  52153. (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. */
  52154. /* For now we're just allocating the decoder backend on the heap. */
  52155. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52156. if (pMP3 == NULL) {
  52157. return MA_OUT_OF_MEMORY;
  52158. }
  52159. result = ma_mp3_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pMP3);
  52160. if (result != MA_SUCCESS) {
  52161. ma_free(pMP3, pAllocationCallbacks);
  52162. return result;
  52163. }
  52164. *ppBackend = pMP3;
  52165. return MA_SUCCESS;
  52166. }
  52167. 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)
  52168. {
  52169. ma_result result;
  52170. ma_mp3* pMP3;
  52171. (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. */
  52172. /* For now we're just allocating the decoder backend on the heap. */
  52173. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  52174. if (pMP3 == NULL) {
  52175. return MA_OUT_OF_MEMORY;
  52176. }
  52177. result = ma_mp3_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pMP3);
  52178. if (result != MA_SUCCESS) {
  52179. ma_free(pMP3, pAllocationCallbacks);
  52180. return result;
  52181. }
  52182. *ppBackend = pMP3;
  52183. return MA_SUCCESS;
  52184. }
  52185. static void ma_decoding_backend_uninit__mp3(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  52186. {
  52187. ma_mp3* pMP3 = (ma_mp3*)pBackend;
  52188. (void)pUserData;
  52189. ma_mp3_uninit(pMP3, pAllocationCallbacks);
  52190. ma_free(pMP3, pAllocationCallbacks);
  52191. }
  52192. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_mp3 =
  52193. {
  52194. ma_decoding_backend_init__mp3,
  52195. ma_decoding_backend_init_file__mp3,
  52196. ma_decoding_backend_init_file_w__mp3,
  52197. ma_decoding_backend_init_memory__mp3,
  52198. ma_decoding_backend_uninit__mp3
  52199. };
  52200. static ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52201. {
  52202. return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pConfig, pDecoder);
  52203. }
  52204. static ma_result ma_decoder_init_mp3_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52205. {
  52206. return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pFilePath, pConfig, pDecoder);
  52207. }
  52208. static ma_result ma_decoder_init_mp3_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52209. {
  52210. return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pFilePath, pConfig, pDecoder);
  52211. }
  52212. static ma_result ma_decoder_init_mp3_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52213. {
  52214. return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_mp3, NULL, pData, dataSize, pConfig, pDecoder);
  52215. }
  52216. #endif /* ma_dr_mp3_h */
  52217. /* Vorbis */
  52218. #ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H
  52219. #define MA_HAS_VORBIS
  52220. /* The size in bytes of each chunk of data to read from the Vorbis stream. */
  52221. #define MA_VORBIS_DATA_CHUNK_SIZE 4096
  52222. typedef struct
  52223. {
  52224. ma_data_source_base ds;
  52225. ma_read_proc onRead;
  52226. ma_seek_proc onSeek;
  52227. ma_tell_proc onTell;
  52228. void* pReadSeekTellUserData;
  52229. 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. */
  52230. ma_format format; /* Only f32 is allowed with stb_vorbis. */
  52231. ma_uint32 channels;
  52232. ma_uint32 sampleRate;
  52233. ma_uint64 cursor;
  52234. #if !defined(MA_NO_VORBIS)
  52235. stb_vorbis* stb;
  52236. ma_bool32 usingPushMode;
  52237. struct
  52238. {
  52239. ma_uint8* pData;
  52240. size_t dataSize;
  52241. size_t dataCapacity;
  52242. size_t audioStartOffsetInBytes;
  52243. ma_uint32 framesConsumed; /* The number of frames consumed in ppPacketData. */
  52244. ma_uint32 framesRemaining; /* The number of frames remaining in ppPacketData. */
  52245. float** ppPacketData;
  52246. } push;
  52247. #endif
  52248. } ma_stbvorbis;
  52249. 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);
  52250. 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);
  52251. 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);
  52252. MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks);
  52253. MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  52254. MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex);
  52255. 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);
  52256. MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor);
  52257. MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength);
  52258. static ma_result ma_stbvorbis_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52259. {
  52260. return ma_stbvorbis_read_pcm_frames((ma_stbvorbis*)pDataSource, pFramesOut, frameCount, pFramesRead);
  52261. }
  52262. static ma_result ma_stbvorbis_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  52263. {
  52264. return ma_stbvorbis_seek_to_pcm_frame((ma_stbvorbis*)pDataSource, frameIndex);
  52265. }
  52266. 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)
  52267. {
  52268. return ma_stbvorbis_get_data_format((ma_stbvorbis*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  52269. }
  52270. static ma_result ma_stbvorbis_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  52271. {
  52272. return ma_stbvorbis_get_cursor_in_pcm_frames((ma_stbvorbis*)pDataSource, pCursor);
  52273. }
  52274. static ma_result ma_stbvorbis_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  52275. {
  52276. return ma_stbvorbis_get_length_in_pcm_frames((ma_stbvorbis*)pDataSource, pLength);
  52277. }
  52278. static ma_data_source_vtable g_ma_stbvorbis_ds_vtable =
  52279. {
  52280. ma_stbvorbis_ds_read,
  52281. ma_stbvorbis_ds_seek,
  52282. ma_stbvorbis_ds_get_data_format,
  52283. ma_stbvorbis_ds_get_cursor,
  52284. ma_stbvorbis_ds_get_length,
  52285. NULL, /* onSetLooping */
  52286. 0
  52287. };
  52288. static ma_result ma_stbvorbis_init_internal(const ma_decoding_backend_config* pConfig, ma_stbvorbis* pVorbis)
  52289. {
  52290. ma_result result;
  52291. ma_data_source_config dataSourceConfig;
  52292. (void)pConfig;
  52293. if (pVorbis == NULL) {
  52294. return MA_INVALID_ARGS;
  52295. }
  52296. MA_ZERO_OBJECT(pVorbis);
  52297. pVorbis->format = ma_format_f32; /* Only supporting f32. */
  52298. dataSourceConfig = ma_data_source_config_init();
  52299. dataSourceConfig.vtable = &g_ma_stbvorbis_ds_vtable;
  52300. result = ma_data_source_init(&dataSourceConfig, &pVorbis->ds);
  52301. if (result != MA_SUCCESS) {
  52302. return result; /* Failed to initialize the base data source. */
  52303. }
  52304. return MA_SUCCESS;
  52305. }
  52306. #if !defined(MA_NO_VORBIS)
  52307. static ma_result ma_stbvorbis_post_init(ma_stbvorbis* pVorbis)
  52308. {
  52309. stb_vorbis_info info;
  52310. MA_ASSERT(pVorbis != NULL);
  52311. info = stb_vorbis_get_info(pVorbis->stb);
  52312. pVorbis->channels = info.channels;
  52313. pVorbis->sampleRate = info.sample_rate;
  52314. return MA_SUCCESS;
  52315. }
  52316. static ma_result ma_stbvorbis_init_internal_decoder_push(ma_stbvorbis* pVorbis)
  52317. {
  52318. ma_result result;
  52319. stb_vorbis* stb;
  52320. size_t dataSize = 0;
  52321. size_t dataCapacity = 0;
  52322. ma_uint8* pData = NULL; /* <-- Must be initialized to NULL. */
  52323. for (;;) {
  52324. int vorbisError;
  52325. int consumedDataSize; /* <-- Fill by stb_vorbis_open_pushdata(). */
  52326. size_t bytesRead;
  52327. ma_uint8* pNewData;
  52328. /* Allocate memory for the new chunk. */
  52329. dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE;
  52330. pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity, &pVorbis->allocationCallbacks);
  52331. if (pNewData == NULL) {
  52332. ma_free(pData, &pVorbis->allocationCallbacks);
  52333. return MA_OUT_OF_MEMORY;
  52334. }
  52335. pData = pNewData;
  52336. /* Read in the next chunk. */
  52337. result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pData, dataSize), (dataCapacity - dataSize), &bytesRead);
  52338. dataSize += bytesRead;
  52339. if (result != MA_SUCCESS) {
  52340. ma_free(pData, &pVorbis->allocationCallbacks);
  52341. return result;
  52342. }
  52343. /* We have a maximum of 31 bits with stb_vorbis. */
  52344. if (dataSize > INT_MAX) {
  52345. ma_free(pData, &pVorbis->allocationCallbacks);
  52346. return MA_TOO_BIG;
  52347. }
  52348. stb = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL);
  52349. if (stb != NULL) {
  52350. /*
  52351. Successfully opened the Vorbis decoder. We might have some leftover unprocessed
  52352. data so we'll need to move that down to the front.
  52353. */
  52354. dataSize -= (size_t)consumedDataSize; /* Consume the data. */
  52355. MA_MOVE_MEMORY(pData, ma_offset_ptr(pData, consumedDataSize), dataSize);
  52356. /*
  52357. We need to track the start point so we can seek back to the start of the audio
  52358. data when seeking.
  52359. */
  52360. pVorbis->push.audioStartOffsetInBytes = consumedDataSize;
  52361. break;
  52362. } else {
  52363. /* Failed to open the decoder. */
  52364. if (vorbisError == VORBIS_need_more_data) {
  52365. continue;
  52366. } else {
  52367. ma_free(pData, &pVorbis->allocationCallbacks);
  52368. return MA_ERROR; /* Failed to open the stb_vorbis decoder. */
  52369. }
  52370. }
  52371. }
  52372. MA_ASSERT(stb != NULL);
  52373. pVorbis->stb = stb;
  52374. pVorbis->push.pData = pData;
  52375. pVorbis->push.dataSize = dataSize;
  52376. pVorbis->push.dataCapacity = dataCapacity;
  52377. return MA_SUCCESS;
  52378. }
  52379. #endif
  52380. 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)
  52381. {
  52382. ma_result result;
  52383. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  52384. if (result != MA_SUCCESS) {
  52385. return result;
  52386. }
  52387. if (onRead == NULL || onSeek == NULL) {
  52388. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  52389. }
  52390. pVorbis->onRead = onRead;
  52391. pVorbis->onSeek = onSeek;
  52392. pVorbis->onTell = onTell;
  52393. pVorbis->pReadSeekTellUserData = pReadSeekTellUserData;
  52394. ma_allocation_callbacks_init_copy(&pVorbis->allocationCallbacks, pAllocationCallbacks);
  52395. #if !defined(MA_NO_VORBIS)
  52396. {
  52397. /*
  52398. stb_vorbis lacks a callback based API for it's pulling API which means we're stuck with the
  52399. pushing API. In order for us to be able to successfully initialize the decoder we need to
  52400. supply it with enough data. We need to keep loading data until we have enough.
  52401. */
  52402. result = ma_stbvorbis_init_internal_decoder_push(pVorbis);
  52403. if (result != MA_SUCCESS) {
  52404. return result;
  52405. }
  52406. pVorbis->usingPushMode = MA_TRUE;
  52407. result = ma_stbvorbis_post_init(pVorbis);
  52408. if (result != MA_SUCCESS) {
  52409. stb_vorbis_close(pVorbis->stb);
  52410. ma_free(pVorbis->push.pData, pAllocationCallbacks);
  52411. return result;
  52412. }
  52413. return MA_SUCCESS;
  52414. }
  52415. #else
  52416. {
  52417. /* vorbis is disabled. */
  52418. (void)pAllocationCallbacks;
  52419. return MA_NOT_IMPLEMENTED;
  52420. }
  52421. #endif
  52422. }
  52423. 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)
  52424. {
  52425. ma_result result;
  52426. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  52427. if (result != MA_SUCCESS) {
  52428. return result;
  52429. }
  52430. #if !defined(MA_NO_VORBIS)
  52431. {
  52432. (void)pAllocationCallbacks; /* Don't know how to make use of this with stb_vorbis. */
  52433. /* We can use stb_vorbis' pull mode for file based streams. */
  52434. pVorbis->stb = stb_vorbis_open_filename(pFilePath, NULL, NULL);
  52435. if (pVorbis->stb == NULL) {
  52436. return MA_INVALID_FILE;
  52437. }
  52438. pVorbis->usingPushMode = MA_FALSE;
  52439. result = ma_stbvorbis_post_init(pVorbis);
  52440. if (result != MA_SUCCESS) {
  52441. stb_vorbis_close(pVorbis->stb);
  52442. return result;
  52443. }
  52444. return MA_SUCCESS;
  52445. }
  52446. #else
  52447. {
  52448. /* vorbis is disabled. */
  52449. (void)pFilePath;
  52450. (void)pAllocationCallbacks;
  52451. return MA_NOT_IMPLEMENTED;
  52452. }
  52453. #endif
  52454. }
  52455. 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)
  52456. {
  52457. ma_result result;
  52458. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  52459. if (result != MA_SUCCESS) {
  52460. return result;
  52461. }
  52462. #if !defined(MA_NO_VORBIS)
  52463. {
  52464. (void)pAllocationCallbacks;
  52465. /* stb_vorbis uses an int as it's size specifier, restricting it to 32-bit even on 64-bit systems. *sigh*. */
  52466. if (dataSize > INT_MAX) {
  52467. return MA_TOO_BIG;
  52468. }
  52469. pVorbis->stb = stb_vorbis_open_memory((const unsigned char*)pData, (int)dataSize, NULL, NULL);
  52470. if (pVorbis->stb == NULL) {
  52471. return MA_INVALID_FILE;
  52472. }
  52473. pVorbis->usingPushMode = MA_FALSE;
  52474. result = ma_stbvorbis_post_init(pVorbis);
  52475. if (result != MA_SUCCESS) {
  52476. stb_vorbis_close(pVorbis->stb);
  52477. return result;
  52478. }
  52479. return MA_SUCCESS;
  52480. }
  52481. #else
  52482. {
  52483. /* vorbis is disabled. */
  52484. (void)pData;
  52485. (void)dataSize;
  52486. (void)pAllocationCallbacks;
  52487. return MA_NOT_IMPLEMENTED;
  52488. }
  52489. #endif
  52490. }
  52491. MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks)
  52492. {
  52493. if (pVorbis == NULL) {
  52494. return;
  52495. }
  52496. #if !defined(MA_NO_VORBIS)
  52497. {
  52498. stb_vorbis_close(pVorbis->stb);
  52499. /* We'll have to clear some memory if we're using push mode. */
  52500. if (pVorbis->usingPushMode) {
  52501. ma_free(pVorbis->push.pData, pAllocationCallbacks);
  52502. }
  52503. }
  52504. #else
  52505. {
  52506. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52507. MA_ASSERT(MA_FALSE);
  52508. }
  52509. #endif
  52510. ma_data_source_uninit(&pVorbis->ds);
  52511. }
  52512. MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52513. {
  52514. if (pFramesRead != NULL) {
  52515. *pFramesRead = 0;
  52516. }
  52517. if (frameCount == 0) {
  52518. return MA_INVALID_ARGS;
  52519. }
  52520. if (pVorbis == NULL) {
  52521. return MA_INVALID_ARGS;
  52522. }
  52523. #if !defined(MA_NO_VORBIS)
  52524. {
  52525. /* We always use floating point format. */
  52526. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  52527. ma_uint64 totalFramesRead = 0;
  52528. ma_format format;
  52529. ma_uint32 channels;
  52530. ma_stbvorbis_get_data_format(pVorbis, &format, &channels, NULL, NULL, 0);
  52531. if (format == ma_format_f32) {
  52532. /* We read differently depending on whether or not we're using push mode. */
  52533. if (pVorbis->usingPushMode) {
  52534. /* Push mode. This is the complex case. */
  52535. float* pFramesOutF32 = (float*)pFramesOut;
  52536. while (totalFramesRead < frameCount) {
  52537. /* The first thing to do is read from any already-cached frames. */
  52538. ma_uint32 framesToReadFromCache = (ma_uint32)ma_min(pVorbis->push.framesRemaining, (frameCount - totalFramesRead)); /* Safe cast because pVorbis->framesRemaining is 32-bit. */
  52539. /* The output pointer can be null in which case we just treate it as a seek. */
  52540. if (pFramesOut != NULL) {
  52541. ma_uint64 iFrame;
  52542. for (iFrame = 0; iFrame < framesToReadFromCache; iFrame += 1) {
  52543. ma_uint32 iChannel;
  52544. for (iChannel = 0; iChannel < pVorbis->channels; iChannel += 1) {
  52545. pFramesOutF32[iChannel] = pVorbis->push.ppPacketData[iChannel][pVorbis->push.framesConsumed + iFrame];
  52546. }
  52547. pFramesOutF32 += pVorbis->channels;
  52548. }
  52549. }
  52550. /* Update pointers and counters. */
  52551. pVorbis->push.framesConsumed += framesToReadFromCache;
  52552. pVorbis->push.framesRemaining -= framesToReadFromCache;
  52553. totalFramesRead += framesToReadFromCache;
  52554. /* Don't bother reading any more frames right now if we've just finished loading. */
  52555. if (totalFramesRead == frameCount) {
  52556. break;
  52557. }
  52558. MA_ASSERT(pVorbis->push.framesRemaining == 0);
  52559. /* Getting here means we've run out of cached frames. We'll need to load some more. */
  52560. for (;;) {
  52561. int samplesRead = 0;
  52562. int consumedDataSize;
  52563. /* We need to case dataSize to an int, so make sure we can do it safely. */
  52564. if (pVorbis->push.dataSize > INT_MAX) {
  52565. break; /* Too big. */
  52566. }
  52567. consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->stb, pVorbis->push.pData, (int)pVorbis->push.dataSize, NULL, &pVorbis->push.ppPacketData, &samplesRead);
  52568. if (consumedDataSize != 0) {
  52569. /* Successfully decoded a Vorbis frame. Consume the data. */
  52570. pVorbis->push.dataSize -= (size_t)consumedDataSize;
  52571. MA_MOVE_MEMORY(pVorbis->push.pData, ma_offset_ptr(pVorbis->push.pData, consumedDataSize), pVorbis->push.dataSize);
  52572. pVorbis->push.framesConsumed = 0;
  52573. pVorbis->push.framesRemaining = samplesRead;
  52574. break;
  52575. } else {
  52576. /* Not enough data. Read more. */
  52577. size_t bytesRead;
  52578. /* Expand the data buffer if necessary. */
  52579. if (pVorbis->push.dataCapacity == pVorbis->push.dataSize) {
  52580. size_t newCap = pVorbis->push.dataCapacity + MA_VORBIS_DATA_CHUNK_SIZE;
  52581. ma_uint8* pNewData;
  52582. pNewData = (ma_uint8*)ma_realloc(pVorbis->push.pData, newCap, &pVorbis->allocationCallbacks);
  52583. if (pNewData == NULL) {
  52584. result = MA_OUT_OF_MEMORY;
  52585. break;
  52586. }
  52587. pVorbis->push.pData = pNewData;
  52588. pVorbis->push.dataCapacity = newCap;
  52589. }
  52590. /* We should have enough room to load some data. */
  52591. result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pVorbis->push.pData, pVorbis->push.dataSize), (pVorbis->push.dataCapacity - pVorbis->push.dataSize), &bytesRead);
  52592. pVorbis->push.dataSize += bytesRead;
  52593. if (result != MA_SUCCESS) {
  52594. break; /* Failed to read any data. Get out. */
  52595. }
  52596. }
  52597. }
  52598. /* 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). */
  52599. if (result != MA_SUCCESS) {
  52600. break;
  52601. }
  52602. }
  52603. } else {
  52604. /* 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. */
  52605. while (totalFramesRead < frameCount) {
  52606. ma_uint64 framesRemaining = (frameCount - totalFramesRead);
  52607. int framesRead;
  52608. if (framesRemaining > INT_MAX) {
  52609. framesRemaining = INT_MAX;
  52610. }
  52611. 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. */
  52612. totalFramesRead += framesRead;
  52613. if (framesRead < (int)framesRemaining) {
  52614. break; /* Nothing left to read. Get out. */
  52615. }
  52616. }
  52617. }
  52618. } else {
  52619. result = MA_INVALID_ARGS;
  52620. }
  52621. pVorbis->cursor += totalFramesRead;
  52622. if (totalFramesRead == 0) {
  52623. result = MA_AT_END;
  52624. }
  52625. if (pFramesRead != NULL) {
  52626. *pFramesRead = totalFramesRead;
  52627. }
  52628. if (result == MA_SUCCESS && totalFramesRead == 0) {
  52629. result = MA_AT_END;
  52630. }
  52631. return result;
  52632. }
  52633. #else
  52634. {
  52635. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52636. MA_ASSERT(MA_FALSE);
  52637. (void)pFramesOut;
  52638. (void)frameCount;
  52639. (void)pFramesRead;
  52640. return MA_NOT_IMPLEMENTED;
  52641. }
  52642. #endif
  52643. }
  52644. MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex)
  52645. {
  52646. if (pVorbis == NULL) {
  52647. return MA_INVALID_ARGS;
  52648. }
  52649. #if !defined(MA_NO_VORBIS)
  52650. {
  52651. /* Different seeking methods depending on whether or not we're using push mode. */
  52652. if (pVorbis->usingPushMode) {
  52653. /* Push mode. This is the complex case. */
  52654. ma_result result;
  52655. float buffer[4096];
  52656. /* If we're seeking backwards, we need to seek back to the start and then brute-force forward. */
  52657. if (frameIndex < pVorbis->cursor) {
  52658. if (frameIndex > 0x7FFFFFFF) {
  52659. return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */
  52660. }
  52661. /*
  52662. This is wildly inefficient due to me having trouble getting sample exact seeking working
  52663. robustly with stb_vorbis_flush_pushdata(). The only way I can think to make this work
  52664. perfectly is to reinitialize the decoder. Note that we only enter this path when seeking
  52665. backwards. This will hopefully be removed once we get our own Vorbis decoder implemented.
  52666. */
  52667. stb_vorbis_close(pVorbis->stb);
  52668. ma_free(pVorbis->push.pData, &pVorbis->allocationCallbacks);
  52669. MA_ZERO_OBJECT(&pVorbis->push);
  52670. /* Seek to the start of the file. */
  52671. result = pVorbis->onSeek(pVorbis->pReadSeekTellUserData, 0, ma_seek_origin_start);
  52672. if (result != MA_SUCCESS) {
  52673. return result;
  52674. }
  52675. result = ma_stbvorbis_init_internal_decoder_push(pVorbis);
  52676. if (result != MA_SUCCESS) {
  52677. return result;
  52678. }
  52679. /* At this point we should be sitting on the first frame. */
  52680. pVorbis->cursor = 0;
  52681. }
  52682. /* We're just brute-forcing this for now. */
  52683. while (pVorbis->cursor < frameIndex) {
  52684. ma_uint64 framesRead;
  52685. ma_uint64 framesToRead = ma_countof(buffer)/pVorbis->channels;
  52686. if (framesToRead > (frameIndex - pVorbis->cursor)) {
  52687. framesToRead = (frameIndex - pVorbis->cursor);
  52688. }
  52689. result = ma_stbvorbis_read_pcm_frames(pVorbis, buffer, framesToRead, &framesRead);
  52690. if (result != MA_SUCCESS) {
  52691. return result;
  52692. }
  52693. }
  52694. } else {
  52695. /* Pull mode. This is the simple case. */
  52696. int vorbisResult;
  52697. if (frameIndex > UINT_MAX) {
  52698. return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */
  52699. }
  52700. vorbisResult = stb_vorbis_seek(pVorbis->stb, (unsigned int)frameIndex); /* Safe cast. */
  52701. if (vorbisResult == 0) {
  52702. return MA_ERROR; /* See failed. */
  52703. }
  52704. pVorbis->cursor = frameIndex;
  52705. }
  52706. return MA_SUCCESS;
  52707. }
  52708. #else
  52709. {
  52710. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52711. MA_ASSERT(MA_FALSE);
  52712. (void)frameIndex;
  52713. return MA_NOT_IMPLEMENTED;
  52714. }
  52715. #endif
  52716. }
  52717. 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)
  52718. {
  52719. /* Defaults for safety. */
  52720. if (pFormat != NULL) {
  52721. *pFormat = ma_format_unknown;
  52722. }
  52723. if (pChannels != NULL) {
  52724. *pChannels = 0;
  52725. }
  52726. if (pSampleRate != NULL) {
  52727. *pSampleRate = 0;
  52728. }
  52729. if (pChannelMap != NULL) {
  52730. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  52731. }
  52732. if (pVorbis == NULL) {
  52733. return MA_INVALID_OPERATION;
  52734. }
  52735. if (pFormat != NULL) {
  52736. *pFormat = pVorbis->format;
  52737. }
  52738. #if !defined(MA_NO_VORBIS)
  52739. {
  52740. if (pChannels != NULL) {
  52741. *pChannels = pVorbis->channels;
  52742. }
  52743. if (pSampleRate != NULL) {
  52744. *pSampleRate = pVorbis->sampleRate;
  52745. }
  52746. if (pChannelMap != NULL) {
  52747. ma_channel_map_init_standard(ma_standard_channel_map_vorbis, pChannelMap, channelMapCap, pVorbis->channels);
  52748. }
  52749. return MA_SUCCESS;
  52750. }
  52751. #else
  52752. {
  52753. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52754. MA_ASSERT(MA_FALSE);
  52755. return MA_NOT_IMPLEMENTED;
  52756. }
  52757. #endif
  52758. }
  52759. MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor)
  52760. {
  52761. if (pCursor == NULL) {
  52762. return MA_INVALID_ARGS;
  52763. }
  52764. *pCursor = 0; /* Safety. */
  52765. if (pVorbis == NULL) {
  52766. return MA_INVALID_ARGS;
  52767. }
  52768. #if !defined(MA_NO_VORBIS)
  52769. {
  52770. *pCursor = pVorbis->cursor;
  52771. return MA_SUCCESS;
  52772. }
  52773. #else
  52774. {
  52775. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52776. MA_ASSERT(MA_FALSE);
  52777. return MA_NOT_IMPLEMENTED;
  52778. }
  52779. #endif
  52780. }
  52781. MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength)
  52782. {
  52783. if (pLength == NULL) {
  52784. return MA_INVALID_ARGS;
  52785. }
  52786. *pLength = 0; /* Safety. */
  52787. if (pVorbis == NULL) {
  52788. return MA_INVALID_ARGS;
  52789. }
  52790. #if !defined(MA_NO_VORBIS)
  52791. {
  52792. if (pVorbis->usingPushMode) {
  52793. *pLength = 0; /* I don't know of a good way to determine this reliably with stb_vorbis and push mode. */
  52794. } else {
  52795. *pLength = stb_vorbis_stream_length_in_samples(pVorbis->stb);
  52796. }
  52797. return MA_SUCCESS;
  52798. }
  52799. #else
  52800. {
  52801. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  52802. MA_ASSERT(MA_FALSE);
  52803. return MA_NOT_IMPLEMENTED;
  52804. }
  52805. #endif
  52806. }
  52807. 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)
  52808. {
  52809. ma_result result;
  52810. ma_stbvorbis* pVorbis;
  52811. (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. */
  52812. /* For now we're just allocating the decoder backend on the heap. */
  52813. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  52814. if (pVorbis == NULL) {
  52815. return MA_OUT_OF_MEMORY;
  52816. }
  52817. result = ma_stbvorbis_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pVorbis);
  52818. if (result != MA_SUCCESS) {
  52819. ma_free(pVorbis, pAllocationCallbacks);
  52820. return result;
  52821. }
  52822. *ppBackend = pVorbis;
  52823. return MA_SUCCESS;
  52824. }
  52825. 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)
  52826. {
  52827. ma_result result;
  52828. ma_stbvorbis* pVorbis;
  52829. (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. */
  52830. /* For now we're just allocating the decoder backend on the heap. */
  52831. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  52832. if (pVorbis == NULL) {
  52833. return MA_OUT_OF_MEMORY;
  52834. }
  52835. result = ma_stbvorbis_init_file(pFilePath, pConfig, pAllocationCallbacks, pVorbis);
  52836. if (result != MA_SUCCESS) {
  52837. ma_free(pVorbis, pAllocationCallbacks);
  52838. return result;
  52839. }
  52840. *ppBackend = pVorbis;
  52841. return MA_SUCCESS;
  52842. }
  52843. 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)
  52844. {
  52845. ma_result result;
  52846. ma_stbvorbis* pVorbis;
  52847. (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. */
  52848. /* For now we're just allocating the decoder backend on the heap. */
  52849. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  52850. if (pVorbis == NULL) {
  52851. return MA_OUT_OF_MEMORY;
  52852. }
  52853. result = ma_stbvorbis_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pVorbis);
  52854. if (result != MA_SUCCESS) {
  52855. ma_free(pVorbis, pAllocationCallbacks);
  52856. return result;
  52857. }
  52858. *ppBackend = pVorbis;
  52859. return MA_SUCCESS;
  52860. }
  52861. static void ma_decoding_backend_uninit__stbvorbis(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  52862. {
  52863. ma_stbvorbis* pVorbis = (ma_stbvorbis*)pBackend;
  52864. (void)pUserData;
  52865. ma_stbvorbis_uninit(pVorbis, pAllocationCallbacks);
  52866. ma_free(pVorbis, pAllocationCallbacks);
  52867. }
  52868. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_stbvorbis =
  52869. {
  52870. ma_decoding_backend_init__stbvorbis,
  52871. ma_decoding_backend_init_file__stbvorbis,
  52872. NULL, /* onInitFileW() */
  52873. ma_decoding_backend_init_memory__stbvorbis,
  52874. ma_decoding_backend_uninit__stbvorbis
  52875. };
  52876. static ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52877. {
  52878. return ma_decoder_init_from_vtable__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pConfig, pDecoder);
  52879. }
  52880. static ma_result ma_decoder_init_vorbis_from_file__internal(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52881. {
  52882. return ma_decoder_init_from_file__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pFilePath, pConfig, pDecoder);
  52883. }
  52884. static ma_result ma_decoder_init_vorbis_from_file_w__internal(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52885. {
  52886. return ma_decoder_init_from_file_w__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pFilePath, pConfig, pDecoder);
  52887. }
  52888. static ma_result ma_decoder_init_vorbis_from_memory__internal(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52889. {
  52890. return ma_decoder_init_from_memory__internal(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pData, dataSize, pConfig, pDecoder);
  52891. }
  52892. #endif /* STB_VORBIS_INCLUDE_STB_VORBIS_H */
  52893. static ma_result ma_decoder__init_allocation_callbacks(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52894. {
  52895. MA_ASSERT(pDecoder != NULL);
  52896. if (pConfig != NULL) {
  52897. return ma_allocation_callbacks_init_copy(&pDecoder->allocationCallbacks, &pConfig->allocationCallbacks);
  52898. } else {
  52899. pDecoder->allocationCallbacks = ma_allocation_callbacks_init_default();
  52900. return MA_SUCCESS;
  52901. }
  52902. }
  52903. static ma_result ma_decoder__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52904. {
  52905. return ma_decoder_read_pcm_frames((ma_decoder*)pDataSource, pFramesOut, frameCount, pFramesRead);
  52906. }
  52907. static ma_result ma_decoder__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  52908. {
  52909. return ma_decoder_seek_to_pcm_frame((ma_decoder*)pDataSource, frameIndex);
  52910. }
  52911. 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)
  52912. {
  52913. return ma_decoder_get_data_format((ma_decoder*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  52914. }
  52915. static ma_result ma_decoder__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  52916. {
  52917. return ma_decoder_get_cursor_in_pcm_frames((ma_decoder*)pDataSource, pCursor);
  52918. }
  52919. static ma_result ma_decoder__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  52920. {
  52921. return ma_decoder_get_length_in_pcm_frames((ma_decoder*)pDataSource, pLength);
  52922. }
  52923. static ma_data_source_vtable g_ma_decoder_data_source_vtable =
  52924. {
  52925. ma_decoder__data_source_on_read,
  52926. ma_decoder__data_source_on_seek,
  52927. ma_decoder__data_source_on_get_data_format,
  52928. ma_decoder__data_source_on_get_cursor,
  52929. ma_decoder__data_source_on_get_length,
  52930. NULL, /* onSetLooping */
  52931. 0
  52932. };
  52933. 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)
  52934. {
  52935. ma_result result;
  52936. ma_data_source_config dataSourceConfig;
  52937. MA_ASSERT(pConfig != NULL);
  52938. if (pDecoder == NULL) {
  52939. return MA_INVALID_ARGS;
  52940. }
  52941. MA_ZERO_OBJECT(pDecoder);
  52942. dataSourceConfig = ma_data_source_config_init();
  52943. dataSourceConfig.vtable = &g_ma_decoder_data_source_vtable;
  52944. result = ma_data_source_init(&dataSourceConfig, &pDecoder->ds);
  52945. if (result != MA_SUCCESS) {
  52946. return result;
  52947. }
  52948. pDecoder->onRead = onRead;
  52949. pDecoder->onSeek = onSeek;
  52950. pDecoder->onTell = onTell;
  52951. pDecoder->pUserData = pUserData;
  52952. result = ma_decoder__init_allocation_callbacks(pConfig, pDecoder);
  52953. if (result != MA_SUCCESS) {
  52954. ma_data_source_uninit(&pDecoder->ds);
  52955. return result;
  52956. }
  52957. return MA_SUCCESS;
  52958. }
  52959. static ma_result ma_decoder__postinit(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52960. {
  52961. ma_result result;
  52962. result = ma_decoder__init_data_converter(pDecoder, pConfig);
  52963. /* If we failed post initialization we need to uninitialize the decoder before returning to prevent a memory leak. */
  52964. if (result != MA_SUCCESS) {
  52965. ma_decoder_uninit(pDecoder);
  52966. return result;
  52967. }
  52968. return result;
  52969. }
  52970. 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)
  52971. {
  52972. ma_result result = MA_NO_BACKEND;
  52973. MA_ASSERT(pConfig != NULL);
  52974. MA_ASSERT(pDecoder != NULL);
  52975. /* Silence some warnings in the case that we don't have any decoder backends enabled. */
  52976. (void)onRead;
  52977. (void)onSeek;
  52978. (void)pUserData;
  52979. /* If we've specified a specific encoding type, try that first. */
  52980. if (pConfig->encodingFormat != ma_encoding_format_unknown) {
  52981. #ifdef MA_HAS_WAV
  52982. if (pConfig->encodingFormat == ma_encoding_format_wav) {
  52983. result = ma_decoder_init_wav__internal(pConfig, pDecoder);
  52984. }
  52985. #endif
  52986. #ifdef MA_HAS_FLAC
  52987. if (pConfig->encodingFormat == ma_encoding_format_flac) {
  52988. result = ma_decoder_init_flac__internal(pConfig, pDecoder);
  52989. }
  52990. #endif
  52991. #ifdef MA_HAS_MP3
  52992. if (pConfig->encodingFormat == ma_encoding_format_mp3) {
  52993. result = ma_decoder_init_mp3__internal(pConfig, pDecoder);
  52994. }
  52995. #endif
  52996. #ifdef MA_HAS_VORBIS
  52997. if (pConfig->encodingFormat == ma_encoding_format_vorbis) {
  52998. result = ma_decoder_init_vorbis__internal(pConfig, pDecoder);
  52999. }
  53000. #endif
  53001. /* If we weren't able to initialize the decoder, seek back to the start to give the next attempts a clean start. */
  53002. if (result != MA_SUCCESS) {
  53003. onSeek(pDecoder, 0, ma_seek_origin_start);
  53004. }
  53005. }
  53006. if (result != MA_SUCCESS) {
  53007. /* Getting here means we couldn't load a specific decoding backend based on the encoding format. */
  53008. /*
  53009. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53010. implement the same encoding format they take priority over the built-in decoders.
  53011. */
  53012. if (result != MA_SUCCESS) {
  53013. result = ma_decoder_init_custom__internal(pConfig, pDecoder);
  53014. if (result != MA_SUCCESS) {
  53015. onSeek(pDecoder, 0, ma_seek_origin_start);
  53016. }
  53017. }
  53018. /*
  53019. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53020. specific encoding format, there's no hope for it. Abort.
  53021. */
  53022. if (pConfig->encodingFormat != ma_encoding_format_unknown) {
  53023. return MA_NO_BACKEND;
  53024. }
  53025. #ifdef MA_HAS_WAV
  53026. if (result != MA_SUCCESS) {
  53027. result = ma_decoder_init_wav__internal(pConfig, pDecoder);
  53028. if (result != MA_SUCCESS) {
  53029. onSeek(pDecoder, 0, ma_seek_origin_start);
  53030. }
  53031. }
  53032. #endif
  53033. #ifdef MA_HAS_FLAC
  53034. if (result != MA_SUCCESS) {
  53035. result = ma_decoder_init_flac__internal(pConfig, pDecoder);
  53036. if (result != MA_SUCCESS) {
  53037. onSeek(pDecoder, 0, ma_seek_origin_start);
  53038. }
  53039. }
  53040. #endif
  53041. #ifdef MA_HAS_MP3
  53042. if (result != MA_SUCCESS) {
  53043. result = ma_decoder_init_mp3__internal(pConfig, pDecoder);
  53044. if (result != MA_SUCCESS) {
  53045. onSeek(pDecoder, 0, ma_seek_origin_start);
  53046. }
  53047. }
  53048. #endif
  53049. #ifdef MA_HAS_VORBIS
  53050. if (result != MA_SUCCESS) {
  53051. result = ma_decoder_init_vorbis__internal(pConfig, pDecoder);
  53052. if (result != MA_SUCCESS) {
  53053. onSeek(pDecoder, 0, ma_seek_origin_start);
  53054. }
  53055. }
  53056. #endif
  53057. }
  53058. if (result != MA_SUCCESS) {
  53059. return result;
  53060. }
  53061. return ma_decoder__postinit(pConfig, pDecoder);
  53062. }
  53063. 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)
  53064. {
  53065. ma_decoder_config config;
  53066. ma_result result;
  53067. config = ma_decoder_config_init_copy(pConfig);
  53068. result = ma_decoder__preinit(onRead, onSeek, NULL, pUserData, &config, pDecoder);
  53069. if (result != MA_SUCCESS) {
  53070. return result;
  53071. }
  53072. return ma_decoder_init__internal(onRead, onSeek, pUserData, &config, pDecoder);
  53073. }
  53074. static ma_result ma_decoder__on_read_memory(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  53075. {
  53076. size_t bytesRemaining;
  53077. MA_ASSERT(pDecoder->data.memory.dataSize >= pDecoder->data.memory.currentReadPos);
  53078. if (pBytesRead != NULL) {
  53079. *pBytesRead = 0;
  53080. }
  53081. bytesRemaining = pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos;
  53082. if (bytesToRead > bytesRemaining) {
  53083. bytesToRead = bytesRemaining;
  53084. }
  53085. if (bytesRemaining == 0) {
  53086. return MA_AT_END;
  53087. }
  53088. if (bytesToRead > 0) {
  53089. MA_COPY_MEMORY(pBufferOut, pDecoder->data.memory.pData + pDecoder->data.memory.currentReadPos, bytesToRead);
  53090. pDecoder->data.memory.currentReadPos += bytesToRead;
  53091. }
  53092. if (pBytesRead != NULL) {
  53093. *pBytesRead = bytesToRead;
  53094. }
  53095. return MA_SUCCESS;
  53096. }
  53097. static ma_result ma_decoder__on_seek_memory(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin)
  53098. {
  53099. if (byteOffset > 0 && (ma_uint64)byteOffset > MA_SIZE_MAX) {
  53100. return MA_BAD_SEEK;
  53101. }
  53102. if (origin == ma_seek_origin_current) {
  53103. if (byteOffset > 0) {
  53104. if (pDecoder->data.memory.currentReadPos + byteOffset > pDecoder->data.memory.dataSize) {
  53105. byteOffset = (ma_int64)(pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos); /* Trying to seek too far forward. */
  53106. }
  53107. pDecoder->data.memory.currentReadPos += (size_t)byteOffset;
  53108. } else {
  53109. if (pDecoder->data.memory.currentReadPos < (size_t)-byteOffset) {
  53110. byteOffset = -(ma_int64)pDecoder->data.memory.currentReadPos; /* Trying to seek too far backwards. */
  53111. }
  53112. pDecoder->data.memory.currentReadPos -= (size_t)-byteOffset;
  53113. }
  53114. } else {
  53115. if (origin == ma_seek_origin_end) {
  53116. if (byteOffset < 0) {
  53117. byteOffset = -byteOffset;
  53118. }
  53119. if (byteOffset > (ma_int64)pDecoder->data.memory.dataSize) {
  53120. pDecoder->data.memory.currentReadPos = 0; /* Trying to seek too far back. */
  53121. } else {
  53122. pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize - (size_t)byteOffset;
  53123. }
  53124. } else {
  53125. if ((size_t)byteOffset <= pDecoder->data.memory.dataSize) {
  53126. pDecoder->data.memory.currentReadPos = (size_t)byteOffset;
  53127. } else {
  53128. pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize; /* Trying to seek too far forward. */
  53129. }
  53130. }
  53131. }
  53132. return MA_SUCCESS;
  53133. }
  53134. static ma_result ma_decoder__on_tell_memory(ma_decoder* pDecoder, ma_int64* pCursor)
  53135. {
  53136. MA_ASSERT(pDecoder != NULL);
  53137. MA_ASSERT(pCursor != NULL);
  53138. *pCursor = (ma_int64)pDecoder->data.memory.currentReadPos;
  53139. return MA_SUCCESS;
  53140. }
  53141. static ma_result ma_decoder__preinit_memory_wrapper(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53142. {
  53143. ma_result result = ma_decoder__preinit(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, ma_decoder__on_tell_memory, NULL, pConfig, pDecoder);
  53144. if (result != MA_SUCCESS) {
  53145. return result;
  53146. }
  53147. if (pData == NULL || dataSize == 0) {
  53148. return MA_INVALID_ARGS;
  53149. }
  53150. pDecoder->data.memory.pData = (const ma_uint8*)pData;
  53151. pDecoder->data.memory.dataSize = dataSize;
  53152. pDecoder->data.memory.currentReadPos = 0;
  53153. (void)pConfig;
  53154. return MA_SUCCESS;
  53155. }
  53156. MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53157. {
  53158. ma_result result;
  53159. ma_decoder_config config;
  53160. config = ma_decoder_config_init_copy(pConfig);
  53161. result = ma_decoder__preinit(NULL, NULL, NULL, NULL, &config, pDecoder);
  53162. if (result != MA_SUCCESS) {
  53163. return result;
  53164. }
  53165. if (pData == NULL || dataSize == 0) {
  53166. return MA_INVALID_ARGS;
  53167. }
  53168. /* If the backend has support for loading from a file path we'll want to use that. If that all fails we'll fall back to the VFS path. */
  53169. result = MA_NO_BACKEND;
  53170. if (config.encodingFormat != ma_encoding_format_unknown) {
  53171. #ifdef MA_HAS_WAV
  53172. if (config.encodingFormat == ma_encoding_format_wav) {
  53173. result = ma_decoder_init_wav_from_memory__internal(pData, dataSize, &config, pDecoder);
  53174. }
  53175. #endif
  53176. #ifdef MA_HAS_FLAC
  53177. if (config.encodingFormat == ma_encoding_format_flac) {
  53178. result = ma_decoder_init_flac_from_memory__internal(pData, dataSize, &config, pDecoder);
  53179. }
  53180. #endif
  53181. #ifdef MA_HAS_MP3
  53182. if (config.encodingFormat == ma_encoding_format_mp3) {
  53183. result = ma_decoder_init_mp3_from_memory__internal(pData, dataSize, &config, pDecoder);
  53184. }
  53185. #endif
  53186. #ifdef MA_HAS_VORBIS
  53187. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53188. result = ma_decoder_init_vorbis_from_memory__internal(pData, dataSize, &config, pDecoder);
  53189. }
  53190. #endif
  53191. }
  53192. if (result != MA_SUCCESS) {
  53193. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53194. /*
  53195. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53196. implement the same encoding format they take priority over the built-in decoders.
  53197. */
  53198. result = ma_decoder_init_custom_from_memory__internal(pData, dataSize, &config, pDecoder);
  53199. /*
  53200. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53201. specific encoding format, there's no hope for it. Abort.
  53202. */
  53203. if (result != MA_SUCCESS && config.encodingFormat != ma_encoding_format_unknown) {
  53204. return MA_NO_BACKEND;
  53205. }
  53206. /* Use trial and error for stock decoders. */
  53207. if (result != MA_SUCCESS) {
  53208. #ifdef MA_HAS_WAV
  53209. if (result != MA_SUCCESS) {
  53210. result = ma_decoder_init_wav_from_memory__internal(pData, dataSize, &config, pDecoder);
  53211. }
  53212. #endif
  53213. #ifdef MA_HAS_FLAC
  53214. if (result != MA_SUCCESS) {
  53215. result = ma_decoder_init_flac_from_memory__internal(pData, dataSize, &config, pDecoder);
  53216. }
  53217. #endif
  53218. #ifdef MA_HAS_MP3
  53219. if (result != MA_SUCCESS) {
  53220. result = ma_decoder_init_mp3_from_memory__internal(pData, dataSize, &config, pDecoder);
  53221. }
  53222. #endif
  53223. #ifdef MA_HAS_VORBIS
  53224. if (result != MA_SUCCESS) {
  53225. result = ma_decoder_init_vorbis_from_memory__internal(pData, dataSize, &config, pDecoder);
  53226. }
  53227. #endif
  53228. }
  53229. }
  53230. /*
  53231. If at this point we still haven't successfully initialized the decoder it most likely means
  53232. the backend doesn't have an implementation for loading from a file path. We'll try using
  53233. miniaudio's built-in file IO for loading file.
  53234. */
  53235. if (result == MA_SUCCESS) {
  53236. /* Initialization was successful. Finish up. */
  53237. result = ma_decoder__postinit(&config, pDecoder);
  53238. if (result != MA_SUCCESS) {
  53239. /*
  53240. The backend was initialized successfully, but for some reason post-initialization failed. This is most likely
  53241. due to an out of memory error. We're going to abort with an error here and not try to recover.
  53242. */
  53243. if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) {
  53244. pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, &pDecoder->pBackend, &pDecoder->allocationCallbacks);
  53245. }
  53246. return result;
  53247. }
  53248. } else {
  53249. /* Probably no implementation for loading from a block of memory. Use miniaudio's abstraction instead. */
  53250. result = ma_decoder__preinit_memory_wrapper(pData, dataSize, &config, pDecoder);
  53251. if (result != MA_SUCCESS) {
  53252. return result;
  53253. }
  53254. result = ma_decoder_init__internal(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, NULL, &config, pDecoder);
  53255. if (result != MA_SUCCESS) {
  53256. return result;
  53257. }
  53258. }
  53259. return MA_SUCCESS;
  53260. }
  53261. #if defined(MA_HAS_WAV) || \
  53262. defined(MA_HAS_MP3) || \
  53263. defined(MA_HAS_FLAC) || \
  53264. defined(MA_HAS_VORBIS) || \
  53265. defined(MA_HAS_OPUS)
  53266. #define MA_HAS_PATH_API
  53267. #endif
  53268. #if defined(MA_HAS_PATH_API)
  53269. static const char* ma_path_file_name(const char* path)
  53270. {
  53271. const char* fileName;
  53272. if (path == NULL) {
  53273. return NULL;
  53274. }
  53275. fileName = path;
  53276. /* We just loop through the path until we find the last slash. */
  53277. while (path[0] != '\0') {
  53278. if (path[0] == '/' || path[0] == '\\') {
  53279. fileName = path;
  53280. }
  53281. path += 1;
  53282. }
  53283. /* At this point the file name is sitting on a slash, so just move forward. */
  53284. while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) {
  53285. fileName += 1;
  53286. }
  53287. return fileName;
  53288. }
  53289. static const wchar_t* ma_path_file_name_w(const wchar_t* path)
  53290. {
  53291. const wchar_t* fileName;
  53292. if (path == NULL) {
  53293. return NULL;
  53294. }
  53295. fileName = path;
  53296. /* We just loop through the path until we find the last slash. */
  53297. while (path[0] != '\0') {
  53298. if (path[0] == '/' || path[0] == '\\') {
  53299. fileName = path;
  53300. }
  53301. path += 1;
  53302. }
  53303. /* At this point the file name is sitting on a slash, so just move forward. */
  53304. while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) {
  53305. fileName += 1;
  53306. }
  53307. return fileName;
  53308. }
  53309. static const char* ma_path_extension(const char* path)
  53310. {
  53311. const char* extension;
  53312. const char* lastOccurance;
  53313. if (path == NULL) {
  53314. path = "";
  53315. }
  53316. extension = ma_path_file_name(path);
  53317. lastOccurance = NULL;
  53318. /* Just find the last '.' and return. */
  53319. while (extension[0] != '\0') {
  53320. if (extension[0] == '.') {
  53321. extension += 1;
  53322. lastOccurance = extension;
  53323. }
  53324. extension += 1;
  53325. }
  53326. return (lastOccurance != NULL) ? lastOccurance : extension;
  53327. }
  53328. static const wchar_t* ma_path_extension_w(const wchar_t* path)
  53329. {
  53330. const wchar_t* extension;
  53331. const wchar_t* lastOccurance;
  53332. if (path == NULL) {
  53333. path = L"";
  53334. }
  53335. extension = ma_path_file_name_w(path);
  53336. lastOccurance = NULL;
  53337. /* Just find the last '.' and return. */
  53338. while (extension[0] != '\0') {
  53339. if (extension[0] == '.') {
  53340. extension += 1;
  53341. lastOccurance = extension;
  53342. }
  53343. extension += 1;
  53344. }
  53345. return (lastOccurance != NULL) ? lastOccurance : extension;
  53346. }
  53347. static ma_bool32 ma_path_extension_equal(const char* path, const char* extension)
  53348. {
  53349. const char* ext1;
  53350. const char* ext2;
  53351. if (path == NULL || extension == NULL) {
  53352. return MA_FALSE;
  53353. }
  53354. ext1 = extension;
  53355. ext2 = ma_path_extension(path);
  53356. #if defined(_MSC_VER) || defined(__DMC__)
  53357. return _stricmp(ext1, ext2) == 0;
  53358. #else
  53359. return strcasecmp(ext1, ext2) == 0;
  53360. #endif
  53361. }
  53362. static ma_bool32 ma_path_extension_equal_w(const wchar_t* path, const wchar_t* extension)
  53363. {
  53364. const wchar_t* ext1;
  53365. const wchar_t* ext2;
  53366. if (path == NULL || extension == NULL) {
  53367. return MA_FALSE;
  53368. }
  53369. ext1 = extension;
  53370. ext2 = ma_path_extension_w(path);
  53371. #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)
  53372. return _wcsicmp(ext1, ext2) == 0;
  53373. #else
  53374. /*
  53375. I'm not aware of a wide character version of strcasecmp(). I'm therefore converting the extensions to multibyte strings and comparing those. This
  53376. isn't the most efficient way to do it, but it should work OK.
  53377. */
  53378. {
  53379. char ext1MB[4096];
  53380. char ext2MB[4096];
  53381. const wchar_t* pext1 = ext1;
  53382. const wchar_t* pext2 = ext2;
  53383. mbstate_t mbs1;
  53384. mbstate_t mbs2;
  53385. MA_ZERO_OBJECT(&mbs1);
  53386. MA_ZERO_OBJECT(&mbs2);
  53387. if (wcsrtombs(ext1MB, &pext1, sizeof(ext1MB), &mbs1) == (size_t)-1) {
  53388. return MA_FALSE;
  53389. }
  53390. if (wcsrtombs(ext2MB, &pext2, sizeof(ext2MB), &mbs2) == (size_t)-1) {
  53391. return MA_FALSE;
  53392. }
  53393. return strcasecmp(ext1MB, ext2MB) == 0;
  53394. }
  53395. #endif
  53396. }
  53397. #endif /* MA_HAS_PATH_API */
  53398. static ma_result ma_decoder__on_read_vfs(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  53399. {
  53400. MA_ASSERT(pDecoder != NULL);
  53401. MA_ASSERT(pBufferOut != NULL);
  53402. return ma_vfs_or_default_read(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pBufferOut, bytesToRead, pBytesRead);
  53403. }
  53404. static ma_result ma_decoder__on_seek_vfs(ma_decoder* pDecoder, ma_int64 offset, ma_seek_origin origin)
  53405. {
  53406. MA_ASSERT(pDecoder != NULL);
  53407. return ma_vfs_or_default_seek(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, offset, origin);
  53408. }
  53409. static ma_result ma_decoder__on_tell_vfs(ma_decoder* pDecoder, ma_int64* pCursor)
  53410. {
  53411. MA_ASSERT(pDecoder != NULL);
  53412. return ma_vfs_or_default_tell(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pCursor);
  53413. }
  53414. static ma_result ma_decoder__preinit_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53415. {
  53416. ma_result result;
  53417. ma_vfs_file file;
  53418. result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder);
  53419. if (result != MA_SUCCESS) {
  53420. return result;
  53421. }
  53422. if (pFilePath == NULL || pFilePath[0] == '\0') {
  53423. return MA_INVALID_ARGS;
  53424. }
  53425. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  53426. if (result != MA_SUCCESS) {
  53427. return result;
  53428. }
  53429. pDecoder->data.vfs.pVFS = pVFS;
  53430. pDecoder->data.vfs.file = file;
  53431. return MA_SUCCESS;
  53432. }
  53433. MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53434. {
  53435. ma_result result;
  53436. ma_decoder_config config;
  53437. config = ma_decoder_config_init_copy(pConfig);
  53438. result = ma_decoder__preinit_vfs(pVFS, pFilePath, &config, pDecoder);
  53439. if (result != MA_SUCCESS) {
  53440. return result;
  53441. }
  53442. result = MA_NO_BACKEND;
  53443. if (config.encodingFormat != ma_encoding_format_unknown) {
  53444. #ifdef MA_HAS_WAV
  53445. if (config.encodingFormat == ma_encoding_format_wav) {
  53446. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53447. }
  53448. #endif
  53449. #ifdef MA_HAS_FLAC
  53450. if (config.encodingFormat == ma_encoding_format_flac) {
  53451. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53452. }
  53453. #endif
  53454. #ifdef MA_HAS_MP3
  53455. if (config.encodingFormat == ma_encoding_format_mp3) {
  53456. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53457. }
  53458. #endif
  53459. #ifdef MA_HAS_VORBIS
  53460. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53461. result = ma_decoder_init_vorbis__internal(&config, pDecoder);
  53462. }
  53463. #endif
  53464. /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */
  53465. if (result != MA_SUCCESS) {
  53466. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53467. }
  53468. }
  53469. if (result != MA_SUCCESS) {
  53470. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53471. /*
  53472. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53473. implement the same encoding format they take priority over the built-in decoders.
  53474. */
  53475. if (result != MA_SUCCESS) {
  53476. result = ma_decoder_init_custom__internal(&config, pDecoder);
  53477. if (result != MA_SUCCESS) {
  53478. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53479. }
  53480. }
  53481. /*
  53482. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53483. specific encoding format, there's no hope for it. Abort.
  53484. */
  53485. if (config.encodingFormat != ma_encoding_format_unknown) {
  53486. return MA_NO_BACKEND;
  53487. }
  53488. #ifdef MA_HAS_WAV
  53489. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "wav")) {
  53490. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53491. if (result != MA_SUCCESS) {
  53492. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53493. }
  53494. }
  53495. #endif
  53496. #ifdef MA_HAS_FLAC
  53497. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "flac")) {
  53498. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53499. if (result != MA_SUCCESS) {
  53500. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53501. }
  53502. }
  53503. #endif
  53504. #ifdef MA_HAS_MP3
  53505. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "mp3")) {
  53506. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53507. if (result != MA_SUCCESS) {
  53508. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53509. }
  53510. }
  53511. #endif
  53512. }
  53513. /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */
  53514. if (result != MA_SUCCESS) {
  53515. result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder);
  53516. } else {
  53517. result = ma_decoder__postinit(&config, pDecoder);
  53518. }
  53519. if (result != MA_SUCCESS) {
  53520. 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. */
  53521. ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file);
  53522. }
  53523. return result;
  53524. }
  53525. return MA_SUCCESS;
  53526. }
  53527. static ma_result ma_decoder__preinit_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53528. {
  53529. ma_result result;
  53530. ma_vfs_file file;
  53531. result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder);
  53532. if (result != MA_SUCCESS) {
  53533. return result;
  53534. }
  53535. if (pFilePath == NULL || pFilePath[0] == '\0') {
  53536. return MA_INVALID_ARGS;
  53537. }
  53538. result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  53539. if (result != MA_SUCCESS) {
  53540. return result;
  53541. }
  53542. pDecoder->data.vfs.pVFS = pVFS;
  53543. pDecoder->data.vfs.file = file;
  53544. return MA_SUCCESS;
  53545. }
  53546. MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53547. {
  53548. ma_result result;
  53549. ma_decoder_config config;
  53550. config = ma_decoder_config_init_copy(pConfig);
  53551. result = ma_decoder__preinit_vfs_w(pVFS, pFilePath, &config, pDecoder);
  53552. if (result != MA_SUCCESS) {
  53553. return result;
  53554. }
  53555. result = MA_NO_BACKEND;
  53556. if (config.encodingFormat != ma_encoding_format_unknown) {
  53557. #ifdef MA_HAS_WAV
  53558. if (config.encodingFormat == ma_encoding_format_wav) {
  53559. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53560. }
  53561. #endif
  53562. #ifdef MA_HAS_FLAC
  53563. if (config.encodingFormat == ma_encoding_format_flac) {
  53564. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53565. }
  53566. #endif
  53567. #ifdef MA_HAS_MP3
  53568. if (config.encodingFormat == ma_encoding_format_mp3) {
  53569. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53570. }
  53571. #endif
  53572. #ifdef MA_HAS_VORBIS
  53573. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53574. result = ma_decoder_init_vorbis__internal(&config, pDecoder);
  53575. }
  53576. #endif
  53577. /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */
  53578. if (result != MA_SUCCESS) {
  53579. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53580. }
  53581. }
  53582. if (result != MA_SUCCESS) {
  53583. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53584. /*
  53585. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53586. implement the same encoding format they take priority over the built-in decoders.
  53587. */
  53588. if (result != MA_SUCCESS) {
  53589. result = ma_decoder_init_custom__internal(&config, pDecoder);
  53590. if (result != MA_SUCCESS) {
  53591. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53592. }
  53593. }
  53594. /*
  53595. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53596. specific encoding format, there's no hope for it. Abort.
  53597. */
  53598. if (config.encodingFormat != ma_encoding_format_unknown) {
  53599. return MA_NO_BACKEND;
  53600. }
  53601. #ifdef MA_HAS_WAV
  53602. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"wav")) {
  53603. result = ma_decoder_init_wav__internal(&config, pDecoder);
  53604. if (result != MA_SUCCESS) {
  53605. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53606. }
  53607. }
  53608. #endif
  53609. #ifdef MA_HAS_FLAC
  53610. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"flac")) {
  53611. result = ma_decoder_init_flac__internal(&config, pDecoder);
  53612. if (result != MA_SUCCESS) {
  53613. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53614. }
  53615. }
  53616. #endif
  53617. #ifdef MA_HAS_MP3
  53618. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"mp3")) {
  53619. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  53620. if (result != MA_SUCCESS) {
  53621. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  53622. }
  53623. }
  53624. #endif
  53625. }
  53626. /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */
  53627. if (result != MA_SUCCESS) {
  53628. result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder);
  53629. } else {
  53630. result = ma_decoder__postinit(&config, pDecoder);
  53631. }
  53632. if (result != MA_SUCCESS) {
  53633. ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file);
  53634. return result;
  53635. }
  53636. return MA_SUCCESS;
  53637. }
  53638. static ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53639. {
  53640. ma_result result;
  53641. result = ma_decoder__preinit(NULL, NULL, NULL, NULL, pConfig, pDecoder);
  53642. if (result != MA_SUCCESS) {
  53643. return result;
  53644. }
  53645. if (pFilePath == NULL || pFilePath[0] == '\0') {
  53646. return MA_INVALID_ARGS;
  53647. }
  53648. return MA_SUCCESS;
  53649. }
  53650. MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53651. {
  53652. ma_result result;
  53653. ma_decoder_config config;
  53654. config = ma_decoder_config_init_copy(pConfig);
  53655. result = ma_decoder__preinit_file(pFilePath, &config, pDecoder);
  53656. if (result != MA_SUCCESS) {
  53657. return result;
  53658. }
  53659. /* If the backend has support for loading from a file path we'll want to use that. If that all fails we'll fall back to the VFS path. */
  53660. result = MA_NO_BACKEND;
  53661. if (config.encodingFormat != ma_encoding_format_unknown) {
  53662. #ifdef MA_HAS_WAV
  53663. if (config.encodingFormat == ma_encoding_format_wav) {
  53664. result = ma_decoder_init_wav_from_file__internal(pFilePath, &config, pDecoder);
  53665. }
  53666. #endif
  53667. #ifdef MA_HAS_FLAC
  53668. if (config.encodingFormat == ma_encoding_format_flac) {
  53669. result = ma_decoder_init_flac_from_file__internal(pFilePath, &config, pDecoder);
  53670. }
  53671. #endif
  53672. #ifdef MA_HAS_MP3
  53673. if (config.encodingFormat == ma_encoding_format_mp3) {
  53674. result = ma_decoder_init_mp3_from_file__internal(pFilePath, &config, pDecoder);
  53675. }
  53676. #endif
  53677. #ifdef MA_HAS_VORBIS
  53678. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53679. result = ma_decoder_init_vorbis_from_file__internal(pFilePath, &config, pDecoder);
  53680. }
  53681. #endif
  53682. }
  53683. if (result != MA_SUCCESS) {
  53684. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53685. /*
  53686. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53687. implement the same encoding format they take priority over the built-in decoders.
  53688. */
  53689. result = ma_decoder_init_custom_from_file__internal(pFilePath, &config, pDecoder);
  53690. /*
  53691. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53692. specific encoding format, there's no hope for it. Abort.
  53693. */
  53694. if (result != MA_SUCCESS && config.encodingFormat != ma_encoding_format_unknown) {
  53695. return MA_NO_BACKEND;
  53696. }
  53697. /* First try loading based on the file extension so we don't waste time opening and closing files. */
  53698. #ifdef MA_HAS_WAV
  53699. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "wav")) {
  53700. result = ma_decoder_init_wav_from_file__internal(pFilePath, &config, pDecoder);
  53701. }
  53702. #endif
  53703. #ifdef MA_HAS_FLAC
  53704. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "flac")) {
  53705. result = ma_decoder_init_flac_from_file__internal(pFilePath, &config, pDecoder);
  53706. }
  53707. #endif
  53708. #ifdef MA_HAS_MP3
  53709. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "mp3")) {
  53710. result = ma_decoder_init_mp3_from_file__internal(pFilePath, &config, pDecoder);
  53711. }
  53712. #endif
  53713. #ifdef MA_HAS_VORBIS
  53714. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "ogg")) {
  53715. result = ma_decoder_init_vorbis_from_file__internal(pFilePath, &config, pDecoder);
  53716. }
  53717. #endif
  53718. /*
  53719. If we still haven't got a result just use trial and error. Custom decoders have already been attempted, so here we
  53720. need only iterate over our stock decoders.
  53721. */
  53722. if (result != MA_SUCCESS) {
  53723. #ifdef MA_HAS_WAV
  53724. if (result != MA_SUCCESS) {
  53725. result = ma_decoder_init_wav_from_file__internal(pFilePath, &config, pDecoder);
  53726. }
  53727. #endif
  53728. #ifdef MA_HAS_FLAC
  53729. if (result != MA_SUCCESS) {
  53730. result = ma_decoder_init_flac_from_file__internal(pFilePath, &config, pDecoder);
  53731. }
  53732. #endif
  53733. #ifdef MA_HAS_MP3
  53734. if (result != MA_SUCCESS) {
  53735. result = ma_decoder_init_mp3_from_file__internal(pFilePath, &config, pDecoder);
  53736. }
  53737. #endif
  53738. #ifdef MA_HAS_VORBIS
  53739. if (result != MA_SUCCESS) {
  53740. result = ma_decoder_init_vorbis_from_file__internal(pFilePath, &config, pDecoder);
  53741. }
  53742. #endif
  53743. }
  53744. }
  53745. /*
  53746. If at this point we still haven't successfully initialized the decoder it most likely means
  53747. the backend doesn't have an implementation for loading from a file path. We'll try using
  53748. miniaudio's built-in file IO for loading file.
  53749. */
  53750. if (result == MA_SUCCESS) {
  53751. /* Initialization was successful. Finish up. */
  53752. result = ma_decoder__postinit(&config, pDecoder);
  53753. if (result != MA_SUCCESS) {
  53754. /*
  53755. The backend was initialized successfully, but for some reason post-initialization failed. This is most likely
  53756. due to an out of memory error. We're going to abort with an error here and not try to recover.
  53757. */
  53758. if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) {
  53759. pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, &pDecoder->pBackend, &pDecoder->allocationCallbacks);
  53760. }
  53761. return result;
  53762. }
  53763. } else {
  53764. /* Probably no implementation for loading from a file path. Use miniaudio's file IO instead. */
  53765. result = ma_decoder_init_vfs(NULL, pFilePath, pConfig, pDecoder);
  53766. if (result != MA_SUCCESS) {
  53767. return result;
  53768. }
  53769. }
  53770. return MA_SUCCESS;
  53771. }
  53772. static ma_result ma_decoder__preinit_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53773. {
  53774. ma_result result;
  53775. result = ma_decoder__preinit(NULL, NULL, NULL, NULL, pConfig, pDecoder);
  53776. if (result != MA_SUCCESS) {
  53777. return result;
  53778. }
  53779. if (pFilePath == NULL || pFilePath[0] == '\0') {
  53780. return MA_INVALID_ARGS;
  53781. }
  53782. return MA_SUCCESS;
  53783. }
  53784. MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  53785. {
  53786. ma_result result;
  53787. ma_decoder_config config;
  53788. config = ma_decoder_config_init_copy(pConfig);
  53789. result = ma_decoder__preinit_file_w(pFilePath, &config, pDecoder);
  53790. if (result != MA_SUCCESS) {
  53791. return result;
  53792. }
  53793. /* If the backend has support for loading from a file path we'll want to use that. If that all fails we'll fall back to the VFS path. */
  53794. result = MA_NO_BACKEND;
  53795. if (config.encodingFormat != ma_encoding_format_unknown) {
  53796. #ifdef MA_HAS_WAV
  53797. if (config.encodingFormat == ma_encoding_format_wav) {
  53798. result = ma_decoder_init_wav_from_file_w__internal(pFilePath, &config, pDecoder);
  53799. }
  53800. #endif
  53801. #ifdef MA_HAS_FLAC
  53802. if (config.encodingFormat == ma_encoding_format_flac) {
  53803. result = ma_decoder_init_flac_from_file_w__internal(pFilePath, &config, pDecoder);
  53804. }
  53805. #endif
  53806. #ifdef MA_HAS_MP3
  53807. if (config.encodingFormat == ma_encoding_format_mp3) {
  53808. result = ma_decoder_init_mp3_from_file_w__internal(pFilePath, &config, pDecoder);
  53809. }
  53810. #endif
  53811. #ifdef MA_HAS_VORBIS
  53812. if (config.encodingFormat == ma_encoding_format_vorbis) {
  53813. result = ma_decoder_init_vorbis_from_file_w__internal(pFilePath, &config, pDecoder);
  53814. }
  53815. #endif
  53816. }
  53817. if (result != MA_SUCCESS) {
  53818. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  53819. /*
  53820. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  53821. implement the same encoding format they take priority over the built-in decoders.
  53822. */
  53823. result = ma_decoder_init_custom_from_file_w__internal(pFilePath, &config, pDecoder);
  53824. /*
  53825. If we get to this point and we still haven't found a decoder, and the caller has requested a
  53826. specific encoding format, there's no hope for it. Abort.
  53827. */
  53828. if (result != MA_SUCCESS && config.encodingFormat != ma_encoding_format_unknown) {
  53829. return MA_NO_BACKEND;
  53830. }
  53831. /* First try loading based on the file extension so we don't waste time opening and closing files. */
  53832. #ifdef MA_HAS_WAV
  53833. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"wav")) {
  53834. result = ma_decoder_init_wav_from_file_w__internal(pFilePath, &config, pDecoder);
  53835. }
  53836. #endif
  53837. #ifdef MA_HAS_FLAC
  53838. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"flac")) {
  53839. result = ma_decoder_init_flac_from_file_w__internal(pFilePath, &config, pDecoder);
  53840. }
  53841. #endif
  53842. #ifdef MA_HAS_MP3
  53843. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"mp3")) {
  53844. result = ma_decoder_init_mp3_from_file_w__internal(pFilePath, &config, pDecoder);
  53845. }
  53846. #endif
  53847. #ifdef MA_HAS_VORBIS
  53848. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"ogg")) {
  53849. result = ma_decoder_init_vorbis_from_file_w__internal(pFilePath, &config, pDecoder);
  53850. }
  53851. #endif
  53852. /*
  53853. If we still haven't got a result just use trial and error. Custom decoders have already been attempted, so here we
  53854. need only iterate over our stock decoders.
  53855. */
  53856. if (result != MA_SUCCESS) {
  53857. #ifdef MA_HAS_WAV
  53858. if (result != MA_SUCCESS) {
  53859. result = ma_decoder_init_wav_from_file_w__internal(pFilePath, &config, pDecoder);
  53860. }
  53861. #endif
  53862. #ifdef MA_HAS_FLAC
  53863. if (result != MA_SUCCESS) {
  53864. result = ma_decoder_init_flac_from_file_w__internal(pFilePath, &config, pDecoder);
  53865. }
  53866. #endif
  53867. #ifdef MA_HAS_MP3
  53868. if (result != MA_SUCCESS) {
  53869. result = ma_decoder_init_mp3_from_file_w__internal(pFilePath, &config, pDecoder);
  53870. }
  53871. #endif
  53872. #ifdef MA_HAS_VORBIS
  53873. if (result != MA_SUCCESS) {
  53874. result = ma_decoder_init_vorbis_from_file_w__internal(pFilePath, &config, pDecoder);
  53875. }
  53876. #endif
  53877. }
  53878. }
  53879. /*
  53880. If at this point we still haven't successfully initialized the decoder it most likely means
  53881. the backend doesn't have an implementation for loading from a file path. We'll try using
  53882. miniaudio's built-in file IO for loading file.
  53883. */
  53884. if (result == MA_SUCCESS) {
  53885. /* Initialization was successful. Finish up. */
  53886. result = ma_decoder__postinit(&config, pDecoder);
  53887. if (result != MA_SUCCESS) {
  53888. /*
  53889. The backend was initialized successfully, but for some reason post-initialization failed. This is most likely
  53890. due to an out of memory error. We're going to abort with an error here and not try to recover.
  53891. */
  53892. if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) {
  53893. pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, &pDecoder->pBackend, &pDecoder->allocationCallbacks);
  53894. }
  53895. return result;
  53896. }
  53897. } else {
  53898. /* Probably no implementation for loading from a file path. Use miniaudio's file IO instead. */
  53899. result = ma_decoder_init_vfs_w(NULL, pFilePath, pConfig, pDecoder);
  53900. if (result != MA_SUCCESS) {
  53901. return result;
  53902. }
  53903. }
  53904. return MA_SUCCESS;
  53905. }
  53906. MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder)
  53907. {
  53908. if (pDecoder == NULL) {
  53909. return MA_INVALID_ARGS;
  53910. }
  53911. if (pDecoder->pBackend != NULL) {
  53912. if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) {
  53913. pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, pDecoder->pBackend, &pDecoder->allocationCallbacks);
  53914. }
  53915. }
  53916. if (pDecoder->onRead == ma_decoder__on_read_vfs) {
  53917. ma_vfs_or_default_close(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file);
  53918. pDecoder->data.vfs.file = NULL;
  53919. }
  53920. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  53921. ma_data_source_uninit(&pDecoder->ds);
  53922. if (pDecoder->pInputCache != NULL) {
  53923. ma_free(pDecoder->pInputCache, &pDecoder->allocationCallbacks);
  53924. }
  53925. return MA_SUCCESS;
  53926. }
  53927. MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  53928. {
  53929. ma_result result = MA_SUCCESS;
  53930. ma_uint64 totalFramesReadOut;
  53931. void* pRunningFramesOut;
  53932. if (pFramesRead != NULL) {
  53933. *pFramesRead = 0; /* Safety. */
  53934. }
  53935. if (frameCount == 0) {
  53936. return MA_INVALID_ARGS;
  53937. }
  53938. if (pDecoder == NULL) {
  53939. return MA_INVALID_ARGS;
  53940. }
  53941. if (pDecoder->pBackend == NULL) {
  53942. return MA_INVALID_OPERATION;
  53943. }
  53944. /* Fast path. */
  53945. if (pDecoder->converter.isPassthrough) {
  53946. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pFramesOut, frameCount, &totalFramesReadOut);
  53947. } else {
  53948. /*
  53949. 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
  53950. need to run through each sample because we need to ensure it's internal cache is updated.
  53951. */
  53952. if (pFramesOut == NULL && pDecoder->converter.hasResampler == MA_FALSE) {
  53953. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, NULL, frameCount, &totalFramesReadOut);
  53954. } else {
  53955. /* Slow path. Need to run everything through the data converter. */
  53956. ma_format internalFormat;
  53957. ma_uint32 internalChannels;
  53958. totalFramesReadOut = 0;
  53959. pRunningFramesOut = pFramesOut;
  53960. result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, NULL, NULL, 0);
  53961. if (result != MA_SUCCESS) {
  53962. return result; /* Failed to retrieve the internal format and channel count. */
  53963. }
  53964. /*
  53965. We run a different path depending on whether or not we are using a heap-allocated
  53966. intermediary buffer or not. If the data converter does not support the calculation of
  53967. the required number of input frames, we'll use the heap-allocated path. Otherwise we'll
  53968. use the stack-allocated path.
  53969. */
  53970. if (pDecoder->pInputCache != NULL) {
  53971. /* We don't have a way of determining the required number of input frames, so need to persistently store input data in a cache. */
  53972. while (totalFramesReadOut < frameCount) {
  53973. ma_uint64 framesToReadThisIterationIn;
  53974. ma_uint64 framesToReadThisIterationOut;
  53975. /* If there's any data available in the cache, that needs to get processed first. */
  53976. if (pDecoder->inputCacheRemaining > 0) {
  53977. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  53978. framesToReadThisIterationIn = framesToReadThisIterationOut;
  53979. if (framesToReadThisIterationIn > pDecoder->inputCacheRemaining) {
  53980. framesToReadThisIterationIn = pDecoder->inputCacheRemaining;
  53981. }
  53982. result = ma_data_converter_process_pcm_frames(&pDecoder->converter, ma_offset_pcm_frames_ptr(pDecoder->pInputCache, pDecoder->inputCacheConsumed, internalFormat, internalChannels), &framesToReadThisIterationIn, pRunningFramesOut, &framesToReadThisIterationOut);
  53983. if (result != MA_SUCCESS) {
  53984. break;
  53985. }
  53986. pDecoder->inputCacheConsumed += framesToReadThisIterationIn;
  53987. pDecoder->inputCacheRemaining -= framesToReadThisIterationIn;
  53988. totalFramesReadOut += framesToReadThisIterationOut;
  53989. if (pRunningFramesOut != NULL) {
  53990. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
  53991. }
  53992. if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) {
  53993. break; /* We're done. */
  53994. }
  53995. }
  53996. /* Getting here means there's no data in the cache and we need to fill it up from the data source. */
  53997. if (pDecoder->inputCacheRemaining == 0) {
  53998. pDecoder->inputCacheConsumed = 0;
  53999. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pDecoder->pInputCache, pDecoder->inputCacheCap, &pDecoder->inputCacheRemaining);
  54000. if (result != MA_SUCCESS) {
  54001. break;
  54002. }
  54003. }
  54004. }
  54005. } else {
  54006. /* We have a way of determining the required number of input frames so just use the stack. */
  54007. while (totalFramesReadOut < frameCount) {
  54008. ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In internal format. */
  54009. ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(internalFormat, internalChannels);
  54010. ma_uint64 framesToReadThisIterationIn;
  54011. ma_uint64 framesReadThisIterationIn;
  54012. ma_uint64 framesToReadThisIterationOut;
  54013. ma_uint64 framesReadThisIterationOut;
  54014. ma_uint64 requiredInputFrameCount;
  54015. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  54016. framesToReadThisIterationIn = framesToReadThisIterationOut;
  54017. if (framesToReadThisIterationIn > intermediaryBufferCap) {
  54018. framesToReadThisIterationIn = intermediaryBufferCap;
  54019. }
  54020. ma_data_converter_get_required_input_frame_count(&pDecoder->converter, framesToReadThisIterationOut, &requiredInputFrameCount);
  54021. if (framesToReadThisIterationIn > requiredInputFrameCount) {
  54022. framesToReadThisIterationIn = requiredInputFrameCount;
  54023. }
  54024. if (requiredInputFrameCount > 0) {
  54025. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pIntermediaryBuffer, framesToReadThisIterationIn, &framesReadThisIterationIn);
  54026. } else {
  54027. framesReadThisIterationIn = 0;
  54028. }
  54029. /*
  54030. 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
  54031. input frames, we still want to try processing frames because there may some output frames generated from cached input data.
  54032. */
  54033. framesReadThisIterationOut = framesToReadThisIterationOut;
  54034. result = ma_data_converter_process_pcm_frames(&pDecoder->converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
  54035. if (result != MA_SUCCESS) {
  54036. break;
  54037. }
  54038. totalFramesReadOut += framesReadThisIterationOut;
  54039. if (pRunningFramesOut != NULL) {
  54040. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
  54041. }
  54042. if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
  54043. break; /* We're done. */
  54044. }
  54045. }
  54046. }
  54047. }
  54048. }
  54049. pDecoder->readPointerInPCMFrames += totalFramesReadOut;
  54050. if (pFramesRead != NULL) {
  54051. *pFramesRead = totalFramesReadOut;
  54052. }
  54053. if (result == MA_SUCCESS && totalFramesReadOut == 0) {
  54054. result = MA_AT_END;
  54055. }
  54056. return result;
  54057. }
  54058. MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex)
  54059. {
  54060. if (pDecoder == NULL) {
  54061. return MA_INVALID_ARGS;
  54062. }
  54063. if (pDecoder->pBackend != NULL) {
  54064. ma_result result;
  54065. ma_uint64 internalFrameIndex;
  54066. ma_uint32 internalSampleRate;
  54067. ma_uint64 currentFrameIndex;
  54068. result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0);
  54069. if (result != MA_SUCCESS) {
  54070. return result; /* Failed to retrieve the internal sample rate. */
  54071. }
  54072. if (internalSampleRate == pDecoder->outputSampleRate) {
  54073. internalFrameIndex = frameIndex;
  54074. } else {
  54075. internalFrameIndex = ma_calculate_frame_count_after_resampling(internalSampleRate, pDecoder->outputSampleRate, frameIndex);
  54076. }
  54077. /* Only seek if we're requesting a different frame to what we're currently sitting on. */
  54078. ma_data_source_get_cursor_in_pcm_frames(pDecoder->pBackend, &currentFrameIndex);
  54079. if (currentFrameIndex != internalFrameIndex) {
  54080. result = ma_data_source_seek_to_pcm_frame(pDecoder->pBackend, internalFrameIndex);
  54081. if (result == MA_SUCCESS) {
  54082. pDecoder->readPointerInPCMFrames = frameIndex;
  54083. }
  54084. /* Reset the data converter so that any cached data in the resampler is cleared. */
  54085. ma_data_converter_reset(&pDecoder->converter);
  54086. }
  54087. return result;
  54088. }
  54089. /* Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. */
  54090. return MA_INVALID_ARGS;
  54091. }
  54092. 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)
  54093. {
  54094. if (pDecoder == NULL) {
  54095. return MA_INVALID_ARGS;
  54096. }
  54097. if (pFormat != NULL) {
  54098. *pFormat = pDecoder->outputFormat;
  54099. }
  54100. if (pChannels != NULL) {
  54101. *pChannels = pDecoder->outputChannels;
  54102. }
  54103. if (pSampleRate != NULL) {
  54104. *pSampleRate = pDecoder->outputSampleRate;
  54105. }
  54106. if (pChannelMap != NULL) {
  54107. ma_data_converter_get_output_channel_map(&pDecoder->converter, pChannelMap, channelMapCap);
  54108. }
  54109. return MA_SUCCESS;
  54110. }
  54111. MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor)
  54112. {
  54113. if (pCursor == NULL) {
  54114. return MA_INVALID_ARGS;
  54115. }
  54116. *pCursor = 0;
  54117. if (pDecoder == NULL) {
  54118. return MA_INVALID_ARGS;
  54119. }
  54120. *pCursor = pDecoder->readPointerInPCMFrames;
  54121. return MA_SUCCESS;
  54122. }
  54123. MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength)
  54124. {
  54125. if (pLength == NULL) {
  54126. return MA_INVALID_ARGS;
  54127. }
  54128. *pLength = 0;
  54129. if (pDecoder == NULL) {
  54130. return MA_INVALID_ARGS;
  54131. }
  54132. if (pDecoder->pBackend != NULL) {
  54133. ma_result result;
  54134. ma_uint64 internalLengthInPCMFrames;
  54135. ma_uint32 internalSampleRate;
  54136. result = ma_data_source_get_length_in_pcm_frames(pDecoder->pBackend, &internalLengthInPCMFrames);
  54137. if (result != MA_SUCCESS) {
  54138. return result; /* Failed to retrieve the internal length. */
  54139. }
  54140. result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0);
  54141. if (result != MA_SUCCESS) {
  54142. return result; /* Failed to retrieve the internal sample rate. */
  54143. }
  54144. if (internalSampleRate == pDecoder->outputSampleRate) {
  54145. *pLength = internalLengthInPCMFrames;
  54146. } else {
  54147. *pLength = ma_calculate_frame_count_after_resampling(pDecoder->outputSampleRate, internalSampleRate, internalLengthInPCMFrames);
  54148. }
  54149. return MA_SUCCESS;
  54150. } else {
  54151. return MA_NO_BACKEND;
  54152. }
  54153. }
  54154. MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames)
  54155. {
  54156. ma_result result;
  54157. ma_uint64 totalFrameCount;
  54158. if (pAvailableFrames == NULL) {
  54159. return MA_INVALID_ARGS;
  54160. }
  54161. *pAvailableFrames = 0;
  54162. if (pDecoder == NULL) {
  54163. return MA_INVALID_ARGS;
  54164. }
  54165. result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount);
  54166. if (result != MA_SUCCESS) {
  54167. return result;
  54168. }
  54169. if (totalFrameCount <= pDecoder->readPointerInPCMFrames) {
  54170. *pAvailableFrames = 0;
  54171. } else {
  54172. *pAvailableFrames = totalFrameCount - pDecoder->readPointerInPCMFrames;
  54173. }
  54174. return MA_SUCCESS;
  54175. }
  54176. static ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54177. {
  54178. ma_result result;
  54179. ma_uint64 totalFrameCount;
  54180. ma_uint64 bpf;
  54181. ma_uint64 dataCapInFrames;
  54182. void* pPCMFramesOut;
  54183. MA_ASSERT(pDecoder != NULL);
  54184. totalFrameCount = 0;
  54185. bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
  54186. /* The frame count is unknown until we try reading. Thus, we just run in a loop. */
  54187. dataCapInFrames = 0;
  54188. pPCMFramesOut = NULL;
  54189. for (;;) {
  54190. ma_uint64 frameCountToTryReading;
  54191. ma_uint64 framesJustRead;
  54192. /* Make room if there's not enough. */
  54193. if (totalFrameCount == dataCapInFrames) {
  54194. void* pNewPCMFramesOut;
  54195. ma_uint64 newDataCapInFrames = dataCapInFrames*2;
  54196. if (newDataCapInFrames == 0) {
  54197. newDataCapInFrames = 4096;
  54198. }
  54199. if ((newDataCapInFrames * bpf) > MA_SIZE_MAX) {
  54200. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  54201. return MA_TOO_BIG;
  54202. }
  54203. pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf), &pDecoder->allocationCallbacks);
  54204. if (pNewPCMFramesOut == NULL) {
  54205. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  54206. return MA_OUT_OF_MEMORY;
  54207. }
  54208. dataCapInFrames = newDataCapInFrames;
  54209. pPCMFramesOut = pNewPCMFramesOut;
  54210. }
  54211. frameCountToTryReading = dataCapInFrames - totalFrameCount;
  54212. MA_ASSERT(frameCountToTryReading > 0);
  54213. result = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading, &framesJustRead);
  54214. totalFrameCount += framesJustRead;
  54215. if (result != MA_SUCCESS) {
  54216. break;
  54217. }
  54218. if (framesJustRead < frameCountToTryReading) {
  54219. break;
  54220. }
  54221. }
  54222. if (pConfigOut != NULL) {
  54223. pConfigOut->format = pDecoder->outputFormat;
  54224. pConfigOut->channels = pDecoder->outputChannels;
  54225. pConfigOut->sampleRate = pDecoder->outputSampleRate;
  54226. }
  54227. if (ppPCMFramesOut != NULL) {
  54228. *ppPCMFramesOut = pPCMFramesOut;
  54229. } else {
  54230. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  54231. }
  54232. if (pFrameCountOut != NULL) {
  54233. *pFrameCountOut = totalFrameCount;
  54234. }
  54235. ma_decoder_uninit(pDecoder);
  54236. return MA_SUCCESS;
  54237. }
  54238. MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54239. {
  54240. ma_result result;
  54241. ma_decoder_config config;
  54242. ma_decoder decoder;
  54243. if (pFrameCountOut != NULL) {
  54244. *pFrameCountOut = 0;
  54245. }
  54246. if (ppPCMFramesOut != NULL) {
  54247. *ppPCMFramesOut = NULL;
  54248. }
  54249. config = ma_decoder_config_init_copy(pConfig);
  54250. result = ma_decoder_init_vfs(pVFS, pFilePath, &config, &decoder);
  54251. if (result != MA_SUCCESS) {
  54252. return result;
  54253. }
  54254. result = ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
  54255. return result;
  54256. }
  54257. MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54258. {
  54259. return ma_decode_from_vfs(NULL, pFilePath, pConfig, pFrameCountOut, ppPCMFramesOut);
  54260. }
  54261. MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  54262. {
  54263. ma_decoder_config config;
  54264. ma_decoder decoder;
  54265. ma_result result;
  54266. if (pFrameCountOut != NULL) {
  54267. *pFrameCountOut = 0;
  54268. }
  54269. if (ppPCMFramesOut != NULL) {
  54270. *ppPCMFramesOut = NULL;
  54271. }
  54272. if (pData == NULL || dataSize == 0) {
  54273. return MA_INVALID_ARGS;
  54274. }
  54275. config = ma_decoder_config_init_copy(pConfig);
  54276. result = ma_decoder_init_memory(pData, dataSize, &config, &decoder);
  54277. if (result != MA_SUCCESS) {
  54278. return result;
  54279. }
  54280. return ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
  54281. }
  54282. #endif /* MA_NO_DECODING */
  54283. #ifndef MA_NO_ENCODING
  54284. #if defined(MA_HAS_WAV)
  54285. static size_t ma_encoder__internal_on_write_wav(void* pUserData, const void* pData, size_t bytesToWrite)
  54286. {
  54287. ma_encoder* pEncoder = (ma_encoder*)pUserData;
  54288. size_t bytesWritten = 0;
  54289. MA_ASSERT(pEncoder != NULL);
  54290. pEncoder->onWrite(pEncoder, pData, bytesToWrite, &bytesWritten);
  54291. return bytesWritten;
  54292. }
  54293. static ma_bool32 ma_encoder__internal_on_seek_wav(void* pUserData, int offset, ma_dr_wav_seek_origin origin)
  54294. {
  54295. ma_encoder* pEncoder = (ma_encoder*)pUserData;
  54296. ma_result result;
  54297. MA_ASSERT(pEncoder != NULL);
  54298. result = pEncoder->onSeek(pEncoder, offset, (origin == ma_dr_wav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
  54299. if (result != MA_SUCCESS) {
  54300. return MA_FALSE;
  54301. } else {
  54302. return MA_TRUE;
  54303. }
  54304. }
  54305. static ma_result ma_encoder__on_init_wav(ma_encoder* pEncoder)
  54306. {
  54307. ma_dr_wav_data_format wavFormat;
  54308. ma_allocation_callbacks allocationCallbacks;
  54309. ma_dr_wav* pWav;
  54310. MA_ASSERT(pEncoder != NULL);
  54311. pWav = (ma_dr_wav*)ma_malloc(sizeof(*pWav), &pEncoder->config.allocationCallbacks);
  54312. if (pWav == NULL) {
  54313. return MA_OUT_OF_MEMORY;
  54314. }
  54315. wavFormat.container = ma_dr_wav_container_riff;
  54316. wavFormat.channels = pEncoder->config.channels;
  54317. wavFormat.sampleRate = pEncoder->config.sampleRate;
  54318. wavFormat.bitsPerSample = ma_get_bytes_per_sample(pEncoder->config.format) * 8;
  54319. if (pEncoder->config.format == ma_format_f32) {
  54320. wavFormat.format = MA_DR_WAVE_FORMAT_IEEE_FLOAT;
  54321. } else {
  54322. wavFormat.format = MA_DR_WAVE_FORMAT_PCM;
  54323. }
  54324. allocationCallbacks.pUserData = pEncoder->config.allocationCallbacks.pUserData;
  54325. allocationCallbacks.onMalloc = pEncoder->config.allocationCallbacks.onMalloc;
  54326. allocationCallbacks.onRealloc = pEncoder->config.allocationCallbacks.onRealloc;
  54327. allocationCallbacks.onFree = pEncoder->config.allocationCallbacks.onFree;
  54328. if (!ma_dr_wav_init_write(pWav, &wavFormat, ma_encoder__internal_on_write_wav, ma_encoder__internal_on_seek_wav, pEncoder, &allocationCallbacks)) {
  54329. return MA_ERROR;
  54330. }
  54331. pEncoder->pInternalEncoder = pWav;
  54332. return MA_SUCCESS;
  54333. }
  54334. static void ma_encoder__on_uninit_wav(ma_encoder* pEncoder)
  54335. {
  54336. ma_dr_wav* pWav;
  54337. MA_ASSERT(pEncoder != NULL);
  54338. pWav = (ma_dr_wav*)pEncoder->pInternalEncoder;
  54339. MA_ASSERT(pWav != NULL);
  54340. ma_dr_wav_uninit(pWav);
  54341. ma_free(pWav, &pEncoder->config.allocationCallbacks);
  54342. }
  54343. static ma_result ma_encoder__on_write_pcm_frames_wav(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten)
  54344. {
  54345. ma_dr_wav* pWav;
  54346. ma_uint64 framesWritten;
  54347. MA_ASSERT(pEncoder != NULL);
  54348. pWav = (ma_dr_wav*)pEncoder->pInternalEncoder;
  54349. MA_ASSERT(pWav != NULL);
  54350. framesWritten = ma_dr_wav_write_pcm_frames(pWav, frameCount, pFramesIn);
  54351. if (pFramesWritten != NULL) {
  54352. *pFramesWritten = framesWritten;
  54353. }
  54354. return MA_SUCCESS;
  54355. }
  54356. #endif
  54357. MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  54358. {
  54359. ma_encoder_config config;
  54360. MA_ZERO_OBJECT(&config);
  54361. config.encodingFormat = encodingFormat;
  54362. config.format = format;
  54363. config.channels = channels;
  54364. config.sampleRate = sampleRate;
  54365. return config;
  54366. }
  54367. MA_API ma_result ma_encoder_preinit(const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54368. {
  54369. ma_result result;
  54370. if (pEncoder == NULL) {
  54371. return MA_INVALID_ARGS;
  54372. }
  54373. MA_ZERO_OBJECT(pEncoder);
  54374. if (pConfig == NULL) {
  54375. return MA_INVALID_ARGS;
  54376. }
  54377. if (pConfig->format == ma_format_unknown || pConfig->channels == 0 || pConfig->sampleRate == 0) {
  54378. return MA_INVALID_ARGS;
  54379. }
  54380. pEncoder->config = *pConfig;
  54381. result = ma_allocation_callbacks_init_copy(&pEncoder->config.allocationCallbacks, &pConfig->allocationCallbacks);
  54382. if (result != MA_SUCCESS) {
  54383. return result;
  54384. }
  54385. return MA_SUCCESS;
  54386. }
  54387. MA_API ma_result ma_encoder_init__internal(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, ma_encoder* pEncoder)
  54388. {
  54389. ma_result result = MA_SUCCESS;
  54390. /* This assumes ma_encoder_preinit() has been called prior. */
  54391. MA_ASSERT(pEncoder != NULL);
  54392. if (onWrite == NULL || onSeek == NULL) {
  54393. return MA_INVALID_ARGS;
  54394. }
  54395. pEncoder->onWrite = onWrite;
  54396. pEncoder->onSeek = onSeek;
  54397. pEncoder->pUserData = pUserData;
  54398. switch (pEncoder->config.encodingFormat)
  54399. {
  54400. case ma_encoding_format_wav:
  54401. {
  54402. #if defined(MA_HAS_WAV)
  54403. pEncoder->onInit = ma_encoder__on_init_wav;
  54404. pEncoder->onUninit = ma_encoder__on_uninit_wav;
  54405. pEncoder->onWritePCMFrames = ma_encoder__on_write_pcm_frames_wav;
  54406. #else
  54407. result = MA_NO_BACKEND;
  54408. #endif
  54409. } break;
  54410. default:
  54411. {
  54412. result = MA_INVALID_ARGS;
  54413. } break;
  54414. }
  54415. /* Getting here means we should have our backend callbacks set up. */
  54416. if (result == MA_SUCCESS) {
  54417. result = pEncoder->onInit(pEncoder);
  54418. }
  54419. return result;
  54420. }
  54421. static ma_result ma_encoder__on_write_vfs(ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten)
  54422. {
  54423. return ma_vfs_or_default_write(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, pBufferIn, bytesToWrite, pBytesWritten);
  54424. }
  54425. static ma_result ma_encoder__on_seek_vfs(ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin)
  54426. {
  54427. return ma_vfs_or_default_seek(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, offset, origin);
  54428. }
  54429. MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54430. {
  54431. ma_result result;
  54432. ma_vfs_file file;
  54433. result = ma_encoder_preinit(pConfig, pEncoder);
  54434. if (result != MA_SUCCESS) {
  54435. return result;
  54436. }
  54437. /* Now open the file. If this fails we don't need to uninitialize the encoder. */
  54438. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file);
  54439. if (result != MA_SUCCESS) {
  54440. return result;
  54441. }
  54442. pEncoder->data.vfs.pVFS = pVFS;
  54443. pEncoder->data.vfs.file = file;
  54444. result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder);
  54445. if (result != MA_SUCCESS) {
  54446. ma_vfs_or_default_close(pVFS, file);
  54447. return result;
  54448. }
  54449. return MA_SUCCESS;
  54450. }
  54451. MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54452. {
  54453. ma_result result;
  54454. ma_vfs_file file;
  54455. result = ma_encoder_preinit(pConfig, pEncoder);
  54456. if (result != MA_SUCCESS) {
  54457. return result;
  54458. }
  54459. /* Now open the file. If this fails we don't need to uninitialize the encoder. */
  54460. result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file);
  54461. if (result != MA_SUCCESS) {
  54462. return result;
  54463. }
  54464. pEncoder->data.vfs.pVFS = pVFS;
  54465. pEncoder->data.vfs.file = file;
  54466. result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder);
  54467. if (result != MA_SUCCESS) {
  54468. ma_vfs_or_default_close(pVFS, file);
  54469. return result;
  54470. }
  54471. return MA_SUCCESS;
  54472. }
  54473. MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54474. {
  54475. return ma_encoder_init_vfs(NULL, pFilePath, pConfig, pEncoder);
  54476. }
  54477. MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  54478. {
  54479. return ma_encoder_init_vfs_w(NULL, pFilePath, pConfig, pEncoder);
  54480. }
  54481. 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)
  54482. {
  54483. ma_result result;
  54484. result = ma_encoder_preinit(pConfig, pEncoder);
  54485. if (result != MA_SUCCESS) {
  54486. return result;
  54487. }
  54488. return ma_encoder_init__internal(onWrite, onSeek, pUserData, pEncoder);
  54489. }
  54490. MA_API void ma_encoder_uninit(ma_encoder* pEncoder)
  54491. {
  54492. if (pEncoder == NULL) {
  54493. return;
  54494. }
  54495. if (pEncoder->onUninit) {
  54496. pEncoder->onUninit(pEncoder);
  54497. }
  54498. /* If we have a file handle, close it. */
  54499. if (pEncoder->onWrite == ma_encoder__on_write_vfs) {
  54500. ma_vfs_or_default_close(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file);
  54501. pEncoder->data.vfs.file = NULL;
  54502. }
  54503. }
  54504. MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten)
  54505. {
  54506. if (pFramesWritten != NULL) {
  54507. *pFramesWritten = 0;
  54508. }
  54509. if (pEncoder == NULL || pFramesIn == NULL) {
  54510. return MA_INVALID_ARGS;
  54511. }
  54512. return pEncoder->onWritePCMFrames(pEncoder, pFramesIn, frameCount, pFramesWritten);
  54513. }
  54514. #endif /* MA_NO_ENCODING */
  54515. /**************************************************************************************************************************************************************
  54516. Generation
  54517. **************************************************************************************************************************************************************/
  54518. #ifndef MA_NO_GENERATION
  54519. 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)
  54520. {
  54521. ma_waveform_config config;
  54522. MA_ZERO_OBJECT(&config);
  54523. config.format = format;
  54524. config.channels = channels;
  54525. config.sampleRate = sampleRate;
  54526. config.type = type;
  54527. config.amplitude = amplitude;
  54528. config.frequency = frequency;
  54529. return config;
  54530. }
  54531. static ma_result ma_waveform__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54532. {
  54533. return ma_waveform_read_pcm_frames((ma_waveform*)pDataSource, pFramesOut, frameCount, pFramesRead);
  54534. }
  54535. static ma_result ma_waveform__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  54536. {
  54537. return ma_waveform_seek_to_pcm_frame((ma_waveform*)pDataSource, frameIndex);
  54538. }
  54539. 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)
  54540. {
  54541. ma_waveform* pWaveform = (ma_waveform*)pDataSource;
  54542. *pFormat = pWaveform->config.format;
  54543. *pChannels = pWaveform->config.channels;
  54544. *pSampleRate = pWaveform->config.sampleRate;
  54545. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pWaveform->config.channels);
  54546. return MA_SUCCESS;
  54547. }
  54548. static ma_result ma_waveform__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  54549. {
  54550. ma_waveform* pWaveform = (ma_waveform*)pDataSource;
  54551. *pCursor = (ma_uint64)(pWaveform->time / pWaveform->advance);
  54552. return MA_SUCCESS;
  54553. }
  54554. static double ma_waveform__calculate_advance(ma_uint32 sampleRate, double frequency)
  54555. {
  54556. return (1.0 / (sampleRate / frequency));
  54557. }
  54558. static void ma_waveform__update_advance(ma_waveform* pWaveform)
  54559. {
  54560. pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency);
  54561. }
  54562. static ma_data_source_vtable g_ma_waveform_data_source_vtable =
  54563. {
  54564. ma_waveform__data_source_on_read,
  54565. ma_waveform__data_source_on_seek,
  54566. ma_waveform__data_source_on_get_data_format,
  54567. ma_waveform__data_source_on_get_cursor,
  54568. NULL, /* onGetLength. There's no notion of a length in waveforms. */
  54569. NULL, /* onSetLooping */
  54570. 0
  54571. };
  54572. MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform)
  54573. {
  54574. ma_result result;
  54575. ma_data_source_config dataSourceConfig;
  54576. if (pWaveform == NULL) {
  54577. return MA_INVALID_ARGS;
  54578. }
  54579. MA_ZERO_OBJECT(pWaveform);
  54580. dataSourceConfig = ma_data_source_config_init();
  54581. dataSourceConfig.vtable = &g_ma_waveform_data_source_vtable;
  54582. result = ma_data_source_init(&dataSourceConfig, &pWaveform->ds);
  54583. if (result != MA_SUCCESS) {
  54584. return result;
  54585. }
  54586. pWaveform->config = *pConfig;
  54587. pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency);
  54588. pWaveform->time = 0;
  54589. return MA_SUCCESS;
  54590. }
  54591. MA_API void ma_waveform_uninit(ma_waveform* pWaveform)
  54592. {
  54593. if (pWaveform == NULL) {
  54594. return;
  54595. }
  54596. ma_data_source_uninit(&pWaveform->ds);
  54597. }
  54598. MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude)
  54599. {
  54600. if (pWaveform == NULL) {
  54601. return MA_INVALID_ARGS;
  54602. }
  54603. pWaveform->config.amplitude = amplitude;
  54604. return MA_SUCCESS;
  54605. }
  54606. MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency)
  54607. {
  54608. if (pWaveform == NULL) {
  54609. return MA_INVALID_ARGS;
  54610. }
  54611. pWaveform->config.frequency = frequency;
  54612. ma_waveform__update_advance(pWaveform);
  54613. return MA_SUCCESS;
  54614. }
  54615. MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type)
  54616. {
  54617. if (pWaveform == NULL) {
  54618. return MA_INVALID_ARGS;
  54619. }
  54620. pWaveform->config.type = type;
  54621. return MA_SUCCESS;
  54622. }
  54623. MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate)
  54624. {
  54625. if (pWaveform == NULL) {
  54626. return MA_INVALID_ARGS;
  54627. }
  54628. pWaveform->config.sampleRate = sampleRate;
  54629. ma_waveform__update_advance(pWaveform);
  54630. return MA_SUCCESS;
  54631. }
  54632. static float ma_waveform_sine_f32(double time, double amplitude)
  54633. {
  54634. return (float)(ma_sind(MA_TAU_D * time) * amplitude);
  54635. }
  54636. static ma_int16 ma_waveform_sine_s16(double time, double amplitude)
  54637. {
  54638. return ma_pcm_sample_f32_to_s16(ma_waveform_sine_f32(time, amplitude));
  54639. }
  54640. static float ma_waveform_square_f32(double time, double dutyCycle, double amplitude)
  54641. {
  54642. double f = time - (ma_int64)time;
  54643. double r;
  54644. if (f < dutyCycle) {
  54645. r = amplitude;
  54646. } else {
  54647. r = -amplitude;
  54648. }
  54649. return (float)r;
  54650. }
  54651. static ma_int16 ma_waveform_square_s16(double time, double dutyCycle, double amplitude)
  54652. {
  54653. return ma_pcm_sample_f32_to_s16(ma_waveform_square_f32(time, dutyCycle, amplitude));
  54654. }
  54655. static float ma_waveform_triangle_f32(double time, double amplitude)
  54656. {
  54657. double f = time - (ma_int64)time;
  54658. double r;
  54659. r = 2 * ma_abs(2 * (f - 0.5)) - 1;
  54660. return (float)(r * amplitude);
  54661. }
  54662. static ma_int16 ma_waveform_triangle_s16(double time, double amplitude)
  54663. {
  54664. return ma_pcm_sample_f32_to_s16(ma_waveform_triangle_f32(time, amplitude));
  54665. }
  54666. static float ma_waveform_sawtooth_f32(double time, double amplitude)
  54667. {
  54668. double f = time - (ma_int64)time;
  54669. double r;
  54670. r = 2 * (f - 0.5);
  54671. return (float)(r * amplitude);
  54672. }
  54673. static ma_int16 ma_waveform_sawtooth_s16(double time, double amplitude)
  54674. {
  54675. return ma_pcm_sample_f32_to_s16(ma_waveform_sawtooth_f32(time, amplitude));
  54676. }
  54677. static void ma_waveform_read_pcm_frames__sine(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54678. {
  54679. ma_uint64 iFrame;
  54680. ma_uint64 iChannel;
  54681. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54682. ma_uint32 bpf = bps * pWaveform->config.channels;
  54683. MA_ASSERT(pWaveform != NULL);
  54684. MA_ASSERT(pFramesOut != NULL);
  54685. if (pWaveform->config.format == ma_format_f32) {
  54686. float* pFramesOutF32 = (float*)pFramesOut;
  54687. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54688. float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude);
  54689. pWaveform->time += pWaveform->advance;
  54690. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54691. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54692. }
  54693. }
  54694. } else if (pWaveform->config.format == ma_format_s16) {
  54695. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54696. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54697. ma_int16 s = ma_waveform_sine_s16(pWaveform->time, pWaveform->config.amplitude);
  54698. pWaveform->time += pWaveform->advance;
  54699. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54700. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54701. }
  54702. }
  54703. } else {
  54704. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54705. float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude);
  54706. pWaveform->time += pWaveform->advance;
  54707. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54708. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54709. }
  54710. }
  54711. }
  54712. }
  54713. static void ma_waveform_read_pcm_frames__square(ma_waveform* pWaveform, double dutyCycle, void* pFramesOut, ma_uint64 frameCount)
  54714. {
  54715. ma_uint64 iFrame;
  54716. ma_uint64 iChannel;
  54717. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54718. ma_uint32 bpf = bps * pWaveform->config.channels;
  54719. MA_ASSERT(pWaveform != NULL);
  54720. MA_ASSERT(pFramesOut != NULL);
  54721. if (pWaveform->config.format == ma_format_f32) {
  54722. float* pFramesOutF32 = (float*)pFramesOut;
  54723. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54724. float s = ma_waveform_square_f32(pWaveform->time, dutyCycle, pWaveform->config.amplitude);
  54725. pWaveform->time += pWaveform->advance;
  54726. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54727. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54728. }
  54729. }
  54730. } else if (pWaveform->config.format == ma_format_s16) {
  54731. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54732. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54733. ma_int16 s = ma_waveform_square_s16(pWaveform->time, dutyCycle, pWaveform->config.amplitude);
  54734. pWaveform->time += pWaveform->advance;
  54735. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54736. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54737. }
  54738. }
  54739. } else {
  54740. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54741. float s = ma_waveform_square_f32(pWaveform->time, dutyCycle, pWaveform->config.amplitude);
  54742. pWaveform->time += pWaveform->advance;
  54743. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54744. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54745. }
  54746. }
  54747. }
  54748. }
  54749. static void ma_waveform_read_pcm_frames__triangle(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54750. {
  54751. ma_uint64 iFrame;
  54752. ma_uint64 iChannel;
  54753. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54754. ma_uint32 bpf = bps * pWaveform->config.channels;
  54755. MA_ASSERT(pWaveform != NULL);
  54756. MA_ASSERT(pFramesOut != NULL);
  54757. if (pWaveform->config.format == ma_format_f32) {
  54758. float* pFramesOutF32 = (float*)pFramesOut;
  54759. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54760. float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude);
  54761. pWaveform->time += pWaveform->advance;
  54762. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54763. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54764. }
  54765. }
  54766. } else if (pWaveform->config.format == ma_format_s16) {
  54767. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54768. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54769. ma_int16 s = ma_waveform_triangle_s16(pWaveform->time, pWaveform->config.amplitude);
  54770. pWaveform->time += pWaveform->advance;
  54771. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54772. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54773. }
  54774. }
  54775. } else {
  54776. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54777. float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude);
  54778. pWaveform->time += pWaveform->advance;
  54779. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54780. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54781. }
  54782. }
  54783. }
  54784. }
  54785. static void ma_waveform_read_pcm_frames__sawtooth(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  54786. {
  54787. ma_uint64 iFrame;
  54788. ma_uint64 iChannel;
  54789. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  54790. ma_uint32 bpf = bps * pWaveform->config.channels;
  54791. MA_ASSERT(pWaveform != NULL);
  54792. MA_ASSERT(pFramesOut != NULL);
  54793. if (pWaveform->config.format == ma_format_f32) {
  54794. float* pFramesOutF32 = (float*)pFramesOut;
  54795. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54796. float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude);
  54797. pWaveform->time += pWaveform->advance;
  54798. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54799. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  54800. }
  54801. }
  54802. } else if (pWaveform->config.format == ma_format_s16) {
  54803. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  54804. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54805. ma_int16 s = ma_waveform_sawtooth_s16(pWaveform->time, pWaveform->config.amplitude);
  54806. pWaveform->time += pWaveform->advance;
  54807. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54808. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  54809. }
  54810. }
  54811. } else {
  54812. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  54813. float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude);
  54814. pWaveform->time += pWaveform->advance;
  54815. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  54816. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  54817. }
  54818. }
  54819. }
  54820. }
  54821. MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54822. {
  54823. if (pFramesRead != NULL) {
  54824. *pFramesRead = 0;
  54825. }
  54826. if (frameCount == 0) {
  54827. return MA_INVALID_ARGS;
  54828. }
  54829. if (pWaveform == NULL) {
  54830. return MA_INVALID_ARGS;
  54831. }
  54832. if (pFramesOut != NULL) {
  54833. switch (pWaveform->config.type)
  54834. {
  54835. case ma_waveform_type_sine:
  54836. {
  54837. ma_waveform_read_pcm_frames__sine(pWaveform, pFramesOut, frameCount);
  54838. } break;
  54839. case ma_waveform_type_square:
  54840. {
  54841. ma_waveform_read_pcm_frames__square(pWaveform, 0.5, pFramesOut, frameCount);
  54842. } break;
  54843. case ma_waveform_type_triangle:
  54844. {
  54845. ma_waveform_read_pcm_frames__triangle(pWaveform, pFramesOut, frameCount);
  54846. } break;
  54847. case ma_waveform_type_sawtooth:
  54848. {
  54849. ma_waveform_read_pcm_frames__sawtooth(pWaveform, pFramesOut, frameCount);
  54850. } break;
  54851. default: return MA_INVALID_OPERATION; /* Unknown waveform type. */
  54852. }
  54853. } else {
  54854. pWaveform->time += pWaveform->advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */
  54855. }
  54856. if (pFramesRead != NULL) {
  54857. *pFramesRead = frameCount;
  54858. }
  54859. return MA_SUCCESS;
  54860. }
  54861. MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex)
  54862. {
  54863. if (pWaveform == NULL) {
  54864. return MA_INVALID_ARGS;
  54865. }
  54866. pWaveform->time = pWaveform->advance * (ma_int64)frameIndex; /* Casting for VC6. Won't be an issue in practice. */
  54867. return MA_SUCCESS;
  54868. }
  54869. MA_API ma_pulsewave_config ma_pulsewave_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double dutyCycle, double amplitude, double frequency)
  54870. {
  54871. ma_pulsewave_config config;
  54872. MA_ZERO_OBJECT(&config);
  54873. config.format = format;
  54874. config.channels = channels;
  54875. config.sampleRate = sampleRate;
  54876. config.dutyCycle = dutyCycle;
  54877. config.amplitude = amplitude;
  54878. config.frequency = frequency;
  54879. return config;
  54880. }
  54881. MA_API ma_result ma_pulsewave_init(const ma_pulsewave_config* pConfig, ma_pulsewave* pWaveform)
  54882. {
  54883. ma_result result;
  54884. ma_waveform_config config;
  54885. if (pWaveform == NULL) {
  54886. return MA_INVALID_ARGS;
  54887. }
  54888. MA_ZERO_OBJECT(pWaveform);
  54889. config = ma_waveform_config_init(
  54890. pConfig->format,
  54891. pConfig->channels,
  54892. pConfig->sampleRate,
  54893. ma_waveform_type_square,
  54894. pConfig->amplitude,
  54895. pConfig->frequency
  54896. );
  54897. result = ma_waveform_init(&config, &pWaveform->waveform);
  54898. ma_pulsewave_set_duty_cycle(pWaveform, pConfig->dutyCycle);
  54899. return result;
  54900. }
  54901. MA_API void ma_pulsewave_uninit(ma_pulsewave* pWaveform)
  54902. {
  54903. if (pWaveform == NULL) {
  54904. return;
  54905. }
  54906. ma_waveform_uninit(&pWaveform->waveform);
  54907. }
  54908. MA_API ma_result ma_pulsewave_read_pcm_frames(ma_pulsewave* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54909. {
  54910. if (pFramesRead != NULL) {
  54911. *pFramesRead = 0;
  54912. }
  54913. if (frameCount == 0) {
  54914. return MA_INVALID_ARGS;
  54915. }
  54916. if (pWaveform == NULL) {
  54917. return MA_INVALID_ARGS;
  54918. }
  54919. if (pFramesOut != NULL) {
  54920. ma_waveform_read_pcm_frames__square(&pWaveform->waveform, pWaveform->config.dutyCycle, pFramesOut, frameCount);
  54921. } else {
  54922. pWaveform->waveform.time += pWaveform->waveform.advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */
  54923. }
  54924. if (pFramesRead != NULL) {
  54925. *pFramesRead = frameCount;
  54926. }
  54927. return MA_SUCCESS;
  54928. }
  54929. MA_API ma_result ma_pulsewave_seek_to_pcm_frame(ma_pulsewave* pWaveform, ma_uint64 frameIndex)
  54930. {
  54931. if (pWaveform == NULL) {
  54932. return MA_INVALID_ARGS;
  54933. }
  54934. ma_waveform_seek_to_pcm_frame(&pWaveform->waveform, frameIndex);
  54935. return MA_SUCCESS;
  54936. }
  54937. MA_API ma_result ma_pulsewave_set_amplitude(ma_pulsewave* pWaveform, double amplitude)
  54938. {
  54939. if (pWaveform == NULL) {
  54940. return MA_INVALID_ARGS;
  54941. }
  54942. pWaveform->config.amplitude = amplitude;
  54943. ma_waveform_set_amplitude(&pWaveform->waveform, amplitude);
  54944. return MA_SUCCESS;
  54945. }
  54946. MA_API ma_result ma_pulsewave_set_frequency(ma_pulsewave* pWaveform, double frequency)
  54947. {
  54948. if (pWaveform == NULL) {
  54949. return MA_INVALID_ARGS;
  54950. }
  54951. pWaveform->config.frequency = frequency;
  54952. ma_waveform_set_frequency(&pWaveform->waveform, frequency);
  54953. return MA_SUCCESS;
  54954. }
  54955. MA_API ma_result ma_pulsewave_set_sample_rate(ma_pulsewave* pWaveform, ma_uint32 sampleRate)
  54956. {
  54957. if (pWaveform == NULL) {
  54958. return MA_INVALID_ARGS;
  54959. }
  54960. pWaveform->config.sampleRate = sampleRate;
  54961. ma_waveform_set_sample_rate(&pWaveform->waveform, sampleRate);
  54962. return MA_SUCCESS;
  54963. }
  54964. MA_API ma_result ma_pulsewave_set_duty_cycle(ma_pulsewave* pWaveform, double dutyCycle)
  54965. {
  54966. if (pWaveform == NULL) {
  54967. return MA_INVALID_ARGS;
  54968. }
  54969. pWaveform->config.dutyCycle = dutyCycle;
  54970. return MA_SUCCESS;
  54971. }
  54972. MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude)
  54973. {
  54974. ma_noise_config config;
  54975. MA_ZERO_OBJECT(&config);
  54976. config.format = format;
  54977. config.channels = channels;
  54978. config.type = type;
  54979. config.seed = seed;
  54980. config.amplitude = amplitude;
  54981. if (config.seed == 0) {
  54982. config.seed = MA_DEFAULT_LCG_SEED;
  54983. }
  54984. return config;
  54985. }
  54986. static ma_result ma_noise__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54987. {
  54988. return ma_noise_read_pcm_frames((ma_noise*)pDataSource, pFramesOut, frameCount, pFramesRead);
  54989. }
  54990. static ma_result ma_noise__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  54991. {
  54992. /* No-op. Just pretend to be successful. */
  54993. (void)pDataSource;
  54994. (void)frameIndex;
  54995. return MA_SUCCESS;
  54996. }
  54997. 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)
  54998. {
  54999. ma_noise* pNoise = (ma_noise*)pDataSource;
  55000. *pFormat = pNoise->config.format;
  55001. *pChannels = pNoise->config.channels;
  55002. *pSampleRate = 0; /* There is no notion of sample rate with noise generation. */
  55003. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pNoise->config.channels);
  55004. return MA_SUCCESS;
  55005. }
  55006. static ma_data_source_vtable g_ma_noise_data_source_vtable =
  55007. {
  55008. ma_noise__data_source_on_read,
  55009. ma_noise__data_source_on_seek, /* No-op for noise. */
  55010. ma_noise__data_source_on_get_data_format,
  55011. NULL, /* onGetCursor. No notion of a cursor for noise. */
  55012. NULL, /* onGetLength. No notion of a length for noise. */
  55013. NULL, /* onSetLooping */
  55014. 0
  55015. };
  55016. #ifndef MA_PINK_NOISE_BIN_SIZE
  55017. #define MA_PINK_NOISE_BIN_SIZE 16
  55018. #endif
  55019. typedef struct
  55020. {
  55021. size_t sizeInBytes;
  55022. struct
  55023. {
  55024. size_t binOffset;
  55025. size_t accumulationOffset;
  55026. size_t counterOffset;
  55027. } pink;
  55028. struct
  55029. {
  55030. size_t accumulationOffset;
  55031. } brownian;
  55032. } ma_noise_heap_layout;
  55033. static ma_result ma_noise_get_heap_layout(const ma_noise_config* pConfig, ma_noise_heap_layout* pHeapLayout)
  55034. {
  55035. MA_ASSERT(pHeapLayout != NULL);
  55036. MA_ZERO_OBJECT(pHeapLayout);
  55037. if (pConfig == NULL) {
  55038. return MA_INVALID_ARGS;
  55039. }
  55040. if (pConfig->channels == 0) {
  55041. return MA_INVALID_ARGS;
  55042. }
  55043. pHeapLayout->sizeInBytes = 0;
  55044. /* Pink. */
  55045. if (pConfig->type == ma_noise_type_pink) {
  55046. /* bin */
  55047. pHeapLayout->pink.binOffset = pHeapLayout->sizeInBytes;
  55048. pHeapLayout->sizeInBytes += sizeof(double*) * pConfig->channels;
  55049. pHeapLayout->sizeInBytes += sizeof(double ) * pConfig->channels * MA_PINK_NOISE_BIN_SIZE;
  55050. /* accumulation */
  55051. pHeapLayout->pink.accumulationOffset = pHeapLayout->sizeInBytes;
  55052. pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels;
  55053. /* counter */
  55054. pHeapLayout->pink.counterOffset = pHeapLayout->sizeInBytes;
  55055. pHeapLayout->sizeInBytes += sizeof(ma_uint32) * pConfig->channels;
  55056. }
  55057. /* Brownian. */
  55058. if (pConfig->type == ma_noise_type_brownian) {
  55059. /* accumulation */
  55060. pHeapLayout->brownian.accumulationOffset = pHeapLayout->sizeInBytes;
  55061. pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels;
  55062. }
  55063. /* Make sure allocation size is aligned. */
  55064. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  55065. return MA_SUCCESS;
  55066. }
  55067. MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes)
  55068. {
  55069. ma_result result;
  55070. ma_noise_heap_layout heapLayout;
  55071. if (pHeapSizeInBytes == NULL) {
  55072. return MA_INVALID_ARGS;
  55073. }
  55074. *pHeapSizeInBytes = 0;
  55075. result = ma_noise_get_heap_layout(pConfig, &heapLayout);
  55076. if (result != MA_SUCCESS) {
  55077. return result;
  55078. }
  55079. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  55080. return MA_SUCCESS;
  55081. }
  55082. MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise)
  55083. {
  55084. ma_result result;
  55085. ma_noise_heap_layout heapLayout;
  55086. ma_data_source_config dataSourceConfig;
  55087. ma_uint32 iChannel;
  55088. if (pNoise == NULL) {
  55089. return MA_INVALID_ARGS;
  55090. }
  55091. MA_ZERO_OBJECT(pNoise);
  55092. result = ma_noise_get_heap_layout(pConfig, &heapLayout);
  55093. if (result != MA_SUCCESS) {
  55094. return result;
  55095. }
  55096. pNoise->_pHeap = pHeap;
  55097. MA_ZERO_MEMORY(pNoise->_pHeap, heapLayout.sizeInBytes);
  55098. dataSourceConfig = ma_data_source_config_init();
  55099. dataSourceConfig.vtable = &g_ma_noise_data_source_vtable;
  55100. result = ma_data_source_init(&dataSourceConfig, &pNoise->ds);
  55101. if (result != MA_SUCCESS) {
  55102. return result;
  55103. }
  55104. pNoise->config = *pConfig;
  55105. ma_lcg_seed(&pNoise->lcg, pConfig->seed);
  55106. if (pNoise->config.type == ma_noise_type_pink) {
  55107. pNoise->state.pink.bin = (double** )ma_offset_ptr(pHeap, heapLayout.pink.binOffset);
  55108. pNoise->state.pink.accumulation = (double* )ma_offset_ptr(pHeap, heapLayout.pink.accumulationOffset);
  55109. pNoise->state.pink.counter = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.pink.counterOffset);
  55110. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  55111. 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));
  55112. pNoise->state.pink.accumulation[iChannel] = 0;
  55113. pNoise->state.pink.counter[iChannel] = 1;
  55114. }
  55115. }
  55116. if (pNoise->config.type == ma_noise_type_brownian) {
  55117. pNoise->state.brownian.accumulation = (double*)ma_offset_ptr(pHeap, heapLayout.brownian.accumulationOffset);
  55118. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  55119. pNoise->state.brownian.accumulation[iChannel] = 0;
  55120. }
  55121. }
  55122. return MA_SUCCESS;
  55123. }
  55124. MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise)
  55125. {
  55126. ma_result result;
  55127. size_t heapSizeInBytes;
  55128. void* pHeap;
  55129. result = ma_noise_get_heap_size(pConfig, &heapSizeInBytes);
  55130. if (result != MA_SUCCESS) {
  55131. return result;
  55132. }
  55133. if (heapSizeInBytes > 0) {
  55134. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  55135. if (pHeap == NULL) {
  55136. return MA_OUT_OF_MEMORY;
  55137. }
  55138. } else {
  55139. pHeap = NULL;
  55140. }
  55141. result = ma_noise_init_preallocated(pConfig, pHeap, pNoise);
  55142. if (result != MA_SUCCESS) {
  55143. ma_free(pHeap, pAllocationCallbacks);
  55144. return result;
  55145. }
  55146. pNoise->_ownsHeap = MA_TRUE;
  55147. return MA_SUCCESS;
  55148. }
  55149. MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks)
  55150. {
  55151. if (pNoise == NULL) {
  55152. return;
  55153. }
  55154. ma_data_source_uninit(&pNoise->ds);
  55155. if (pNoise->_ownsHeap) {
  55156. ma_free(pNoise->_pHeap, pAllocationCallbacks);
  55157. }
  55158. }
  55159. MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude)
  55160. {
  55161. if (pNoise == NULL) {
  55162. return MA_INVALID_ARGS;
  55163. }
  55164. pNoise->config.amplitude = amplitude;
  55165. return MA_SUCCESS;
  55166. }
  55167. MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed)
  55168. {
  55169. if (pNoise == NULL) {
  55170. return MA_INVALID_ARGS;
  55171. }
  55172. pNoise->lcg.state = seed;
  55173. return MA_SUCCESS;
  55174. }
  55175. MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type)
  55176. {
  55177. if (pNoise == NULL) {
  55178. return MA_INVALID_ARGS;
  55179. }
  55180. /*
  55181. This function should never have been implemented in the first place. Changing the type dynamically is not
  55182. supported. Instead you need to uninitialize and reinitiailize a fresh `ma_noise` object. This function
  55183. will be removed in version 0.12.
  55184. */
  55185. MA_ASSERT(MA_FALSE);
  55186. (void)type;
  55187. return MA_INVALID_OPERATION;
  55188. }
  55189. static MA_INLINE float ma_noise_f32_white(ma_noise* pNoise)
  55190. {
  55191. return (float)(ma_lcg_rand_f64(&pNoise->lcg) * pNoise->config.amplitude);
  55192. }
  55193. static MA_INLINE ma_int16 ma_noise_s16_white(ma_noise* pNoise)
  55194. {
  55195. return ma_pcm_sample_f32_to_s16(ma_noise_f32_white(pNoise));
  55196. }
  55197. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__white(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  55198. {
  55199. ma_uint64 iFrame;
  55200. ma_uint32 iChannel;
  55201. const ma_uint32 channels = pNoise->config.channels;
  55202. MA_ASSUME(channels > 0);
  55203. if (pNoise->config.format == ma_format_f32) {
  55204. float* pFramesOutF32 = (float*)pFramesOut;
  55205. if (pNoise->config.duplicateChannels) {
  55206. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55207. float s = ma_noise_f32_white(pNoise);
  55208. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55209. pFramesOutF32[iFrame*channels + iChannel] = s;
  55210. }
  55211. }
  55212. } else {
  55213. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55214. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55215. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_white(pNoise);
  55216. }
  55217. }
  55218. }
  55219. } else if (pNoise->config.format == ma_format_s16) {
  55220. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  55221. if (pNoise->config.duplicateChannels) {
  55222. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55223. ma_int16 s = ma_noise_s16_white(pNoise);
  55224. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55225. pFramesOutS16[iFrame*channels + iChannel] = s;
  55226. }
  55227. }
  55228. } else {
  55229. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55230. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55231. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_white(pNoise);
  55232. }
  55233. }
  55234. }
  55235. } else {
  55236. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  55237. const ma_uint32 bpf = bps * channels;
  55238. if (pNoise->config.duplicateChannels) {
  55239. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55240. float s = ma_noise_f32_white(pNoise);
  55241. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55242. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55243. }
  55244. }
  55245. } else {
  55246. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55247. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55248. float s = ma_noise_f32_white(pNoise);
  55249. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55250. }
  55251. }
  55252. }
  55253. }
  55254. return frameCount;
  55255. }
  55256. static MA_INLINE unsigned int ma_tzcnt32(unsigned int x)
  55257. {
  55258. unsigned int n;
  55259. /* Special case for odd numbers since they should happen about half the time. */
  55260. if (x & 0x1) {
  55261. return 0;
  55262. }
  55263. if (x == 0) {
  55264. return sizeof(x) << 3;
  55265. }
  55266. n = 1;
  55267. if ((x & 0x0000FFFF) == 0) { x >>= 16; n += 16; }
  55268. if ((x & 0x000000FF) == 0) { x >>= 8; n += 8; }
  55269. if ((x & 0x0000000F) == 0) { x >>= 4; n += 4; }
  55270. if ((x & 0x00000003) == 0) { x >>= 2; n += 2; }
  55271. n -= x & 0x00000001;
  55272. return n;
  55273. }
  55274. /*
  55275. Pink noise generation based on Tonic (public domain) with modifications. https://github.com/TonicAudio/Tonic/blob/master/src/Tonic/Noise.h
  55276. This is basically _the_ reference for pink noise from what I've found: http://www.firstpr.com.au/dsp/pink-noise/
  55277. */
  55278. static MA_INLINE float ma_noise_f32_pink(ma_noise* pNoise, ma_uint32 iChannel)
  55279. {
  55280. double result;
  55281. double binPrev;
  55282. double binNext;
  55283. unsigned int ibin;
  55284. ibin = ma_tzcnt32(pNoise->state.pink.counter[iChannel]) & (MA_PINK_NOISE_BIN_SIZE - 1);
  55285. binPrev = pNoise->state.pink.bin[iChannel][ibin];
  55286. binNext = ma_lcg_rand_f64(&pNoise->lcg);
  55287. pNoise->state.pink.bin[iChannel][ibin] = binNext;
  55288. pNoise->state.pink.accumulation[iChannel] += (binNext - binPrev);
  55289. pNoise->state.pink.counter[iChannel] += 1;
  55290. result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.pink.accumulation[iChannel]);
  55291. result /= 10;
  55292. return (float)(result * pNoise->config.amplitude);
  55293. }
  55294. static MA_INLINE ma_int16 ma_noise_s16_pink(ma_noise* pNoise, ma_uint32 iChannel)
  55295. {
  55296. return ma_pcm_sample_f32_to_s16(ma_noise_f32_pink(pNoise, iChannel));
  55297. }
  55298. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__pink(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  55299. {
  55300. ma_uint64 iFrame;
  55301. ma_uint32 iChannel;
  55302. const ma_uint32 channels = pNoise->config.channels;
  55303. MA_ASSUME(channels > 0);
  55304. if (pNoise->config.format == ma_format_f32) {
  55305. float* pFramesOutF32 = (float*)pFramesOut;
  55306. if (pNoise->config.duplicateChannels) {
  55307. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55308. float s = ma_noise_f32_pink(pNoise, 0);
  55309. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55310. pFramesOutF32[iFrame*channels + iChannel] = s;
  55311. }
  55312. }
  55313. } else {
  55314. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55315. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55316. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_pink(pNoise, iChannel);
  55317. }
  55318. }
  55319. }
  55320. } else if (pNoise->config.format == ma_format_s16) {
  55321. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  55322. if (pNoise->config.duplicateChannels) {
  55323. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55324. ma_int16 s = ma_noise_s16_pink(pNoise, 0);
  55325. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55326. pFramesOutS16[iFrame*channels + iChannel] = s;
  55327. }
  55328. }
  55329. } else {
  55330. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55331. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55332. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_pink(pNoise, iChannel);
  55333. }
  55334. }
  55335. }
  55336. } else {
  55337. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  55338. const ma_uint32 bpf = bps * channels;
  55339. if (pNoise->config.duplicateChannels) {
  55340. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55341. float s = ma_noise_f32_pink(pNoise, 0);
  55342. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55343. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55344. }
  55345. }
  55346. } else {
  55347. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55348. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55349. float s = ma_noise_f32_pink(pNoise, iChannel);
  55350. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55351. }
  55352. }
  55353. }
  55354. }
  55355. return frameCount;
  55356. }
  55357. static MA_INLINE float ma_noise_f32_brownian(ma_noise* pNoise, ma_uint32 iChannel)
  55358. {
  55359. double result;
  55360. result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.brownian.accumulation[iChannel]);
  55361. result /= 1.005; /* Don't escape the -1..1 range on average. */
  55362. pNoise->state.brownian.accumulation[iChannel] = result;
  55363. result /= 20;
  55364. return (float)(result * pNoise->config.amplitude);
  55365. }
  55366. static MA_INLINE ma_int16 ma_noise_s16_brownian(ma_noise* pNoise, ma_uint32 iChannel)
  55367. {
  55368. return ma_pcm_sample_f32_to_s16(ma_noise_f32_brownian(pNoise, iChannel));
  55369. }
  55370. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__brownian(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  55371. {
  55372. ma_uint64 iFrame;
  55373. ma_uint32 iChannel;
  55374. const ma_uint32 channels = pNoise->config.channels;
  55375. MA_ASSUME(channels > 0);
  55376. if (pNoise->config.format == ma_format_f32) {
  55377. float* pFramesOutF32 = (float*)pFramesOut;
  55378. if (pNoise->config.duplicateChannels) {
  55379. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55380. float s = ma_noise_f32_brownian(pNoise, 0);
  55381. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55382. pFramesOutF32[iFrame*channels + iChannel] = s;
  55383. }
  55384. }
  55385. } else {
  55386. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55387. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55388. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_brownian(pNoise, iChannel);
  55389. }
  55390. }
  55391. }
  55392. } else if (pNoise->config.format == ma_format_s16) {
  55393. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  55394. if (pNoise->config.duplicateChannels) {
  55395. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55396. ma_int16 s = ma_noise_s16_brownian(pNoise, 0);
  55397. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55398. pFramesOutS16[iFrame*channels + iChannel] = s;
  55399. }
  55400. }
  55401. } else {
  55402. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55403. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55404. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_brownian(pNoise, iChannel);
  55405. }
  55406. }
  55407. }
  55408. } else {
  55409. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  55410. const ma_uint32 bpf = bps * channels;
  55411. if (pNoise->config.duplicateChannels) {
  55412. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55413. float s = ma_noise_f32_brownian(pNoise, 0);
  55414. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55415. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55416. }
  55417. }
  55418. } else {
  55419. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  55420. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  55421. float s = ma_noise_f32_brownian(pNoise, iChannel);
  55422. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  55423. }
  55424. }
  55425. }
  55426. }
  55427. return frameCount;
  55428. }
  55429. MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  55430. {
  55431. ma_uint64 framesRead = 0;
  55432. if (pFramesRead != NULL) {
  55433. *pFramesRead = 0;
  55434. }
  55435. if (frameCount == 0) {
  55436. return MA_INVALID_ARGS;
  55437. }
  55438. if (pNoise == NULL) {
  55439. return MA_INVALID_ARGS;
  55440. }
  55441. /* 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. */
  55442. if (pFramesOut == NULL) {
  55443. framesRead = frameCount;
  55444. } else {
  55445. switch (pNoise->config.type) {
  55446. case ma_noise_type_white: framesRead = ma_noise_read_pcm_frames__white (pNoise, pFramesOut, frameCount); break;
  55447. case ma_noise_type_pink: framesRead = ma_noise_read_pcm_frames__pink (pNoise, pFramesOut, frameCount); break;
  55448. case ma_noise_type_brownian: framesRead = ma_noise_read_pcm_frames__brownian(pNoise, pFramesOut, frameCount); break;
  55449. default: return MA_INVALID_OPERATION; /* Unknown noise type. */
  55450. }
  55451. }
  55452. if (pFramesRead != NULL) {
  55453. *pFramesRead = framesRead;
  55454. }
  55455. return MA_SUCCESS;
  55456. }
  55457. #endif /* MA_NO_GENERATION */
  55458. #ifndef MA_NO_RESOURCE_MANAGER
  55459. #ifndef MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS
  55460. #define MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS 1000
  55461. #endif
  55462. #ifndef MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY
  55463. #define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY 1024
  55464. #endif
  55465. MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void)
  55466. {
  55467. ma_resource_manager_pipeline_notifications notifications;
  55468. MA_ZERO_OBJECT(&notifications);
  55469. return notifications;
  55470. }
  55471. static void ma_resource_manager_pipeline_notifications_signal_all_notifications(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  55472. {
  55473. if (pPipelineNotifications == NULL) {
  55474. return;
  55475. }
  55476. if (pPipelineNotifications->init.pNotification) { ma_async_notification_signal(pPipelineNotifications->init.pNotification); }
  55477. if (pPipelineNotifications->done.pNotification) { ma_async_notification_signal(pPipelineNotifications->done.pNotification); }
  55478. }
  55479. static void ma_resource_manager_pipeline_notifications_acquire_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  55480. {
  55481. if (pPipelineNotifications == NULL) {
  55482. return;
  55483. }
  55484. if (pPipelineNotifications->init.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->init.pFence); }
  55485. if (pPipelineNotifications->done.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->done.pFence); }
  55486. }
  55487. static void ma_resource_manager_pipeline_notifications_release_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  55488. {
  55489. if (pPipelineNotifications == NULL) {
  55490. return;
  55491. }
  55492. if (pPipelineNotifications->init.pFence != NULL) { ma_fence_release(pPipelineNotifications->init.pFence); }
  55493. if (pPipelineNotifications->done.pFence != NULL) { ma_fence_release(pPipelineNotifications->done.pFence); }
  55494. }
  55495. #ifndef MA_DEFAULT_HASH_SEED
  55496. #define MA_DEFAULT_HASH_SEED 42
  55497. #endif
  55498. /* MurmurHash3. Based on code from https://github.com/PeterScott/murmur3/blob/master/murmur3.c (public domain). */
  55499. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  55500. #pragma GCC diagnostic push
  55501. #if __GNUC__ >= 7
  55502. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  55503. #endif
  55504. #endif
  55505. static MA_INLINE ma_uint32 ma_rotl32(ma_uint32 x, ma_int8 r)
  55506. {
  55507. return (x << r) | (x >> (32 - r));
  55508. }
  55509. static MA_INLINE ma_uint32 ma_hash_getblock(const ma_uint32* blocks, int i)
  55510. {
  55511. ma_uint32 block;
  55512. /* Try silencing a sanitization warning about unaligned access by doing a memcpy() instead of assignment. */
  55513. MA_COPY_MEMORY(&block, ma_offset_ptr(blocks, i * sizeof(block)), sizeof(block));
  55514. if (ma_is_little_endian()) {
  55515. return block;
  55516. } else {
  55517. return ma_swap_endian_uint32(block);
  55518. }
  55519. }
  55520. static MA_INLINE ma_uint32 ma_hash_fmix32(ma_uint32 h)
  55521. {
  55522. h ^= h >> 16;
  55523. h *= 0x85ebca6b;
  55524. h ^= h >> 13;
  55525. h *= 0xc2b2ae35;
  55526. h ^= h >> 16;
  55527. return h;
  55528. }
  55529. static ma_uint32 ma_hash_32(const void* key, int len, ma_uint32 seed)
  55530. {
  55531. const ma_uint8* data = (const ma_uint8*)key;
  55532. const ma_uint32* blocks;
  55533. const ma_uint8* tail;
  55534. const int nblocks = len / 4;
  55535. ma_uint32 h1 = seed;
  55536. ma_uint32 c1 = 0xcc9e2d51;
  55537. ma_uint32 c2 = 0x1b873593;
  55538. ma_uint32 k1;
  55539. int i;
  55540. blocks = (const ma_uint32 *)(data + nblocks*4);
  55541. for(i = -nblocks; i; i++) {
  55542. k1 = ma_hash_getblock(blocks,i);
  55543. k1 *= c1;
  55544. k1 = ma_rotl32(k1, 15);
  55545. k1 *= c2;
  55546. h1 ^= k1;
  55547. h1 = ma_rotl32(h1, 13);
  55548. h1 = h1*5 + 0xe6546b64;
  55549. }
  55550. tail = (const ma_uint8*)(data + nblocks*4);
  55551. k1 = 0;
  55552. switch(len & 3) {
  55553. case 3: k1 ^= tail[2] << 16;
  55554. case 2: k1 ^= tail[1] << 8;
  55555. case 1: k1 ^= tail[0];
  55556. k1 *= c1; k1 = ma_rotl32(k1, 15); k1 *= c2; h1 ^= k1;
  55557. };
  55558. h1 ^= len;
  55559. h1 = ma_hash_fmix32(h1);
  55560. return h1;
  55561. }
  55562. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  55563. #pragma GCC diagnostic push
  55564. #endif
  55565. /* End MurmurHash3 */
  55566. static ma_uint32 ma_hash_string_32(const char* str)
  55567. {
  55568. return ma_hash_32(str, (int)strlen(str), MA_DEFAULT_HASH_SEED);
  55569. }
  55570. static ma_uint32 ma_hash_string_w_32(const wchar_t* str)
  55571. {
  55572. return ma_hash_32(str, (int)wcslen(str) * sizeof(*str), MA_DEFAULT_HASH_SEED);
  55573. }
  55574. /*
  55575. Basic BST Functions
  55576. */
  55577. static ma_result ma_resource_manager_data_buffer_node_search(ma_resource_manager* pResourceManager, ma_uint32 hashedName32, ma_resource_manager_data_buffer_node** ppDataBufferNode)
  55578. {
  55579. ma_resource_manager_data_buffer_node* pCurrentNode;
  55580. MA_ASSERT(pResourceManager != NULL);
  55581. MA_ASSERT(ppDataBufferNode != NULL);
  55582. pCurrentNode = pResourceManager->pRootDataBufferNode;
  55583. while (pCurrentNode != NULL) {
  55584. if (hashedName32 == pCurrentNode->hashedName32) {
  55585. break; /* Found. */
  55586. } else if (hashedName32 < pCurrentNode->hashedName32) {
  55587. pCurrentNode = pCurrentNode->pChildLo;
  55588. } else {
  55589. pCurrentNode = pCurrentNode->pChildHi;
  55590. }
  55591. }
  55592. *ppDataBufferNode = pCurrentNode;
  55593. if (pCurrentNode == NULL) {
  55594. return MA_DOES_NOT_EXIST;
  55595. } else {
  55596. return MA_SUCCESS;
  55597. }
  55598. }
  55599. 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)
  55600. {
  55601. ma_result result = MA_SUCCESS;
  55602. ma_resource_manager_data_buffer_node* pCurrentNode;
  55603. MA_ASSERT(pResourceManager != NULL);
  55604. MA_ASSERT(ppInsertPoint != NULL);
  55605. *ppInsertPoint = NULL;
  55606. if (pResourceManager->pRootDataBufferNode == NULL) {
  55607. return MA_SUCCESS; /* No items. */
  55608. }
  55609. /* 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. */
  55610. pCurrentNode = pResourceManager->pRootDataBufferNode;
  55611. while (pCurrentNode != NULL) {
  55612. if (hashedName32 == pCurrentNode->hashedName32) {
  55613. result = MA_ALREADY_EXISTS;
  55614. break;
  55615. } else {
  55616. if (hashedName32 < pCurrentNode->hashedName32) {
  55617. if (pCurrentNode->pChildLo == NULL) {
  55618. result = MA_SUCCESS;
  55619. break;
  55620. } else {
  55621. pCurrentNode = pCurrentNode->pChildLo;
  55622. }
  55623. } else {
  55624. if (pCurrentNode->pChildHi == NULL) {
  55625. result = MA_SUCCESS;
  55626. break;
  55627. } else {
  55628. pCurrentNode = pCurrentNode->pChildHi;
  55629. }
  55630. }
  55631. }
  55632. }
  55633. *ppInsertPoint = pCurrentNode;
  55634. return result;
  55635. }
  55636. 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)
  55637. {
  55638. MA_ASSERT(pResourceManager != NULL);
  55639. MA_ASSERT(pDataBufferNode != NULL);
  55640. /* The key must have been set before calling this function. */
  55641. MA_ASSERT(pDataBufferNode->hashedName32 != 0);
  55642. if (pInsertPoint == NULL) {
  55643. /* It's the first node. */
  55644. pResourceManager->pRootDataBufferNode = pDataBufferNode;
  55645. } else {
  55646. /* It's not the first node. It needs to be inserted. */
  55647. if (pDataBufferNode->hashedName32 < pInsertPoint->hashedName32) {
  55648. MA_ASSERT(pInsertPoint->pChildLo == NULL);
  55649. pInsertPoint->pChildLo = pDataBufferNode;
  55650. } else {
  55651. MA_ASSERT(pInsertPoint->pChildHi == NULL);
  55652. pInsertPoint->pChildHi = pDataBufferNode;
  55653. }
  55654. }
  55655. pDataBufferNode->pParent = pInsertPoint;
  55656. return MA_SUCCESS;
  55657. }
  55658. #if 0 /* Unused for now. */
  55659. static ma_result ma_resource_manager_data_buffer_node_insert(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  55660. {
  55661. ma_result result;
  55662. ma_resource_manager_data_buffer_node* pInsertPoint;
  55663. MA_ASSERT(pResourceManager != NULL);
  55664. MA_ASSERT(pDataBufferNode != NULL);
  55665. result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, pDataBufferNode->hashedName32, &pInsertPoint);
  55666. if (result != MA_SUCCESS) {
  55667. return MA_INVALID_ARGS;
  55668. }
  55669. return ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint);
  55670. }
  55671. #endif
  55672. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_min(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55673. {
  55674. ma_resource_manager_data_buffer_node* pCurrentNode;
  55675. MA_ASSERT(pDataBufferNode != NULL);
  55676. pCurrentNode = pDataBufferNode;
  55677. while (pCurrentNode->pChildLo != NULL) {
  55678. pCurrentNode = pCurrentNode->pChildLo;
  55679. }
  55680. return pCurrentNode;
  55681. }
  55682. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_max(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55683. {
  55684. ma_resource_manager_data_buffer_node* pCurrentNode;
  55685. MA_ASSERT(pDataBufferNode != NULL);
  55686. pCurrentNode = pDataBufferNode;
  55687. while (pCurrentNode->pChildHi != NULL) {
  55688. pCurrentNode = pCurrentNode->pChildHi;
  55689. }
  55690. return pCurrentNode;
  55691. }
  55692. 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)
  55693. {
  55694. MA_ASSERT(pDataBufferNode != NULL);
  55695. MA_ASSERT(pDataBufferNode->pChildHi != NULL);
  55696. return ma_resource_manager_data_buffer_node_find_min(pDataBufferNode->pChildHi);
  55697. }
  55698. 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)
  55699. {
  55700. MA_ASSERT(pDataBufferNode != NULL);
  55701. MA_ASSERT(pDataBufferNode->pChildLo != NULL);
  55702. return ma_resource_manager_data_buffer_node_find_max(pDataBufferNode->pChildLo);
  55703. }
  55704. static ma_result ma_resource_manager_data_buffer_node_remove(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  55705. {
  55706. MA_ASSERT(pResourceManager != NULL);
  55707. MA_ASSERT(pDataBufferNode != NULL);
  55708. if (pDataBufferNode->pChildLo == NULL) {
  55709. if (pDataBufferNode->pChildHi == NULL) {
  55710. /* Simple case - deleting a buffer with no children. */
  55711. if (pDataBufferNode->pParent == NULL) {
  55712. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode); /* There is only a single buffer in the tree which should be equal to the root node. */
  55713. pResourceManager->pRootDataBufferNode = NULL;
  55714. } else {
  55715. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55716. pDataBufferNode->pParent->pChildLo = NULL;
  55717. } else {
  55718. pDataBufferNode->pParent->pChildHi = NULL;
  55719. }
  55720. }
  55721. } else {
  55722. /* Node has one child - pChildHi != NULL. */
  55723. pDataBufferNode->pChildHi->pParent = pDataBufferNode->pParent;
  55724. if (pDataBufferNode->pParent == NULL) {
  55725. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode);
  55726. pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildHi;
  55727. } else {
  55728. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55729. pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildHi;
  55730. } else {
  55731. pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildHi;
  55732. }
  55733. }
  55734. }
  55735. } else {
  55736. if (pDataBufferNode->pChildHi == NULL) {
  55737. /* Node has one child - pChildLo != NULL. */
  55738. pDataBufferNode->pChildLo->pParent = pDataBufferNode->pParent;
  55739. if (pDataBufferNode->pParent == NULL) {
  55740. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode);
  55741. pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildLo;
  55742. } else {
  55743. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55744. pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildLo;
  55745. } else {
  55746. pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildLo;
  55747. }
  55748. }
  55749. } else {
  55750. /* Complex case - deleting a node with two children. */
  55751. ma_resource_manager_data_buffer_node* pReplacementDataBufferNode;
  55752. /* 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. */
  55753. pReplacementDataBufferNode = ma_resource_manager_data_buffer_node_find_inorder_successor(pDataBufferNode);
  55754. MA_ASSERT(pReplacementDataBufferNode != NULL);
  55755. /*
  55756. 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
  55757. 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
  55758. 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
  55759. replacement node and reinserting it into the same position as the deleted node.
  55760. */
  55761. MA_ASSERT(pReplacementDataBufferNode->pParent != NULL); /* The replacement node should never be the root which means it should always have a parent. */
  55762. MA_ASSERT(pReplacementDataBufferNode->pChildLo == NULL); /* Because we used in-order successor. This would be pChildHi == NULL if we used in-order predecessor. */
  55763. if (pReplacementDataBufferNode->pChildHi == NULL) {
  55764. if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) {
  55765. pReplacementDataBufferNode->pParent->pChildLo = NULL;
  55766. } else {
  55767. pReplacementDataBufferNode->pParent->pChildHi = NULL;
  55768. }
  55769. } else {
  55770. pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode->pParent;
  55771. if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) {
  55772. pReplacementDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode->pChildHi;
  55773. } else {
  55774. pReplacementDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode->pChildHi;
  55775. }
  55776. }
  55777. /* 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 */
  55778. if (pDataBufferNode->pParent != NULL) {
  55779. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  55780. pDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode;
  55781. } else {
  55782. pDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode;
  55783. }
  55784. }
  55785. /* Now need to update the replacement node's pointers. */
  55786. pReplacementDataBufferNode->pParent = pDataBufferNode->pParent;
  55787. pReplacementDataBufferNode->pChildLo = pDataBufferNode->pChildLo;
  55788. pReplacementDataBufferNode->pChildHi = pDataBufferNode->pChildHi;
  55789. /* Now the children of the replacement node need to have their parent pointers updated. */
  55790. if (pReplacementDataBufferNode->pChildLo != NULL) {
  55791. pReplacementDataBufferNode->pChildLo->pParent = pReplacementDataBufferNode;
  55792. }
  55793. if (pReplacementDataBufferNode->pChildHi != NULL) {
  55794. pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode;
  55795. }
  55796. /* Now the root node needs to be updated. */
  55797. if (pResourceManager->pRootDataBufferNode == pDataBufferNode) {
  55798. pResourceManager->pRootDataBufferNode = pReplacementDataBufferNode;
  55799. }
  55800. }
  55801. }
  55802. return MA_SUCCESS;
  55803. }
  55804. #if 0 /* Unused for now. */
  55805. static ma_result ma_resource_manager_data_buffer_node_remove_by_key(ma_resource_manager* pResourceManager, ma_uint32 hashedName32)
  55806. {
  55807. ma_result result;
  55808. ma_resource_manager_data_buffer_node* pDataBufferNode;
  55809. result = ma_resource_manager_data_buffer_search(pResourceManager, hashedName32, &pDataBufferNode);
  55810. if (result != MA_SUCCESS) {
  55811. return result; /* Could not find the data buffer. */
  55812. }
  55813. return ma_resource_manager_data_buffer_remove(pResourceManager, pDataBufferNode);
  55814. }
  55815. #endif
  55816. static ma_resource_manager_data_supply_type ma_resource_manager_data_buffer_node_get_data_supply_type(ma_resource_manager_data_buffer_node* pDataBufferNode)
  55817. {
  55818. return (ma_resource_manager_data_supply_type)ma_atomic_load_i32(&pDataBufferNode->data.type);
  55819. }
  55820. 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)
  55821. {
  55822. ma_atomic_exchange_i32(&pDataBufferNode->data.type, supplyType);
  55823. }
  55824. 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)
  55825. {
  55826. ma_uint32 refCount;
  55827. MA_ASSERT(pResourceManager != NULL);
  55828. MA_ASSERT(pDataBufferNode != NULL);
  55829. (void)pResourceManager;
  55830. refCount = ma_atomic_fetch_add_32(&pDataBufferNode->refCount, 1) + 1;
  55831. if (pNewRefCount != NULL) {
  55832. *pNewRefCount = refCount;
  55833. }
  55834. return MA_SUCCESS;
  55835. }
  55836. 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)
  55837. {
  55838. ma_uint32 refCount;
  55839. MA_ASSERT(pResourceManager != NULL);
  55840. MA_ASSERT(pDataBufferNode != NULL);
  55841. (void)pResourceManager;
  55842. refCount = ma_atomic_fetch_sub_32(&pDataBufferNode->refCount, 1) - 1;
  55843. if (pNewRefCount != NULL) {
  55844. *pNewRefCount = refCount;
  55845. }
  55846. return MA_SUCCESS;
  55847. }
  55848. static void ma_resource_manager_data_buffer_node_free(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  55849. {
  55850. MA_ASSERT(pResourceManager != NULL);
  55851. MA_ASSERT(pDataBufferNode != NULL);
  55852. if (pDataBufferNode->isDataOwnedByResourceManager) {
  55853. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_encoded) {
  55854. ma_free((void*)pDataBufferNode->data.backend.encoded.pData, &pResourceManager->config.allocationCallbacks);
  55855. pDataBufferNode->data.backend.encoded.pData = NULL;
  55856. pDataBufferNode->data.backend.encoded.sizeInBytes = 0;
  55857. } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded) {
  55858. ma_free((void*)pDataBufferNode->data.backend.decoded.pData, &pResourceManager->config.allocationCallbacks);
  55859. pDataBufferNode->data.backend.decoded.pData = NULL;
  55860. pDataBufferNode->data.backend.decoded.totalFrameCount = 0;
  55861. } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded_paged) {
  55862. ma_paged_audio_buffer_data_uninit(&pDataBufferNode->data.backend.decodedPaged.data, &pResourceManager->config.allocationCallbacks);
  55863. } else {
  55864. /* Should never hit this if the node was successfully initialized. */
  55865. MA_ASSERT(pDataBufferNode->result != MA_SUCCESS);
  55866. }
  55867. }
  55868. /* The data buffer itself needs to be freed. */
  55869. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  55870. }
  55871. static ma_result ma_resource_manager_data_buffer_node_result(const ma_resource_manager_data_buffer_node* pDataBufferNode)
  55872. {
  55873. MA_ASSERT(pDataBufferNode != NULL);
  55874. return (ma_result)ma_atomic_load_i32((ma_result*)&pDataBufferNode->result); /* Need a naughty const-cast here. */
  55875. }
  55876. static ma_bool32 ma_resource_manager_is_threading_enabled(const ma_resource_manager* pResourceManager)
  55877. {
  55878. MA_ASSERT(pResourceManager != NULL);
  55879. return (pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) == 0;
  55880. }
  55881. typedef struct
  55882. {
  55883. union
  55884. {
  55885. ma_async_notification_event e;
  55886. ma_async_notification_poll p;
  55887. } backend; /* Must be the first member. */
  55888. ma_resource_manager* pResourceManager;
  55889. } ma_resource_manager_inline_notification;
  55890. static ma_result ma_resource_manager_inline_notification_init(ma_resource_manager* pResourceManager, ma_resource_manager_inline_notification* pNotification)
  55891. {
  55892. MA_ASSERT(pResourceManager != NULL);
  55893. MA_ASSERT(pNotification != NULL);
  55894. pNotification->pResourceManager = pResourceManager;
  55895. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55896. return ma_async_notification_event_init(&pNotification->backend.e);
  55897. } else {
  55898. return ma_async_notification_poll_init(&pNotification->backend.p);
  55899. }
  55900. }
  55901. static void ma_resource_manager_inline_notification_uninit(ma_resource_manager_inline_notification* pNotification)
  55902. {
  55903. MA_ASSERT(pNotification != NULL);
  55904. if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) {
  55905. ma_async_notification_event_uninit(&pNotification->backend.e);
  55906. } else {
  55907. /* No need to uninitialize a polling notification. */
  55908. }
  55909. }
  55910. static void ma_resource_manager_inline_notification_wait(ma_resource_manager_inline_notification* pNotification)
  55911. {
  55912. MA_ASSERT(pNotification != NULL);
  55913. if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) {
  55914. ma_async_notification_event_wait(&pNotification->backend.e);
  55915. } else {
  55916. while (ma_async_notification_poll_is_signalled(&pNotification->backend.p) == MA_FALSE) {
  55917. ma_result result = ma_resource_manager_process_next_job(pNotification->pResourceManager);
  55918. if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) {
  55919. break;
  55920. }
  55921. }
  55922. }
  55923. }
  55924. static void ma_resource_manager_inline_notification_wait_and_uninit(ma_resource_manager_inline_notification* pNotification)
  55925. {
  55926. ma_resource_manager_inline_notification_wait(pNotification);
  55927. ma_resource_manager_inline_notification_uninit(pNotification);
  55928. }
  55929. static void ma_resource_manager_data_buffer_bst_lock(ma_resource_manager* pResourceManager)
  55930. {
  55931. MA_ASSERT(pResourceManager != NULL);
  55932. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55933. #ifndef MA_NO_THREADING
  55934. {
  55935. ma_mutex_lock(&pResourceManager->dataBufferBSTLock);
  55936. }
  55937. #else
  55938. {
  55939. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  55940. }
  55941. #endif
  55942. } else {
  55943. /* Threading not enabled. Do nothing. */
  55944. }
  55945. }
  55946. static void ma_resource_manager_data_buffer_bst_unlock(ma_resource_manager* pResourceManager)
  55947. {
  55948. MA_ASSERT(pResourceManager != NULL);
  55949. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  55950. #ifndef MA_NO_THREADING
  55951. {
  55952. ma_mutex_unlock(&pResourceManager->dataBufferBSTLock);
  55953. }
  55954. #else
  55955. {
  55956. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  55957. }
  55958. #endif
  55959. } else {
  55960. /* Threading not enabled. Do nothing. */
  55961. }
  55962. }
  55963. #ifndef MA_NO_THREADING
  55964. static ma_thread_result MA_THREADCALL ma_resource_manager_job_thread(void* pUserData)
  55965. {
  55966. ma_resource_manager* pResourceManager = (ma_resource_manager*)pUserData;
  55967. MA_ASSERT(pResourceManager != NULL);
  55968. for (;;) {
  55969. ma_result result;
  55970. ma_job job;
  55971. result = ma_resource_manager_next_job(pResourceManager, &job);
  55972. if (result != MA_SUCCESS) {
  55973. break;
  55974. }
  55975. /* Terminate if we got a quit message. */
  55976. if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
  55977. break;
  55978. }
  55979. ma_job_process(&job);
  55980. }
  55981. return (ma_thread_result)0;
  55982. }
  55983. #endif
  55984. MA_API ma_resource_manager_config ma_resource_manager_config_init(void)
  55985. {
  55986. ma_resource_manager_config config;
  55987. MA_ZERO_OBJECT(&config);
  55988. config.decodedFormat = ma_format_unknown;
  55989. config.decodedChannels = 0;
  55990. config.decodedSampleRate = 0;
  55991. config.jobThreadCount = 1; /* A single miniaudio-managed job thread by default. */
  55992. config.jobQueueCapacity = MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY;
  55993. /* Flags. */
  55994. config.flags = 0;
  55995. #ifdef MA_NO_THREADING
  55996. {
  55997. /* Threading is disabled at compile time so disable threading at runtime as well by default. */
  55998. config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  55999. config.jobThreadCount = 0;
  56000. }
  56001. #endif
  56002. return config;
  56003. }
  56004. MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager)
  56005. {
  56006. ma_result result;
  56007. ma_job_queue_config jobQueueConfig;
  56008. if (pResourceManager == NULL) {
  56009. return MA_INVALID_ARGS;
  56010. }
  56011. MA_ZERO_OBJECT(pResourceManager);
  56012. if (pConfig == NULL) {
  56013. return MA_INVALID_ARGS;
  56014. }
  56015. #ifndef MA_NO_THREADING
  56016. {
  56017. if (pConfig->jobThreadCount > ma_countof(pResourceManager->jobThreads)) {
  56018. return MA_INVALID_ARGS; /* Requesting too many job threads. */
  56019. }
  56020. }
  56021. #endif
  56022. pResourceManager->config = *pConfig;
  56023. ma_allocation_callbacks_init_copy(&pResourceManager->config.allocationCallbacks, &pConfig->allocationCallbacks);
  56024. /* Get the log set up early so we can start using it as soon as possible. */
  56025. if (pResourceManager->config.pLog == NULL) {
  56026. result = ma_log_init(&pResourceManager->config.allocationCallbacks, &pResourceManager->log);
  56027. if (result == MA_SUCCESS) {
  56028. pResourceManager->config.pLog = &pResourceManager->log;
  56029. } else {
  56030. pResourceManager->config.pLog = NULL; /* Logging is unavailable. */
  56031. }
  56032. }
  56033. if (pResourceManager->config.pVFS == NULL) {
  56034. result = ma_default_vfs_init(&pResourceManager->defaultVFS, &pResourceManager->config.allocationCallbacks);
  56035. if (result != MA_SUCCESS) {
  56036. return result; /* Failed to initialize the default file system. */
  56037. }
  56038. pResourceManager->config.pVFS = &pResourceManager->defaultVFS;
  56039. }
  56040. /* If threading has been disabled at compile time, enfore it at run time as well. */
  56041. #ifdef MA_NO_THREADING
  56042. {
  56043. pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  56044. }
  56045. #endif
  56046. /* We need to force MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING if MA_RESOURCE_MANAGER_FLAG_NO_THREADING is set. */
  56047. if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) {
  56048. pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING;
  56049. /* We cannot allow job threads when MA_RESOURCE_MANAGER_FLAG_NO_THREADING has been set. This is an invalid use case. */
  56050. if (pResourceManager->config.jobThreadCount > 0) {
  56051. return MA_INVALID_ARGS;
  56052. }
  56053. }
  56054. /* Job queue. */
  56055. jobQueueConfig.capacity = pResourceManager->config.jobQueueCapacity;
  56056. jobQueueConfig.flags = 0;
  56057. if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING) != 0) {
  56058. if (pResourceManager->config.jobThreadCount > 0) {
  56059. return MA_INVALID_ARGS; /* Non-blocking mode is only valid for self-managed job threads. */
  56060. }
  56061. jobQueueConfig.flags |= MA_JOB_QUEUE_FLAG_NON_BLOCKING;
  56062. }
  56063. result = ma_job_queue_init(&jobQueueConfig, &pResourceManager->config.allocationCallbacks, &pResourceManager->jobQueue);
  56064. if (result != MA_SUCCESS) {
  56065. return result;
  56066. }
  56067. /* Custom decoding backends. */
  56068. if (pConfig->ppCustomDecodingBackendVTables != NULL && pConfig->customDecodingBackendCount > 0) {
  56069. size_t sizeInBytes = sizeof(*pResourceManager->config.ppCustomDecodingBackendVTables) * pConfig->customDecodingBackendCount;
  56070. pResourceManager->config.ppCustomDecodingBackendVTables = (ma_decoding_backend_vtable**)ma_malloc(sizeInBytes, &pResourceManager->config.allocationCallbacks);
  56071. if (pResourceManager->config.ppCustomDecodingBackendVTables == NULL) {
  56072. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  56073. return MA_OUT_OF_MEMORY;
  56074. }
  56075. MA_COPY_MEMORY(pResourceManager->config.ppCustomDecodingBackendVTables, pConfig->ppCustomDecodingBackendVTables, sizeInBytes);
  56076. pResourceManager->config.customDecodingBackendCount = pConfig->customDecodingBackendCount;
  56077. pResourceManager->config.pCustomDecodingBackendUserData = pConfig->pCustomDecodingBackendUserData;
  56078. }
  56079. /* Here is where we initialize our threading stuff. We don't do this if we don't support threading. */
  56080. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  56081. #ifndef MA_NO_THREADING
  56082. {
  56083. ma_uint32 iJobThread;
  56084. /* Data buffer lock. */
  56085. result = ma_mutex_init(&pResourceManager->dataBufferBSTLock);
  56086. if (result != MA_SUCCESS) {
  56087. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  56088. return result;
  56089. }
  56090. /* Create the job threads last to ensure the threads has access to valid data. */
  56091. for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) {
  56092. result = ma_thread_create(&pResourceManager->jobThreads[iJobThread], ma_thread_priority_normal, pResourceManager->config.jobThreadStackSize, ma_resource_manager_job_thread, pResourceManager, &pResourceManager->config.allocationCallbacks);
  56093. if (result != MA_SUCCESS) {
  56094. ma_mutex_uninit(&pResourceManager->dataBufferBSTLock);
  56095. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  56096. return result;
  56097. }
  56098. }
  56099. }
  56100. #else
  56101. {
  56102. /* Threading is disabled at compile time. We should never get here because validation checks should have already been performed. */
  56103. MA_ASSERT(MA_FALSE);
  56104. }
  56105. #endif
  56106. }
  56107. return MA_SUCCESS;
  56108. }
  56109. static void ma_resource_manager_delete_all_data_buffer_nodes(ma_resource_manager* pResourceManager)
  56110. {
  56111. MA_ASSERT(pResourceManager);
  56112. /* If everything was done properly, there shouldn't be any active data buffers. */
  56113. while (pResourceManager->pRootDataBufferNode != NULL) {
  56114. ma_resource_manager_data_buffer_node* pDataBufferNode = pResourceManager->pRootDataBufferNode;
  56115. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56116. /* The data buffer has been removed from the BST, so now we need to free it's data. */
  56117. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  56118. }
  56119. }
  56120. MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager)
  56121. {
  56122. if (pResourceManager == NULL) {
  56123. return;
  56124. }
  56125. /*
  56126. 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
  56127. queue which means it will never not be returned after being encounted for the first time which means all threads will eventually receive it.
  56128. */
  56129. ma_resource_manager_post_job_quit(pResourceManager);
  56130. /* Wait for every job to finish before continuing to ensure nothing is sill trying to access any of our objects below. */
  56131. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  56132. #ifndef MA_NO_THREADING
  56133. {
  56134. ma_uint32 iJobThread;
  56135. for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) {
  56136. ma_thread_wait(&pResourceManager->jobThreads[iJobThread]);
  56137. }
  56138. }
  56139. #else
  56140. {
  56141. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  56142. }
  56143. #endif
  56144. }
  56145. /* At this point the thread should have returned and no other thread should be accessing our data. We can now delete all data buffers. */
  56146. ma_resource_manager_delete_all_data_buffer_nodes(pResourceManager);
  56147. /* The job queue is no longer needed. */
  56148. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  56149. /* We're no longer doing anything with data buffers so the lock can now be uninitialized. */
  56150. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  56151. #ifndef MA_NO_THREADING
  56152. {
  56153. ma_mutex_uninit(&pResourceManager->dataBufferBSTLock);
  56154. }
  56155. #else
  56156. {
  56157. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  56158. }
  56159. #endif
  56160. }
  56161. ma_free(pResourceManager->config.ppCustomDecodingBackendVTables, &pResourceManager->config.allocationCallbacks);
  56162. if (pResourceManager->config.pLog == &pResourceManager->log) {
  56163. ma_log_uninit(&pResourceManager->log);
  56164. }
  56165. }
  56166. MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager)
  56167. {
  56168. if (pResourceManager == NULL) {
  56169. return NULL;
  56170. }
  56171. return pResourceManager->config.pLog;
  56172. }
  56173. MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void)
  56174. {
  56175. ma_resource_manager_data_source_config config;
  56176. MA_ZERO_OBJECT(&config);
  56177. config.rangeBegInPCMFrames = MA_DATA_SOURCE_DEFAULT_RANGE_BEG;
  56178. config.rangeEndInPCMFrames = MA_DATA_SOURCE_DEFAULT_RANGE_END;
  56179. config.loopPointBegInPCMFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG;
  56180. config.loopPointEndInPCMFrames = MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END;
  56181. config.isLooping = MA_FALSE;
  56182. return config;
  56183. }
  56184. static ma_decoder_config ma_resource_manager__init_decoder_config(ma_resource_manager* pResourceManager)
  56185. {
  56186. ma_decoder_config config;
  56187. config = ma_decoder_config_init(pResourceManager->config.decodedFormat, pResourceManager->config.decodedChannels, pResourceManager->config.decodedSampleRate);
  56188. config.allocationCallbacks = pResourceManager->config.allocationCallbacks;
  56189. config.ppCustomBackendVTables = pResourceManager->config.ppCustomDecodingBackendVTables;
  56190. config.customBackendCount = pResourceManager->config.customDecodingBackendCount;
  56191. config.pCustomBackendUserData = pResourceManager->config.pCustomDecodingBackendUserData;
  56192. return config;
  56193. }
  56194. static ma_result ma_resource_manager__init_decoder(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_decoder* pDecoder)
  56195. {
  56196. ma_result result;
  56197. ma_decoder_config config;
  56198. MA_ASSERT(pResourceManager != NULL);
  56199. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  56200. MA_ASSERT(pDecoder != NULL);
  56201. config = ma_resource_manager__init_decoder_config(pResourceManager);
  56202. if (pFilePath != NULL) {
  56203. result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pFilePath, &config, pDecoder);
  56204. if (result != MA_SUCCESS) {
  56205. 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));
  56206. return result;
  56207. }
  56208. } else {
  56209. result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pFilePathW, &config, pDecoder);
  56210. if (result != MA_SUCCESS) {
  56211. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  56212. 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));
  56213. #endif
  56214. return result;
  56215. }
  56216. }
  56217. return MA_SUCCESS;
  56218. }
  56219. static ma_bool32 ma_resource_manager_data_buffer_has_connector(ma_resource_manager_data_buffer* pDataBuffer)
  56220. {
  56221. return ma_atomic_bool32_get(&pDataBuffer->isConnectorInitialized);
  56222. }
  56223. static ma_data_source* ma_resource_manager_data_buffer_get_connector(ma_resource_manager_data_buffer* pDataBuffer)
  56224. {
  56225. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) {
  56226. return NULL; /* Connector not yet initialized. */
  56227. }
  56228. switch (pDataBuffer->pNode->data.type)
  56229. {
  56230. case ma_resource_manager_data_supply_type_encoded: return &pDataBuffer->connector.decoder;
  56231. case ma_resource_manager_data_supply_type_decoded: return &pDataBuffer->connector.buffer;
  56232. case ma_resource_manager_data_supply_type_decoded_paged: return &pDataBuffer->connector.pagedBuffer;
  56233. case ma_resource_manager_data_supply_type_unknown:
  56234. default:
  56235. {
  56236. 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");
  56237. return NULL;
  56238. };
  56239. };
  56240. }
  56241. 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)
  56242. {
  56243. ma_result result;
  56244. MA_ASSERT(pDataBuffer != NULL);
  56245. MA_ASSERT(pConfig != NULL);
  56246. MA_ASSERT(ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE);
  56247. /* The underlying data buffer must be initialized before we'll be able to know how to initialize the backend. */
  56248. result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode);
  56249. if (result != MA_SUCCESS && result != MA_BUSY) {
  56250. return result; /* The data buffer is in an erroneous state. */
  56251. }
  56252. /*
  56253. 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
  56254. "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
  56255. an ma_audio_buffer. This enables us to use memory mapping when mixing which saves us a bit of data movement overhead.
  56256. */
  56257. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  56258. {
  56259. case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */
  56260. {
  56261. ma_decoder_config config;
  56262. config = ma_resource_manager__init_decoder_config(pDataBuffer->pResourceManager);
  56263. result = ma_decoder_init_memory(pDataBuffer->pNode->data.backend.encoded.pData, pDataBuffer->pNode->data.backend.encoded.sizeInBytes, &config, &pDataBuffer->connector.decoder);
  56264. } break;
  56265. case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */
  56266. {
  56267. ma_audio_buffer_config config;
  56268. 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);
  56269. result = ma_audio_buffer_init(&config, &pDataBuffer->connector.buffer);
  56270. } break;
  56271. case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */
  56272. {
  56273. ma_paged_audio_buffer_config config;
  56274. config = ma_paged_audio_buffer_config_init(&pDataBuffer->pNode->data.backend.decodedPaged.data);
  56275. result = ma_paged_audio_buffer_init(&config, &pDataBuffer->connector.pagedBuffer);
  56276. } break;
  56277. case ma_resource_manager_data_supply_type_unknown:
  56278. default:
  56279. {
  56280. /* Unknown data supply type. Should never happen. Need to post an error here. */
  56281. return MA_INVALID_ARGS;
  56282. };
  56283. }
  56284. /*
  56285. Initialization of the connector is when we can fire the init notification. This will give the application access to
  56286. the format/channels/rate of the data source.
  56287. */
  56288. if (result == MA_SUCCESS) {
  56289. /*
  56290. The resource manager supports the ability to set the range and loop settings via a config at
  56291. initialization time. This results in an case where the ranges could be set explicitly via
  56292. ma_data_source_set_*() before we get to this point here. If this happens, we'll end up
  56293. hitting a case where we just override those settings which results in what feels like a bug.
  56294. To address this we only change the relevant properties if they're not equal to defaults. If
  56295. they're equal to defaults there's no need to change them anyway. If they're *not* set to the
  56296. default values, we can assume the user has set the range and loop settings via the config. If
  56297. they're doing their own calls to ma_data_source_set_*() in addition to setting them via the
  56298. config, that's entirely on the caller and any synchronization issue becomes their problem.
  56299. */
  56300. if (pConfig->rangeBegInPCMFrames != MA_DATA_SOURCE_DEFAULT_RANGE_BEG || pConfig->rangeEndInPCMFrames != MA_DATA_SOURCE_DEFAULT_RANGE_END) {
  56301. ma_data_source_set_range_in_pcm_frames(pDataBuffer, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  56302. }
  56303. if (pConfig->loopPointBegInPCMFrames != MA_DATA_SOURCE_DEFAULT_LOOP_POINT_BEG || pConfig->loopPointEndInPCMFrames != MA_DATA_SOURCE_DEFAULT_LOOP_POINT_END) {
  56304. ma_data_source_set_loop_point_in_pcm_frames(pDataBuffer, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  56305. }
  56306. if (pConfig->isLooping != MA_FALSE) {
  56307. ma_data_source_set_looping(pDataBuffer, pConfig->isLooping);
  56308. }
  56309. ma_atomic_bool32_set(&pDataBuffer->isConnectorInitialized, MA_TRUE);
  56310. if (pInitNotification != NULL) {
  56311. ma_async_notification_signal(pInitNotification);
  56312. }
  56313. if (pInitFence != NULL) {
  56314. ma_fence_release(pInitFence);
  56315. }
  56316. }
  56317. /* 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. */
  56318. return result;
  56319. }
  56320. static ma_result ma_resource_manager_data_buffer_uninit_connector(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer* pDataBuffer)
  56321. {
  56322. MA_ASSERT(pResourceManager != NULL);
  56323. MA_ASSERT(pDataBuffer != NULL);
  56324. (void)pResourceManager;
  56325. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  56326. {
  56327. case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */
  56328. {
  56329. ma_decoder_uninit(&pDataBuffer->connector.decoder);
  56330. } break;
  56331. case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */
  56332. {
  56333. ma_audio_buffer_uninit(&pDataBuffer->connector.buffer);
  56334. } break;
  56335. case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */
  56336. {
  56337. ma_paged_audio_buffer_uninit(&pDataBuffer->connector.pagedBuffer);
  56338. } break;
  56339. case ma_resource_manager_data_supply_type_unknown:
  56340. default:
  56341. {
  56342. /* Unknown data supply type. Should never happen. Need to post an error here. */
  56343. return MA_INVALID_ARGS;
  56344. };
  56345. }
  56346. return MA_SUCCESS;
  56347. }
  56348. static ma_uint32 ma_resource_manager_data_buffer_node_next_execution_order(ma_resource_manager_data_buffer_node* pDataBufferNode)
  56349. {
  56350. MA_ASSERT(pDataBufferNode != NULL);
  56351. return ma_atomic_fetch_add_32(&pDataBufferNode->executionCounter, 1);
  56352. }
  56353. 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)
  56354. {
  56355. ma_result result;
  56356. size_t dataSizeInBytes;
  56357. void* pData;
  56358. MA_ASSERT(pResourceManager != NULL);
  56359. MA_ASSERT(pDataBufferNode != NULL);
  56360. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  56361. result = ma_vfs_open_and_read_file_ex(pResourceManager->config.pVFS, pFilePath, pFilePathW, &pData, &dataSizeInBytes, &pResourceManager->config.allocationCallbacks);
  56362. if (result != MA_SUCCESS) {
  56363. if (pFilePath != NULL) {
  56364. 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));
  56365. } else {
  56366. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  56367. 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));
  56368. #endif
  56369. }
  56370. return result;
  56371. }
  56372. pDataBufferNode->data.backend.encoded.pData = pData;
  56373. pDataBufferNode->data.backend.encoded.sizeInBytes = dataSizeInBytes;
  56374. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_encoded); /* <-- Must be set last. */
  56375. return MA_SUCCESS;
  56376. }
  56377. 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)
  56378. {
  56379. ma_result result = MA_SUCCESS;
  56380. ma_decoder* pDecoder;
  56381. ma_uint64 totalFrameCount;
  56382. MA_ASSERT(pResourceManager != NULL);
  56383. MA_ASSERT(pDataBufferNode != NULL);
  56384. MA_ASSERT(ppDecoder != NULL);
  56385. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  56386. *ppDecoder = NULL; /* For safety. */
  56387. pDecoder = (ma_decoder*)ma_malloc(sizeof(*pDecoder), &pResourceManager->config.allocationCallbacks);
  56388. if (pDecoder == NULL) {
  56389. return MA_OUT_OF_MEMORY;
  56390. }
  56391. result = ma_resource_manager__init_decoder(pResourceManager, pFilePath, pFilePathW, pDecoder);
  56392. if (result != MA_SUCCESS) {
  56393. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56394. return result;
  56395. }
  56396. /*
  56397. At this point we have the decoder and we now need to initialize the data supply. This will
  56398. be either a decoded buffer, or a decoded paged buffer. A regular buffer is just one big heap
  56399. allocated buffer, whereas a paged buffer is a linked list of paged-sized buffers. The latter
  56400. is used when the length of a sound is unknown until a full decode has been performed.
  56401. */
  56402. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) {
  56403. result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount);
  56404. if (result != MA_SUCCESS) {
  56405. return result;
  56406. }
  56407. } else {
  56408. totalFrameCount = 0;
  56409. }
  56410. if (totalFrameCount > 0) {
  56411. /* It's a known length. The data supply is a regular decoded buffer. */
  56412. ma_uint64 dataSizeInBytes;
  56413. void* pData;
  56414. dataSizeInBytes = totalFrameCount * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
  56415. if (dataSizeInBytes > MA_SIZE_MAX) {
  56416. ma_decoder_uninit(pDecoder);
  56417. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56418. return MA_TOO_BIG;
  56419. }
  56420. pData = ma_malloc((size_t)dataSizeInBytes, &pResourceManager->config.allocationCallbacks);
  56421. if (pData == NULL) {
  56422. ma_decoder_uninit(pDecoder);
  56423. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56424. return MA_OUT_OF_MEMORY;
  56425. }
  56426. /* The buffer needs to be initialized to silence in case the caller reads from it. */
  56427. ma_silence_pcm_frames(pData, totalFrameCount, pDecoder->outputFormat, pDecoder->outputChannels);
  56428. /* Data has been allocated and the data supply can now be initialized. */
  56429. pDataBufferNode->data.backend.decoded.pData = pData;
  56430. pDataBufferNode->data.backend.decoded.totalFrameCount = totalFrameCount;
  56431. pDataBufferNode->data.backend.decoded.format = pDecoder->outputFormat;
  56432. pDataBufferNode->data.backend.decoded.channels = pDecoder->outputChannels;
  56433. pDataBufferNode->data.backend.decoded.sampleRate = pDecoder->outputSampleRate;
  56434. pDataBufferNode->data.backend.decoded.decodedFrameCount = 0;
  56435. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded); /* <-- Must be set last. */
  56436. } else {
  56437. /*
  56438. It's an unknown length. The data supply is a paged decoded buffer. Setting this up is
  56439. actually easier than the non-paged decoded buffer because we just need to initialize
  56440. a ma_paged_audio_buffer object.
  56441. */
  56442. result = ma_paged_audio_buffer_data_init(pDecoder->outputFormat, pDecoder->outputChannels, &pDataBufferNode->data.backend.decodedPaged.data);
  56443. if (result != MA_SUCCESS) {
  56444. ma_decoder_uninit(pDecoder);
  56445. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56446. return result;
  56447. }
  56448. pDataBufferNode->data.backend.decodedPaged.sampleRate = pDecoder->outputSampleRate;
  56449. pDataBufferNode->data.backend.decodedPaged.decodedFrameCount = 0;
  56450. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded_paged); /* <-- Must be set last. */
  56451. }
  56452. *ppDecoder = pDecoder;
  56453. return MA_SUCCESS;
  56454. }
  56455. 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)
  56456. {
  56457. ma_result result = MA_SUCCESS;
  56458. ma_uint64 pageSizeInFrames;
  56459. ma_uint64 framesToTryReading;
  56460. ma_uint64 framesRead;
  56461. MA_ASSERT(pResourceManager != NULL);
  56462. MA_ASSERT(pDataBufferNode != NULL);
  56463. MA_ASSERT(pDecoder != NULL);
  56464. /* We need to know the size of a page in frames to know how many frames to decode. */
  56465. pageSizeInFrames = MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDecoder->outputSampleRate/1000);
  56466. framesToTryReading = pageSizeInFrames;
  56467. /*
  56468. Here is where we do the decoding of the next page. We'll run a slightly different path depending
  56469. on whether or not we're using a flat or paged buffer because the allocation of the page differs
  56470. between the two. For a flat buffer it's an offset to an already-allocated buffer. For a paged
  56471. buffer, we need to allocate a new page and attach it to the linked list.
  56472. */
  56473. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode))
  56474. {
  56475. case ma_resource_manager_data_supply_type_decoded:
  56476. {
  56477. /* The destination buffer is an offset to the existing buffer. Don't read more than we originally retrieved when we first initialized the decoder. */
  56478. void* pDst;
  56479. ma_uint64 framesRemaining = pDataBufferNode->data.backend.decoded.totalFrameCount - pDataBufferNode->data.backend.decoded.decodedFrameCount;
  56480. if (framesToTryReading > framesRemaining) {
  56481. framesToTryReading = framesRemaining;
  56482. }
  56483. if (framesToTryReading > 0) {
  56484. pDst = ma_offset_ptr(
  56485. pDataBufferNode->data.backend.decoded.pData,
  56486. pDataBufferNode->data.backend.decoded.decodedFrameCount * ma_get_bytes_per_frame(pDataBufferNode->data.backend.decoded.format, pDataBufferNode->data.backend.decoded.channels)
  56487. );
  56488. MA_ASSERT(pDst != NULL);
  56489. result = ma_decoder_read_pcm_frames(pDecoder, pDst, framesToTryReading, &framesRead);
  56490. if (framesRead > 0) {
  56491. pDataBufferNode->data.backend.decoded.decodedFrameCount += framesRead;
  56492. }
  56493. } else {
  56494. framesRead = 0;
  56495. }
  56496. } break;
  56497. case ma_resource_manager_data_supply_type_decoded_paged:
  56498. {
  56499. /* The destination buffer is a freshly allocated page. */
  56500. ma_paged_audio_buffer_page* pPage;
  56501. result = ma_paged_audio_buffer_data_allocate_page(&pDataBufferNode->data.backend.decodedPaged.data, framesToTryReading, NULL, &pResourceManager->config.allocationCallbacks, &pPage);
  56502. if (result != MA_SUCCESS) {
  56503. return result;
  56504. }
  56505. result = ma_decoder_read_pcm_frames(pDecoder, pPage->pAudioData, framesToTryReading, &framesRead);
  56506. if (framesRead > 0) {
  56507. pPage->sizeInFrames = framesRead;
  56508. result = ma_paged_audio_buffer_data_append_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage);
  56509. if (result == MA_SUCCESS) {
  56510. pDataBufferNode->data.backend.decodedPaged.decodedFrameCount += framesRead;
  56511. } else {
  56512. /* Failed to append the page. Just abort and set the status to MA_AT_END. */
  56513. ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks);
  56514. result = MA_AT_END;
  56515. }
  56516. } else {
  56517. /* No frames were read. Free the page and just set the status to MA_AT_END. */
  56518. ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks);
  56519. result = MA_AT_END;
  56520. }
  56521. } break;
  56522. case ma_resource_manager_data_supply_type_encoded:
  56523. case ma_resource_manager_data_supply_type_unknown:
  56524. default:
  56525. {
  56526. /* Unexpected data supply type. */
  56527. 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));
  56528. return MA_ERROR;
  56529. };
  56530. }
  56531. if (result == MA_SUCCESS && framesRead == 0) {
  56532. result = MA_AT_END;
  56533. }
  56534. return result;
  56535. }
  56536. 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)
  56537. {
  56538. ma_result result = MA_SUCCESS;
  56539. ma_resource_manager_data_buffer_node* pDataBufferNode = NULL;
  56540. ma_resource_manager_data_buffer_node* pInsertPoint;
  56541. if (ppDataBufferNode != NULL) {
  56542. *ppDataBufferNode = NULL;
  56543. }
  56544. result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, hashedName32, &pInsertPoint);
  56545. if (result == MA_ALREADY_EXISTS) {
  56546. /* The node already exists. We just need to increment the reference count. */
  56547. pDataBufferNode = pInsertPoint;
  56548. result = ma_resource_manager_data_buffer_node_increment_ref(pResourceManager, pDataBufferNode, NULL);
  56549. if (result != MA_SUCCESS) {
  56550. return result; /* Should never happen. Failed to increment the reference count. */
  56551. }
  56552. result = MA_ALREADY_EXISTS;
  56553. goto done;
  56554. } else {
  56555. /*
  56556. The node does not already exist. We need to post a LOAD_DATA_BUFFER_NODE job here. This
  56557. needs to be done inside the critical section to ensure an uninitialization of the node
  56558. does not occur before initialization on another thread.
  56559. */
  56560. pDataBufferNode = (ma_resource_manager_data_buffer_node*)ma_malloc(sizeof(*pDataBufferNode), &pResourceManager->config.allocationCallbacks);
  56561. if (pDataBufferNode == NULL) {
  56562. return MA_OUT_OF_MEMORY;
  56563. }
  56564. MA_ZERO_OBJECT(pDataBufferNode);
  56565. pDataBufferNode->hashedName32 = hashedName32;
  56566. pDataBufferNode->refCount = 1; /* Always set to 1 by default (this is our first reference). */
  56567. if (pExistingData == NULL) {
  56568. pDataBufferNode->data.type = ma_resource_manager_data_supply_type_unknown; /* <-- We won't know this until we start decoding. */
  56569. pDataBufferNode->result = MA_BUSY; /* Must be set to MA_BUSY before we leave the critical section, so might as well do it now. */
  56570. pDataBufferNode->isDataOwnedByResourceManager = MA_TRUE;
  56571. } else {
  56572. pDataBufferNode->data = *pExistingData;
  56573. pDataBufferNode->result = MA_SUCCESS; /* Not loading asynchronously, so just set the status */
  56574. pDataBufferNode->isDataOwnedByResourceManager = MA_FALSE;
  56575. }
  56576. result = ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint);
  56577. if (result != MA_SUCCESS) {
  56578. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56579. return result; /* Should never happen. Failed to insert the data buffer into the BST. */
  56580. }
  56581. /*
  56582. Here is where we'll post the job, but only if we're loading asynchronously. If we're
  56583. loading synchronously we'll defer loading to a later stage, outside of the critical
  56584. section.
  56585. */
  56586. if (pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) {
  56587. /* Loading asynchronously. Post the job. */
  56588. ma_job job;
  56589. char* pFilePathCopy = NULL;
  56590. wchar_t* pFilePathWCopy = NULL;
  56591. /* 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. */
  56592. if (pFilePath != NULL) {
  56593. pFilePathCopy = ma_copy_string(pFilePath, &pResourceManager->config.allocationCallbacks);
  56594. } else {
  56595. pFilePathWCopy = ma_copy_string_w(pFilePathW, &pResourceManager->config.allocationCallbacks);
  56596. }
  56597. if (pFilePathCopy == NULL && pFilePathWCopy == NULL) {
  56598. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56599. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56600. return MA_OUT_OF_MEMORY;
  56601. }
  56602. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56603. ma_resource_manager_inline_notification_init(pResourceManager, pInitNotification);
  56604. }
  56605. /* Acquire init and done fences before posting the job. These will be unacquired by the job thread. */
  56606. if (pInitFence != NULL) { ma_fence_acquire(pInitFence); }
  56607. if (pDoneFence != NULL) { ma_fence_acquire(pDoneFence); }
  56608. /* We now have everything we need to post the job to the job thread. */
  56609. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE);
  56610. job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  56611. job.data.resourceManager.loadDataBufferNode.pResourceManager = pResourceManager;
  56612. job.data.resourceManager.loadDataBufferNode.pDataBufferNode = pDataBufferNode;
  56613. job.data.resourceManager.loadDataBufferNode.pFilePath = pFilePathCopy;
  56614. job.data.resourceManager.loadDataBufferNode.pFilePathW = pFilePathWCopy;
  56615. job.data.resourceManager.loadDataBufferNode.flags = flags;
  56616. job.data.resourceManager.loadDataBufferNode.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? pInitNotification : NULL;
  56617. job.data.resourceManager.loadDataBufferNode.pDoneNotification = NULL;
  56618. job.data.resourceManager.loadDataBufferNode.pInitFence = pInitFence;
  56619. job.data.resourceManager.loadDataBufferNode.pDoneFence = pDoneFence;
  56620. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56621. result = ma_job_process(&job);
  56622. } else {
  56623. result = ma_resource_manager_post_job(pResourceManager, &job);
  56624. }
  56625. if (result != MA_SUCCESS) {
  56626. /* Failed to post job. Probably ran out of memory. */
  56627. 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));
  56628. /*
  56629. Fences were acquired before posting the job, but since the job was not able to
  56630. be posted, we need to make sure we release them so nothing gets stuck waiting.
  56631. */
  56632. if (pInitFence != NULL) { ma_fence_release(pInitFence); }
  56633. if (pDoneFence != NULL) { ma_fence_release(pDoneFence); }
  56634. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56635. ma_resource_manager_inline_notification_uninit(pInitNotification);
  56636. } else {
  56637. /* These will have been freed by the job thread, but with WAIT_INIT they will already have happend sinced the job has already been handled. */
  56638. ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks);
  56639. ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks);
  56640. }
  56641. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56642. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56643. return result;
  56644. }
  56645. }
  56646. }
  56647. done:
  56648. if (ppDataBufferNode != NULL) {
  56649. *ppDataBufferNode = pDataBufferNode;
  56650. }
  56651. return result;
  56652. }
  56653. 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)
  56654. {
  56655. ma_result result = MA_SUCCESS;
  56656. ma_bool32 nodeAlreadyExists = MA_FALSE;
  56657. ma_resource_manager_data_buffer_node* pDataBufferNode = NULL;
  56658. ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */
  56659. if (ppDataBufferNode != NULL) {
  56660. *ppDataBufferNode = NULL; /* Safety. */
  56661. }
  56662. if (pResourceManager == NULL || (pFilePath == NULL && pFilePathW == NULL && hashedName32 == 0)) {
  56663. return MA_INVALID_ARGS;
  56664. }
  56665. /* If we're specifying existing data, it must be valid. */
  56666. if (pExistingData != NULL && pExistingData->type == ma_resource_manager_data_supply_type_unknown) {
  56667. return MA_INVALID_ARGS;
  56668. }
  56669. /* If we don't support threading, remove the ASYNC flag to make the rest of this a bit simpler. */
  56670. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  56671. flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC;
  56672. }
  56673. if (hashedName32 == 0) {
  56674. if (pFilePath != NULL) {
  56675. hashedName32 = ma_hash_string_32(pFilePath);
  56676. } else {
  56677. hashedName32 = ma_hash_string_w_32(pFilePathW);
  56678. }
  56679. }
  56680. /*
  56681. Here is where we either increment the node's reference count or allocate a new one and add it
  56682. to the BST. When allocating a new node, we need to make sure the LOAD_DATA_BUFFER_NODE job is
  56683. posted inside the critical section just in case the caller immediately uninitializes the node
  56684. as this will ensure the FREE_DATA_BUFFER_NODE job is given an execution order such that the
  56685. node is not uninitialized before initialization.
  56686. */
  56687. ma_resource_manager_data_buffer_bst_lock(pResourceManager);
  56688. {
  56689. result = ma_resource_manager_data_buffer_node_acquire_critical_section(pResourceManager, pFilePath, pFilePathW, hashedName32, flags, pExistingData, pInitFence, pDoneFence, &initNotification, &pDataBufferNode);
  56690. }
  56691. ma_resource_manager_data_buffer_bst_unlock(pResourceManager);
  56692. if (result == MA_ALREADY_EXISTS) {
  56693. nodeAlreadyExists = MA_TRUE;
  56694. result = MA_SUCCESS;
  56695. } else {
  56696. if (result != MA_SUCCESS) {
  56697. return result;
  56698. }
  56699. }
  56700. /*
  56701. If we're loading synchronously, we'll need to load everything now. When loading asynchronously,
  56702. a job will have been posted inside the BST critical section so that an uninitialization can be
  56703. allocated an appropriate execution order thereby preventing it from being uninitialized before
  56704. the node is initialized by the decoding thread(s).
  56705. */
  56706. if (nodeAlreadyExists == MA_FALSE) { /* Don't need to try loading anything if the node already exists. */
  56707. if (pFilePath == NULL && pFilePathW == NULL) {
  56708. /*
  56709. If this path is hit, it means a buffer is being copied (i.e. initialized from only the
  56710. hashed name), but that node has been freed in the meantime, probably from some other
  56711. thread. This is an invalid operation.
  56712. */
  56713. 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");
  56714. result = MA_INVALID_OPERATION;
  56715. goto done;
  56716. }
  56717. if (pDataBufferNode->isDataOwnedByResourceManager) {
  56718. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0) {
  56719. /* Loading synchronously. Load the sound in it's entirety here. */
  56720. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) == 0) {
  56721. /* No decoding. This is the simple case - just store the file contents in memory. */
  56722. result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW);
  56723. if (result != MA_SUCCESS) {
  56724. goto done;
  56725. }
  56726. } else {
  56727. /* Decoding. We do this the same way as we do when loading asynchronously. */
  56728. ma_decoder* pDecoder;
  56729. result = ma_resource_manager_data_buffer_node_init_supply_decoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW, flags, &pDecoder);
  56730. if (result != MA_SUCCESS) {
  56731. goto done;
  56732. }
  56733. /* We have the decoder, now decode page by page just like we do when loading asynchronously. */
  56734. for (;;) {
  56735. /* Decode next page. */
  56736. result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, pDecoder);
  56737. if (result != MA_SUCCESS) {
  56738. break; /* Will return MA_AT_END when the last page has been decoded. */
  56739. }
  56740. }
  56741. /* Reaching the end needs to be considered successful. */
  56742. if (result == MA_AT_END) {
  56743. result = MA_SUCCESS;
  56744. }
  56745. /*
  56746. At this point the data buffer is either fully decoded or some error occurred. Either
  56747. way, the decoder is no longer necessary.
  56748. */
  56749. ma_decoder_uninit(pDecoder);
  56750. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56751. }
  56752. /* Getting here means we were successful. Make sure the status of the node is updated accordingly. */
  56753. ma_atomic_exchange_i32(&pDataBufferNode->result, result);
  56754. } else {
  56755. /* Loading asynchronously. We may need to wait for initialization. */
  56756. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56757. ma_resource_manager_inline_notification_wait(&initNotification);
  56758. }
  56759. }
  56760. } else {
  56761. /* The data is not managed by the resource manager so there's nothing else to do. */
  56762. MA_ASSERT(pExistingData != NULL);
  56763. }
  56764. }
  56765. done:
  56766. /* If we failed to initialize the data buffer we need to free it. */
  56767. if (result != MA_SUCCESS) {
  56768. if (nodeAlreadyExists == MA_FALSE) {
  56769. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56770. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  56771. }
  56772. }
  56773. /*
  56774. The init notification needs to be uninitialized. This will be used if the node does not already
  56775. exist, and we've specified ASYNC | WAIT_INIT.
  56776. */
  56777. if (nodeAlreadyExists == MA_FALSE && pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) {
  56778. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56779. ma_resource_manager_inline_notification_uninit(&initNotification);
  56780. }
  56781. }
  56782. if (ppDataBufferNode != NULL) {
  56783. *ppDataBufferNode = pDataBufferNode;
  56784. }
  56785. return result;
  56786. }
  56787. 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)
  56788. {
  56789. ma_result result = MA_SUCCESS;
  56790. 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. */
  56791. ma_uint32 hashedName32 = 0;
  56792. if (pResourceManager == NULL) {
  56793. return MA_INVALID_ARGS;
  56794. }
  56795. if (pDataBufferNode == NULL) {
  56796. if (pName == NULL && pNameW == NULL) {
  56797. return MA_INVALID_ARGS;
  56798. }
  56799. if (pName != NULL) {
  56800. hashedName32 = ma_hash_string_32(pName);
  56801. } else {
  56802. hashedName32 = ma_hash_string_w_32(pNameW);
  56803. }
  56804. }
  56805. /*
  56806. The first thing to do is decrement the reference counter of the node. Then, if the reference
  56807. count is zero, we need to free the node. If the node is still in the process of loading, we'll
  56808. need to post a job to the job queue to free the node. Otherwise we'll just do it here.
  56809. */
  56810. ma_resource_manager_data_buffer_bst_lock(pResourceManager);
  56811. {
  56812. /* Might need to find the node. Must be done inside the critical section. */
  56813. if (pDataBufferNode == NULL) {
  56814. result = ma_resource_manager_data_buffer_node_search(pResourceManager, hashedName32, &pDataBufferNode);
  56815. if (result != MA_SUCCESS) {
  56816. goto stage2; /* Couldn't find the node. */
  56817. }
  56818. }
  56819. result = ma_resource_manager_data_buffer_node_decrement_ref(pResourceManager, pDataBufferNode, &refCount);
  56820. if (result != MA_SUCCESS) {
  56821. goto stage2; /* Should never happen. */
  56822. }
  56823. if (refCount == 0) {
  56824. result = ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  56825. if (result != MA_SUCCESS) {
  56826. goto stage2; /* An error occurred when trying to remove the data buffer. This should never happen. */
  56827. }
  56828. }
  56829. }
  56830. ma_resource_manager_data_buffer_bst_unlock(pResourceManager);
  56831. stage2:
  56832. if (result != MA_SUCCESS) {
  56833. return result;
  56834. }
  56835. /*
  56836. Here is where we need to free the node. We don't want to do this inside the critical section
  56837. above because we want to keep that as small as possible for multi-threaded efficiency.
  56838. */
  56839. if (refCount == 0) {
  56840. if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) {
  56841. /* The sound is still loading. We need to delay the freeing of the node to a safe time. */
  56842. ma_job job;
  56843. /* We need to mark the node as unavailable for the sake of the resource manager worker threads. */
  56844. ma_atomic_exchange_i32(&pDataBufferNode->result, MA_UNAVAILABLE);
  56845. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE);
  56846. job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  56847. job.data.resourceManager.freeDataBufferNode.pResourceManager = pResourceManager;
  56848. job.data.resourceManager.freeDataBufferNode.pDataBufferNode = pDataBufferNode;
  56849. result = ma_resource_manager_post_job(pResourceManager, &job);
  56850. if (result != MA_SUCCESS) {
  56851. 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));
  56852. return result;
  56853. }
  56854. /* If we don't support threading, process the job queue here. */
  56855. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  56856. while (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) {
  56857. result = ma_resource_manager_process_next_job(pResourceManager);
  56858. if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) {
  56859. result = MA_SUCCESS;
  56860. break;
  56861. }
  56862. }
  56863. } else {
  56864. /* Threading is enabled. The job queue will deal with the rest of the cleanup from here. */
  56865. }
  56866. } else {
  56867. /* The sound isn't loading so we can just free the node here. */
  56868. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  56869. }
  56870. }
  56871. return result;
  56872. }
  56873. static ma_uint32 ma_resource_manager_data_buffer_next_execution_order(ma_resource_manager_data_buffer* pDataBuffer)
  56874. {
  56875. MA_ASSERT(pDataBuffer != NULL);
  56876. return ma_atomic_fetch_add_32(&pDataBuffer->executionCounter, 1);
  56877. }
  56878. static ma_result ma_resource_manager_data_buffer_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  56879. {
  56880. return ma_resource_manager_data_buffer_read_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead);
  56881. }
  56882. static ma_result ma_resource_manager_data_buffer_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  56883. {
  56884. return ma_resource_manager_data_buffer_seek_to_pcm_frame((ma_resource_manager_data_buffer*)pDataSource, frameIndex);
  56885. }
  56886. 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)
  56887. {
  56888. return ma_resource_manager_data_buffer_get_data_format((ma_resource_manager_data_buffer*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  56889. }
  56890. static ma_result ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  56891. {
  56892. return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pCursor);
  56893. }
  56894. static ma_result ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  56895. {
  56896. return ma_resource_manager_data_buffer_get_length_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pLength);
  56897. }
  56898. static ma_result ma_resource_manager_data_buffer_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  56899. {
  56900. ma_resource_manager_data_buffer* pDataBuffer = (ma_resource_manager_data_buffer*)pDataSource;
  56901. MA_ASSERT(pDataBuffer != NULL);
  56902. ma_atomic_exchange_32(&pDataBuffer->isLooping, isLooping);
  56903. /* The looping state needs to be set on the connector as well or else looping won't work when we read audio data. */
  56904. ma_data_source_set_looping(ma_resource_manager_data_buffer_get_connector(pDataBuffer), isLooping);
  56905. return MA_SUCCESS;
  56906. }
  56907. static ma_data_source_vtable g_ma_resource_manager_data_buffer_vtable =
  56908. {
  56909. ma_resource_manager_data_buffer_cb__read_pcm_frames,
  56910. ma_resource_manager_data_buffer_cb__seek_to_pcm_frame,
  56911. ma_resource_manager_data_buffer_cb__get_data_format,
  56912. ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames,
  56913. ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames,
  56914. ma_resource_manager_data_buffer_cb__set_looping,
  56915. 0
  56916. };
  56917. 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)
  56918. {
  56919. ma_result result = MA_SUCCESS;
  56920. ma_resource_manager_data_buffer_node* pDataBufferNode;
  56921. ma_data_source_config dataSourceConfig;
  56922. ma_bool32 async;
  56923. ma_uint32 flags;
  56924. ma_resource_manager_pipeline_notifications notifications;
  56925. if (pDataBuffer == NULL) {
  56926. if (pConfig != NULL && pConfig->pNotifications != NULL) {
  56927. ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications);
  56928. }
  56929. return MA_INVALID_ARGS;
  56930. }
  56931. MA_ZERO_OBJECT(pDataBuffer);
  56932. if (pConfig == NULL) {
  56933. return MA_INVALID_ARGS;
  56934. }
  56935. if (pConfig->pNotifications != NULL) {
  56936. 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. */
  56937. } else {
  56938. MA_ZERO_OBJECT(&notifications);
  56939. }
  56940. /* For safety, always remove the ASYNC flag if threading is disabled on the resource manager. */
  56941. flags = pConfig->flags;
  56942. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  56943. flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC;
  56944. }
  56945. async = (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0;
  56946. /*
  56947. Fences need to be acquired before doing anything. These must be acquired and released outside of
  56948. the node to ensure there's no holes where ma_fence_wait() could prematurely return before the
  56949. data buffer has completed initialization.
  56950. When loading asynchronously, the node acquisition routine below will acquire the fences on this
  56951. thread and then release them on the async thread when the operation is complete.
  56952. These fences are always released at the "done" tag at the end of this function. They'll be
  56953. acquired a second if loading asynchronously. This double acquisition system is just done to
  56954. simplify code maintanence.
  56955. */
  56956. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  56957. {
  56958. /* We first need to acquire a node. If ASYNC is not set, this will not return until the entire sound has been loaded. */
  56959. result = ma_resource_manager_data_buffer_node_acquire(pResourceManager, pConfig->pFilePath, pConfig->pFilePathW, hashedName32, flags, NULL, notifications.init.pFence, notifications.done.pFence, &pDataBufferNode);
  56960. if (result != MA_SUCCESS) {
  56961. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  56962. goto done;
  56963. }
  56964. dataSourceConfig = ma_data_source_config_init();
  56965. dataSourceConfig.vtable = &g_ma_resource_manager_data_buffer_vtable;
  56966. result = ma_data_source_init(&dataSourceConfig, &pDataBuffer->ds);
  56967. if (result != MA_SUCCESS) {
  56968. ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL);
  56969. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  56970. goto done;
  56971. }
  56972. pDataBuffer->pResourceManager = pResourceManager;
  56973. pDataBuffer->pNode = pDataBufferNode;
  56974. pDataBuffer->flags = flags;
  56975. pDataBuffer->result = MA_BUSY; /* Always default to MA_BUSY for safety. It'll be overwritten when loading completes or an error occurs. */
  56976. /* If we're loading asynchronously we need to post a job to the job queue to initialize the connector. */
  56977. if (async == MA_FALSE || ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_SUCCESS) {
  56978. /* Loading synchronously or the data has already been fully loaded. We can just initialize the connector from here without a job. */
  56979. result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, pConfig, NULL, NULL);
  56980. ma_atomic_exchange_i32(&pDataBuffer->result, result);
  56981. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  56982. goto done;
  56983. } else {
  56984. /* 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. */
  56985. ma_job job;
  56986. ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */
  56987. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  56988. ma_resource_manager_inline_notification_init(pResourceManager, &initNotification);
  56989. }
  56990. /*
  56991. The status of the data buffer needs to be set to MA_BUSY before posting the job so that the
  56992. worker thread is aware of it's busy state. If the LOAD_DATA_BUFFER job sees a status other
  56993. than MA_BUSY, it'll assume an error and fall through to an early exit.
  56994. */
  56995. ma_atomic_exchange_i32(&pDataBuffer->result, MA_BUSY);
  56996. /* Acquire fences a second time. These will be released by the async thread. */
  56997. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  56998. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER);
  56999. job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer);
  57000. job.data.resourceManager.loadDataBuffer.pDataBuffer = pDataBuffer;
  57001. job.data.resourceManager.loadDataBuffer.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? &initNotification : notifications.init.pNotification;
  57002. job.data.resourceManager.loadDataBuffer.pDoneNotification = notifications.done.pNotification;
  57003. job.data.resourceManager.loadDataBuffer.pInitFence = notifications.init.pFence;
  57004. job.data.resourceManager.loadDataBuffer.pDoneFence = notifications.done.pFence;
  57005. job.data.resourceManager.loadDataBuffer.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames;
  57006. job.data.resourceManager.loadDataBuffer.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames;
  57007. job.data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames;
  57008. job.data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames;
  57009. job.data.resourceManager.loadDataBuffer.isLooping = pConfig->isLooping;
  57010. /* If we need to wait for initialization to complete we can just process the job in place. */
  57011. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  57012. result = ma_job_process(&job);
  57013. } else {
  57014. result = ma_resource_manager_post_job(pResourceManager, &job);
  57015. }
  57016. if (result != MA_SUCCESS) {
  57017. /* We failed to post the job. Most likely there isn't enough room in the queue's buffer. */
  57018. 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));
  57019. ma_atomic_exchange_i32(&pDataBuffer->result, result);
  57020. /* Release the fences after the result has been set on the data buffer. */
  57021. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  57022. } else {
  57023. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  57024. ma_resource_manager_inline_notification_wait(&initNotification);
  57025. if (notifications.init.pNotification != NULL) {
  57026. ma_async_notification_signal(notifications.init.pNotification);
  57027. }
  57028. /* NOTE: Do not release the init fence here. It will have been done by the job. */
  57029. /* Make sure we return an error if initialization failed on the async thread. */
  57030. result = ma_resource_manager_data_buffer_result(pDataBuffer);
  57031. if (result == MA_BUSY) {
  57032. result = MA_SUCCESS;
  57033. }
  57034. }
  57035. }
  57036. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  57037. ma_resource_manager_inline_notification_uninit(&initNotification);
  57038. }
  57039. }
  57040. if (result != MA_SUCCESS) {
  57041. ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL);
  57042. goto done;
  57043. }
  57044. }
  57045. done:
  57046. if (result == MA_SUCCESS) {
  57047. if (pConfig->initialSeekPointInPCMFrames > 0) {
  57048. ma_resource_manager_data_buffer_seek_to_pcm_frame(pDataBuffer, pConfig->initialSeekPointInPCMFrames);
  57049. }
  57050. }
  57051. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  57052. return result;
  57053. }
  57054. 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)
  57055. {
  57056. return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, pConfig, 0, pDataBuffer);
  57057. }
  57058. 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)
  57059. {
  57060. ma_resource_manager_data_source_config config;
  57061. config = ma_resource_manager_data_source_config_init();
  57062. config.pFilePath = pFilePath;
  57063. config.flags = flags;
  57064. config.pNotifications = pNotifications;
  57065. return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer);
  57066. }
  57067. 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)
  57068. {
  57069. ma_resource_manager_data_source_config config;
  57070. config = ma_resource_manager_data_source_config_init();
  57071. config.pFilePathW = pFilePath;
  57072. config.flags = flags;
  57073. config.pNotifications = pNotifications;
  57074. return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer);
  57075. }
  57076. 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)
  57077. {
  57078. ma_resource_manager_data_source_config config;
  57079. if (pExistingDataBuffer == NULL) {
  57080. return MA_INVALID_ARGS;
  57081. }
  57082. MA_ASSERT(pExistingDataBuffer->pNode != NULL); /* <-- If you've triggered this, you've passed in an invalid existing data buffer. */
  57083. config = ma_resource_manager_data_source_config_init();
  57084. config.flags = pExistingDataBuffer->flags;
  57085. return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, &config, pExistingDataBuffer->pNode->hashedName32, pDataBuffer);
  57086. }
  57087. static ma_result ma_resource_manager_data_buffer_uninit_internal(ma_resource_manager_data_buffer* pDataBuffer)
  57088. {
  57089. MA_ASSERT(pDataBuffer != NULL);
  57090. /* The connector should be uninitialized first. */
  57091. ma_resource_manager_data_buffer_uninit_connector(pDataBuffer->pResourceManager, pDataBuffer);
  57092. /* With the connector uninitialized we can unacquire the node. */
  57093. ma_resource_manager_data_buffer_node_unacquire(pDataBuffer->pResourceManager, pDataBuffer->pNode, NULL, NULL);
  57094. /* The base data source needs to be uninitialized as well. */
  57095. ma_data_source_uninit(&pDataBuffer->ds);
  57096. return MA_SUCCESS;
  57097. }
  57098. MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer)
  57099. {
  57100. ma_result result;
  57101. if (pDataBuffer == NULL) {
  57102. return MA_INVALID_ARGS;
  57103. }
  57104. if (ma_resource_manager_data_buffer_result(pDataBuffer) == MA_SUCCESS) {
  57105. /* The data buffer can be deleted synchronously. */
  57106. return ma_resource_manager_data_buffer_uninit_internal(pDataBuffer);
  57107. } else {
  57108. /*
  57109. The data buffer needs to be deleted asynchronously because it's still loading. With the status set to MA_UNAVAILABLE, no more pages will
  57110. be loaded and the uninitialization should happen fairly quickly. Since the caller owns the data buffer, we need to wait for this event
  57111. to get processed before returning.
  57112. */
  57113. ma_resource_manager_inline_notification notification;
  57114. ma_job job;
  57115. /*
  57116. We need to mark the node as unavailable so we don't try reading from it anymore, but also to
  57117. let the loading thread know that it needs to abort it's loading procedure.
  57118. */
  57119. ma_atomic_exchange_i32(&pDataBuffer->result, MA_UNAVAILABLE);
  57120. result = ma_resource_manager_inline_notification_init(pDataBuffer->pResourceManager, &notification);
  57121. if (result != MA_SUCCESS) {
  57122. return result; /* Failed to create the notification. This should rarely, if ever, happen. */
  57123. }
  57124. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER);
  57125. job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer);
  57126. job.data.resourceManager.freeDataBuffer.pDataBuffer = pDataBuffer;
  57127. job.data.resourceManager.freeDataBuffer.pDoneNotification = &notification;
  57128. job.data.resourceManager.freeDataBuffer.pDoneFence = NULL;
  57129. result = ma_resource_manager_post_job(pDataBuffer->pResourceManager, &job);
  57130. if (result != MA_SUCCESS) {
  57131. ma_resource_manager_inline_notification_uninit(&notification);
  57132. return result;
  57133. }
  57134. ma_resource_manager_inline_notification_wait_and_uninit(&notification);
  57135. }
  57136. return result;
  57137. }
  57138. 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)
  57139. {
  57140. ma_result result = MA_SUCCESS;
  57141. ma_uint64 framesRead = 0;
  57142. ma_bool32 isDecodedBufferBusy = MA_FALSE;
  57143. /* Safety. */
  57144. if (pFramesRead != NULL) {
  57145. *pFramesRead = 0;
  57146. }
  57147. if (frameCount == 0) {
  57148. return MA_INVALID_ARGS;
  57149. }
  57150. /*
  57151. 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
  57152. it's been uninitialized or is in the process of uninitializing.
  57153. */
  57154. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  57155. /* If the node is not initialized we need to abort with a busy code. */
  57156. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) {
  57157. return MA_BUSY; /* Still loading. */
  57158. }
  57159. /*
  57160. If we've got a seek scheduled we'll want to do that before reading. However, for paged buffers, there's
  57161. a chance that the sound hasn't yet been decoded up to the seek point will result in the seek failing. If
  57162. this happens, we need to keep the seek scheduled and return MA_BUSY.
  57163. */
  57164. if (pDataBuffer->seekToCursorOnNextRead) {
  57165. pDataBuffer->seekToCursorOnNextRead = MA_FALSE;
  57166. result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pDataBuffer->seekTargetInPCMFrames);
  57167. if (result != MA_SUCCESS) {
  57168. 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) {
  57169. pDataBuffer->seekToCursorOnNextRead = MA_TRUE; /* Keep the seek scheduled. We just haven't loaded enough data yet to do the seek properly. */
  57170. return MA_BUSY;
  57171. }
  57172. return result;
  57173. }
  57174. }
  57175. /*
  57176. For decoded buffers (not paged) we need to check beforehand how many frames we have available. We cannot
  57177. exceed this amount. We'll read as much as we can, and then return MA_BUSY.
  57178. */
  57179. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_decoded) {
  57180. ma_uint64 availableFrames;
  57181. isDecodedBufferBusy = (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY);
  57182. if (ma_resource_manager_data_buffer_get_available_frames(pDataBuffer, &availableFrames) == MA_SUCCESS) {
  57183. /* Don't try reading more than the available frame count. */
  57184. if (frameCount > availableFrames) {
  57185. frameCount = availableFrames;
  57186. /*
  57187. If there's no frames available we want to set the status to MA_AT_END. The logic below
  57188. will check if the node is busy, and if so, change it to MA_BUSY. The reason we do this
  57189. is because we don't want to call `ma_data_source_read_pcm_frames()` if the frame count
  57190. is 0 because that'll result in a situation where it's possible MA_AT_END won't get
  57191. returned.
  57192. */
  57193. if (frameCount == 0) {
  57194. result = MA_AT_END;
  57195. }
  57196. } else {
  57197. isDecodedBufferBusy = MA_FALSE; /* We have enough frames available in the buffer to avoid a MA_BUSY status. */
  57198. }
  57199. }
  57200. }
  57201. /* Don't attempt to read anything if we've got no frames available. */
  57202. if (frameCount > 0) {
  57203. result = ma_data_source_read_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pFramesOut, frameCount, &framesRead);
  57204. }
  57205. /*
  57206. 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
  57207. as at the end and terminate decoding.
  57208. */
  57209. if (result == MA_AT_END) {
  57210. if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) {
  57211. result = MA_BUSY;
  57212. }
  57213. }
  57214. if (isDecodedBufferBusy) {
  57215. result = MA_BUSY;
  57216. }
  57217. if (pFramesRead != NULL) {
  57218. *pFramesRead = framesRead;
  57219. }
  57220. if (result == MA_SUCCESS && framesRead == 0) {
  57221. result = MA_AT_END;
  57222. }
  57223. return result;
  57224. }
  57225. MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex)
  57226. {
  57227. ma_result result;
  57228. /* We cannot be using the data source after it's been uninitialized. */
  57229. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  57230. /* If we haven't yet got a connector we need to abort. */
  57231. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE) {
  57232. pDataBuffer->seekTargetInPCMFrames = frameIndex;
  57233. pDataBuffer->seekToCursorOnNextRead = MA_TRUE;
  57234. return MA_BUSY; /* Still loading. */
  57235. }
  57236. result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), frameIndex);
  57237. if (result != MA_SUCCESS) {
  57238. return result;
  57239. }
  57240. pDataBuffer->seekTargetInPCMFrames = ~(ma_uint64)0; /* <-- For identification purposes. */
  57241. pDataBuffer->seekToCursorOnNextRead = MA_FALSE;
  57242. return MA_SUCCESS;
  57243. }
  57244. 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)
  57245. {
  57246. /* We cannot be using the data source after it's been uninitialized. */
  57247. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  57248. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  57249. {
  57250. case ma_resource_manager_data_supply_type_encoded:
  57251. {
  57252. return ma_data_source_get_data_format(&pDataBuffer->connector.decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57253. };
  57254. case ma_resource_manager_data_supply_type_decoded:
  57255. {
  57256. *pFormat = pDataBuffer->pNode->data.backend.decoded.format;
  57257. *pChannels = pDataBuffer->pNode->data.backend.decoded.channels;
  57258. *pSampleRate = pDataBuffer->pNode->data.backend.decoded.sampleRate;
  57259. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels);
  57260. return MA_SUCCESS;
  57261. };
  57262. case ma_resource_manager_data_supply_type_decoded_paged:
  57263. {
  57264. *pFormat = pDataBuffer->pNode->data.backend.decodedPaged.data.format;
  57265. *pChannels = pDataBuffer->pNode->data.backend.decodedPaged.data.channels;
  57266. *pSampleRate = pDataBuffer->pNode->data.backend.decodedPaged.sampleRate;
  57267. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels);
  57268. return MA_SUCCESS;
  57269. };
  57270. case ma_resource_manager_data_supply_type_unknown:
  57271. {
  57272. return MA_BUSY; /* Still loading. */
  57273. };
  57274. default:
  57275. {
  57276. /* Unknown supply type. Should never hit this. */
  57277. return MA_INVALID_ARGS;
  57278. }
  57279. }
  57280. }
  57281. MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor)
  57282. {
  57283. /* We cannot be using the data source after it's been uninitialized. */
  57284. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  57285. if (pDataBuffer == NULL || pCursor == NULL) {
  57286. return MA_INVALID_ARGS;
  57287. }
  57288. *pCursor = 0;
  57289. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  57290. {
  57291. case ma_resource_manager_data_supply_type_encoded:
  57292. {
  57293. return ma_decoder_get_cursor_in_pcm_frames(&pDataBuffer->connector.decoder, pCursor);
  57294. };
  57295. case ma_resource_manager_data_supply_type_decoded:
  57296. {
  57297. return ma_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.buffer, pCursor);
  57298. };
  57299. case ma_resource_manager_data_supply_type_decoded_paged:
  57300. {
  57301. return ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, pCursor);
  57302. };
  57303. case ma_resource_manager_data_supply_type_unknown:
  57304. {
  57305. return MA_BUSY;
  57306. };
  57307. default:
  57308. {
  57309. return MA_INVALID_ARGS;
  57310. }
  57311. }
  57312. }
  57313. MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength)
  57314. {
  57315. /* We cannot be using the data source after it's been uninitialized. */
  57316. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  57317. if (pDataBuffer == NULL || pLength == NULL) {
  57318. return MA_INVALID_ARGS;
  57319. }
  57320. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  57321. return MA_BUSY; /* Still loading. */
  57322. }
  57323. return ma_data_source_get_length_in_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pLength);
  57324. }
  57325. MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer)
  57326. {
  57327. if (pDataBuffer == NULL) {
  57328. return MA_INVALID_ARGS;
  57329. }
  57330. return (ma_result)ma_atomic_load_i32((ma_result*)&pDataBuffer->result); /* Need a naughty const-cast here. */
  57331. }
  57332. MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping)
  57333. {
  57334. return ma_data_source_set_looping(pDataBuffer, isLooping);
  57335. }
  57336. MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer)
  57337. {
  57338. return ma_data_source_is_looping(pDataBuffer);
  57339. }
  57340. MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames)
  57341. {
  57342. if (pAvailableFrames == NULL) {
  57343. return MA_INVALID_ARGS;
  57344. }
  57345. *pAvailableFrames = 0;
  57346. if (pDataBuffer == NULL) {
  57347. return MA_INVALID_ARGS;
  57348. }
  57349. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  57350. if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) {
  57351. return MA_BUSY;
  57352. } else {
  57353. return MA_INVALID_OPERATION; /* No connector. */
  57354. }
  57355. }
  57356. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  57357. {
  57358. case ma_resource_manager_data_supply_type_encoded:
  57359. {
  57360. return ma_decoder_get_available_frames(&pDataBuffer->connector.decoder, pAvailableFrames);
  57361. };
  57362. case ma_resource_manager_data_supply_type_decoded:
  57363. {
  57364. return ma_audio_buffer_get_available_frames(&pDataBuffer->connector.buffer, pAvailableFrames);
  57365. };
  57366. case ma_resource_manager_data_supply_type_decoded_paged:
  57367. {
  57368. ma_uint64 cursor;
  57369. ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, &cursor);
  57370. if (pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount > cursor) {
  57371. *pAvailableFrames = pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount - cursor;
  57372. } else {
  57373. *pAvailableFrames = 0;
  57374. }
  57375. return MA_SUCCESS;
  57376. };
  57377. case ma_resource_manager_data_supply_type_unknown:
  57378. default:
  57379. {
  57380. /* Unknown supply type. Should never hit this. */
  57381. return MA_INVALID_ARGS;
  57382. }
  57383. }
  57384. }
  57385. MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags)
  57386. {
  57387. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pFilePath, NULL, 0, flags, NULL, NULL, NULL, NULL);
  57388. }
  57389. MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags)
  57390. {
  57391. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, NULL, pFilePath, 0, flags, NULL, NULL, NULL, NULL);
  57392. }
  57393. 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)
  57394. {
  57395. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pName, pNameW, 0, 0, pExistingData, NULL, NULL, NULL);
  57396. }
  57397. 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)
  57398. {
  57399. ma_resource_manager_data_supply data;
  57400. data.type = ma_resource_manager_data_supply_type_decoded;
  57401. data.backend.decoded.pData = pData;
  57402. data.backend.decoded.totalFrameCount = frameCount;
  57403. data.backend.decoded.format = format;
  57404. data.backend.decoded.channels = channels;
  57405. data.backend.decoded.sampleRate = sampleRate;
  57406. return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data);
  57407. }
  57408. 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)
  57409. {
  57410. return ma_resource_manager_register_decoded_data_internal(pResourceManager, pName, NULL, pData, frameCount, format, channels, sampleRate);
  57411. }
  57412. 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)
  57413. {
  57414. return ma_resource_manager_register_decoded_data_internal(pResourceManager, NULL, pName, pData, frameCount, format, channels, sampleRate);
  57415. }
  57416. 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)
  57417. {
  57418. ma_resource_manager_data_supply data;
  57419. data.type = ma_resource_manager_data_supply_type_encoded;
  57420. data.backend.encoded.pData = pData;
  57421. data.backend.encoded.sizeInBytes = sizeInBytes;
  57422. return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data);
  57423. }
  57424. MA_API ma_result ma_resource_manager_register_encoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, size_t sizeInBytes)
  57425. {
  57426. return ma_resource_manager_register_encoded_data_internal(pResourceManager, pName, NULL, pData, sizeInBytes);
  57427. }
  57428. 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)
  57429. {
  57430. return ma_resource_manager_register_encoded_data_internal(pResourceManager, NULL, pName, pData, sizeInBytes);
  57431. }
  57432. MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath)
  57433. {
  57434. return ma_resource_manager_unregister_data(pResourceManager, pFilePath);
  57435. }
  57436. MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath)
  57437. {
  57438. return ma_resource_manager_unregister_data_w(pResourceManager, pFilePath);
  57439. }
  57440. MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName)
  57441. {
  57442. return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, pName, NULL);
  57443. }
  57444. MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName)
  57445. {
  57446. return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, NULL, pName);
  57447. }
  57448. static ma_uint32 ma_resource_manager_data_stream_next_execution_order(ma_resource_manager_data_stream* pDataStream)
  57449. {
  57450. MA_ASSERT(pDataStream != NULL);
  57451. return ma_atomic_fetch_add_32(&pDataStream->executionCounter, 1);
  57452. }
  57453. static ma_bool32 ma_resource_manager_data_stream_is_decoder_at_end(const ma_resource_manager_data_stream* pDataStream)
  57454. {
  57455. MA_ASSERT(pDataStream != NULL);
  57456. return ma_atomic_load_32((ma_bool32*)&pDataStream->isDecoderAtEnd);
  57457. }
  57458. static ma_uint32 ma_resource_manager_data_stream_seek_counter(const ma_resource_manager_data_stream* pDataStream)
  57459. {
  57460. MA_ASSERT(pDataStream != NULL);
  57461. return ma_atomic_load_32((ma_uint32*)&pDataStream->seekCounter);
  57462. }
  57463. static ma_result ma_resource_manager_data_stream_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  57464. {
  57465. return ma_resource_manager_data_stream_read_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pFramesOut, frameCount, pFramesRead);
  57466. }
  57467. static ma_result ma_resource_manager_data_stream_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  57468. {
  57469. return ma_resource_manager_data_stream_seek_to_pcm_frame((ma_resource_manager_data_stream*)pDataSource, frameIndex);
  57470. }
  57471. 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)
  57472. {
  57473. return ma_resource_manager_data_stream_get_data_format((ma_resource_manager_data_stream*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57474. }
  57475. static ma_result ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  57476. {
  57477. return ma_resource_manager_data_stream_get_cursor_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pCursor);
  57478. }
  57479. static ma_result ma_resource_manager_data_stream_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  57480. {
  57481. return ma_resource_manager_data_stream_get_length_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pLength);
  57482. }
  57483. static ma_result ma_resource_manager_data_stream_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  57484. {
  57485. ma_resource_manager_data_stream* pDataStream = (ma_resource_manager_data_stream*)pDataSource;
  57486. MA_ASSERT(pDataStream != NULL);
  57487. ma_atomic_exchange_32(&pDataStream->isLooping, isLooping);
  57488. return MA_SUCCESS;
  57489. }
  57490. static ma_data_source_vtable g_ma_resource_manager_data_stream_vtable =
  57491. {
  57492. ma_resource_manager_data_stream_cb__read_pcm_frames,
  57493. ma_resource_manager_data_stream_cb__seek_to_pcm_frame,
  57494. ma_resource_manager_data_stream_cb__get_data_format,
  57495. ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames,
  57496. ma_resource_manager_data_stream_cb__get_length_in_pcm_frames,
  57497. ma_resource_manager_data_stream_cb__set_looping,
  57498. 0 /*MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT*/
  57499. };
  57500. static void ma_resource_manager_data_stream_set_absolute_cursor(ma_resource_manager_data_stream* pDataStream, ma_uint64 absoluteCursor)
  57501. {
  57502. /* Loop if possible. */
  57503. if (absoluteCursor > pDataStream->totalLengthInPCMFrames && pDataStream->totalLengthInPCMFrames > 0) {
  57504. absoluteCursor = absoluteCursor % pDataStream->totalLengthInPCMFrames;
  57505. }
  57506. ma_atomic_exchange_64(&pDataStream->absoluteCursor, absoluteCursor);
  57507. }
  57508. 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)
  57509. {
  57510. ma_result result;
  57511. ma_data_source_config dataSourceConfig;
  57512. char* pFilePathCopy = NULL;
  57513. wchar_t* pFilePathWCopy = NULL;
  57514. ma_job job;
  57515. ma_bool32 waitBeforeReturning = MA_FALSE;
  57516. ma_resource_manager_inline_notification waitNotification;
  57517. ma_resource_manager_pipeline_notifications notifications;
  57518. if (pDataStream == NULL) {
  57519. if (pConfig != NULL && pConfig->pNotifications != NULL) {
  57520. ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications);
  57521. }
  57522. return MA_INVALID_ARGS;
  57523. }
  57524. MA_ZERO_OBJECT(pDataStream);
  57525. if (pConfig == NULL) {
  57526. return MA_INVALID_ARGS;
  57527. }
  57528. if (pConfig->pNotifications != NULL) {
  57529. 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. */
  57530. } else {
  57531. MA_ZERO_OBJECT(&notifications);
  57532. }
  57533. dataSourceConfig = ma_data_source_config_init();
  57534. dataSourceConfig.vtable = &g_ma_resource_manager_data_stream_vtable;
  57535. result = ma_data_source_init(&dataSourceConfig, &pDataStream->ds);
  57536. if (result != MA_SUCCESS) {
  57537. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57538. return result;
  57539. }
  57540. pDataStream->pResourceManager = pResourceManager;
  57541. pDataStream->flags = pConfig->flags;
  57542. pDataStream->result = MA_BUSY;
  57543. ma_data_source_set_range_in_pcm_frames(pDataStream, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  57544. ma_data_source_set_loop_point_in_pcm_frames(pDataStream, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  57545. ma_data_source_set_looping(pDataStream, pConfig->isLooping);
  57546. if (pResourceManager == NULL || (pConfig->pFilePath == NULL && pConfig->pFilePathW == NULL)) {
  57547. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57548. return MA_INVALID_ARGS;
  57549. }
  57550. /* 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. */
  57551. /* 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. */
  57552. if (pConfig->pFilePath != NULL) {
  57553. pFilePathCopy = ma_copy_string(pConfig->pFilePath, &pResourceManager->config.allocationCallbacks);
  57554. } else {
  57555. pFilePathWCopy = ma_copy_string_w(pConfig->pFilePathW, &pResourceManager->config.allocationCallbacks);
  57556. }
  57557. if (pFilePathCopy == NULL && pFilePathWCopy == NULL) {
  57558. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57559. return MA_OUT_OF_MEMORY;
  57560. }
  57561. /*
  57562. 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
  57563. can return immediately. Likewise, we'll also check for MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT and do the same.
  57564. */
  57565. if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0 || (pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  57566. waitBeforeReturning = MA_TRUE;
  57567. ma_resource_manager_inline_notification_init(pResourceManager, &waitNotification);
  57568. }
  57569. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  57570. /* Set the absolute cursor to our initial seek position so retrieval of the cursor returns a good value. */
  57571. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, pConfig->initialSeekPointInPCMFrames);
  57572. /* 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. */
  57573. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM);
  57574. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57575. job.data.resourceManager.loadDataStream.pDataStream = pDataStream;
  57576. job.data.resourceManager.loadDataStream.pFilePath = pFilePathCopy;
  57577. job.data.resourceManager.loadDataStream.pFilePathW = pFilePathWCopy;
  57578. job.data.resourceManager.loadDataStream.initialSeekPoint = pConfig->initialSeekPointInPCMFrames;
  57579. job.data.resourceManager.loadDataStream.pInitNotification = (waitBeforeReturning == MA_TRUE) ? &waitNotification : notifications.init.pNotification;
  57580. job.data.resourceManager.loadDataStream.pInitFence = notifications.init.pFence;
  57581. result = ma_resource_manager_post_job(pResourceManager, &job);
  57582. if (result != MA_SUCCESS) {
  57583. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  57584. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  57585. if (waitBeforeReturning) {
  57586. ma_resource_manager_inline_notification_uninit(&waitNotification);
  57587. }
  57588. ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks);
  57589. ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks);
  57590. return result;
  57591. }
  57592. /* Wait if needed. */
  57593. if (waitBeforeReturning) {
  57594. ma_resource_manager_inline_notification_wait_and_uninit(&waitNotification);
  57595. if (notifications.init.pNotification != NULL) {
  57596. ma_async_notification_signal(notifications.init.pNotification);
  57597. }
  57598. /*
  57599. If there was an error during initialization make sure we return that result here. We don't want to do this
  57600. if we're not waiting because it will most likely be in a busy state.
  57601. */
  57602. if (pDataStream->result != MA_SUCCESS) {
  57603. return pDataStream->result;
  57604. }
  57605. /* NOTE: Do not release pInitFence here. That will be done by the job. */
  57606. }
  57607. return MA_SUCCESS;
  57608. }
  57609. 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)
  57610. {
  57611. ma_resource_manager_data_source_config config;
  57612. config = ma_resource_manager_data_source_config_init();
  57613. config.pFilePath = pFilePath;
  57614. config.flags = flags;
  57615. config.pNotifications = pNotifications;
  57616. return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream);
  57617. }
  57618. 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)
  57619. {
  57620. ma_resource_manager_data_source_config config;
  57621. config = ma_resource_manager_data_source_config_init();
  57622. config.pFilePathW = pFilePath;
  57623. config.flags = flags;
  57624. config.pNotifications = pNotifications;
  57625. return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream);
  57626. }
  57627. MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream)
  57628. {
  57629. ma_resource_manager_inline_notification freeEvent;
  57630. ma_job job;
  57631. if (pDataStream == NULL) {
  57632. return MA_INVALID_ARGS;
  57633. }
  57634. /* The first thing to do is set the result to unavailable. This will prevent future page decoding. */
  57635. ma_atomic_exchange_i32(&pDataStream->result, MA_UNAVAILABLE);
  57636. /*
  57637. 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
  57638. to wait for it to complete before returning which means we need an event.
  57639. */
  57640. ma_resource_manager_inline_notification_init(pDataStream->pResourceManager, &freeEvent);
  57641. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM);
  57642. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57643. job.data.resourceManager.freeDataStream.pDataStream = pDataStream;
  57644. job.data.resourceManager.freeDataStream.pDoneNotification = &freeEvent;
  57645. job.data.resourceManager.freeDataStream.pDoneFence = NULL;
  57646. ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  57647. /* We need to wait for the job to finish processing before we return. */
  57648. ma_resource_manager_inline_notification_wait_and_uninit(&freeEvent);
  57649. return MA_SUCCESS;
  57650. }
  57651. static ma_uint32 ma_resource_manager_data_stream_get_page_size_in_frames(ma_resource_manager_data_stream* pDataStream)
  57652. {
  57653. MA_ASSERT(pDataStream != NULL);
  57654. MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE);
  57655. return MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDataStream->decoder.outputSampleRate/1000);
  57656. }
  57657. static void* ma_resource_manager_data_stream_get_page_data_pointer(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex, ma_uint32 relativeCursor)
  57658. {
  57659. MA_ASSERT(pDataStream != NULL);
  57660. MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE);
  57661. MA_ASSERT(pageIndex == 0 || pageIndex == 1);
  57662. 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));
  57663. }
  57664. static void ma_resource_manager_data_stream_fill_page(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex)
  57665. {
  57666. ma_result result = MA_SUCCESS;
  57667. ma_uint64 pageSizeInFrames;
  57668. ma_uint64 totalFramesReadForThisPage = 0;
  57669. void* pPageData = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pageIndex, 0);
  57670. pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream);
  57671. /* The decoder needs to inherit the stream's looping and range state. */
  57672. {
  57673. ma_uint64 rangeBeg;
  57674. ma_uint64 rangeEnd;
  57675. ma_uint64 loopPointBeg;
  57676. ma_uint64 loopPointEnd;
  57677. ma_data_source_set_looping(&pDataStream->decoder, ma_resource_manager_data_stream_is_looping(pDataStream));
  57678. ma_data_source_get_range_in_pcm_frames(pDataStream, &rangeBeg, &rangeEnd);
  57679. ma_data_source_set_range_in_pcm_frames(&pDataStream->decoder, rangeBeg, rangeEnd);
  57680. ma_data_source_get_loop_point_in_pcm_frames(pDataStream, &loopPointBeg, &loopPointEnd);
  57681. ma_data_source_set_loop_point_in_pcm_frames(&pDataStream->decoder, loopPointBeg, loopPointEnd);
  57682. }
  57683. /* Just read straight from the decoder. It will deal with ranges and looping for us. */
  57684. result = ma_data_source_read_pcm_frames(&pDataStream->decoder, pPageData, pageSizeInFrames, &totalFramesReadForThisPage);
  57685. if (result == MA_AT_END || totalFramesReadForThisPage < pageSizeInFrames) {
  57686. ma_atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_TRUE);
  57687. }
  57688. ma_atomic_exchange_32(&pDataStream->pageFrameCount[pageIndex], (ma_uint32)totalFramesReadForThisPage);
  57689. ma_atomic_exchange_32(&pDataStream->isPageValid[pageIndex], MA_TRUE);
  57690. }
  57691. static void ma_resource_manager_data_stream_fill_pages(ma_resource_manager_data_stream* pDataStream)
  57692. {
  57693. ma_uint32 iPage;
  57694. MA_ASSERT(pDataStream != NULL);
  57695. for (iPage = 0; iPage < 2; iPage += 1) {
  57696. ma_resource_manager_data_stream_fill_page(pDataStream, iPage);
  57697. }
  57698. }
  57699. static ma_result ma_resource_manager_data_stream_map(ma_resource_manager_data_stream* pDataStream, void** ppFramesOut, ma_uint64* pFrameCount)
  57700. {
  57701. ma_uint64 framesAvailable;
  57702. ma_uint64 frameCount = 0;
  57703. /* We cannot be using the data source after it's been uninitialized. */
  57704. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57705. if (pFrameCount != NULL) {
  57706. frameCount = *pFrameCount;
  57707. *pFrameCount = 0;
  57708. }
  57709. if (ppFramesOut != NULL) {
  57710. *ppFramesOut = NULL;
  57711. }
  57712. if (pDataStream == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
  57713. return MA_INVALID_ARGS;
  57714. }
  57715. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57716. return MA_INVALID_OPERATION;
  57717. }
  57718. /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */
  57719. if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) {
  57720. return MA_BUSY;
  57721. }
  57722. /* If the page we're on is invalid it means we've caught up to the job thread. */
  57723. if (ma_atomic_load_32(&pDataStream->isPageValid[pDataStream->currentPageIndex]) == MA_FALSE) {
  57724. framesAvailable = 0;
  57725. } else {
  57726. /*
  57727. 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
  57728. that the unmap process will only post an update for one page at a time. Keeping mapping tied to page boundaries makes this simpler.
  57729. */
  57730. ma_uint32 currentPageFrameCount = ma_atomic_load_32(&pDataStream->pageFrameCount[pDataStream->currentPageIndex]);
  57731. MA_ASSERT(currentPageFrameCount >= pDataStream->relativeCursor);
  57732. framesAvailable = currentPageFrameCount - pDataStream->relativeCursor;
  57733. }
  57734. /* If there's no frames available and the result is set to MA_AT_END we need to return MA_AT_END. */
  57735. if (framesAvailable == 0) {
  57736. if (ma_resource_manager_data_stream_is_decoder_at_end(pDataStream)) {
  57737. return MA_AT_END;
  57738. } else {
  57739. 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. */
  57740. }
  57741. }
  57742. MA_ASSERT(framesAvailable > 0);
  57743. if (frameCount > framesAvailable) {
  57744. frameCount = framesAvailable;
  57745. }
  57746. *ppFramesOut = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pDataStream->currentPageIndex, pDataStream->relativeCursor);
  57747. *pFrameCount = frameCount;
  57748. return MA_SUCCESS;
  57749. }
  57750. static ma_result ma_resource_manager_data_stream_unmap(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameCount)
  57751. {
  57752. ma_uint32 newRelativeCursor;
  57753. ma_uint32 pageSizeInFrames;
  57754. ma_job job;
  57755. /* We cannot be using the data source after it's been uninitialized. */
  57756. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57757. if (pDataStream == NULL) {
  57758. return MA_INVALID_ARGS;
  57759. }
  57760. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57761. return MA_INVALID_OPERATION;
  57762. }
  57763. /* The frame count should always fit inside a 32-bit integer. */
  57764. if (frameCount > 0xFFFFFFFF) {
  57765. return MA_INVALID_ARGS;
  57766. }
  57767. pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream);
  57768. /* The absolute cursor needs to be updated for ma_resource_manager_data_stream_get_cursor_in_pcm_frames(). */
  57769. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, ma_atomic_load_64(&pDataStream->absoluteCursor) + frameCount);
  57770. /* Here is where we need to check if we need to load a new page, and if so, post a job to load it. */
  57771. newRelativeCursor = pDataStream->relativeCursor + (ma_uint32)frameCount;
  57772. /* 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. */
  57773. if (newRelativeCursor >= pageSizeInFrames) {
  57774. newRelativeCursor -= pageSizeInFrames;
  57775. /* Here is where we post the job start decoding. */
  57776. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM);
  57777. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57778. job.data.resourceManager.pageDataStream.pDataStream = pDataStream;
  57779. job.data.resourceManager.pageDataStream.pageIndex = pDataStream->currentPageIndex;
  57780. /* The page needs to be marked as invalid so that the public API doesn't try reading from it. */
  57781. ma_atomic_exchange_32(&pDataStream->isPageValid[pDataStream->currentPageIndex], MA_FALSE);
  57782. /* Before posting the job we need to make sure we set some state. */
  57783. pDataStream->relativeCursor = newRelativeCursor;
  57784. pDataStream->currentPageIndex = (pDataStream->currentPageIndex + 1) & 0x01;
  57785. return ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  57786. } else {
  57787. /* We haven't moved into a new page so we can just move the cursor forward. */
  57788. pDataStream->relativeCursor = newRelativeCursor;
  57789. return MA_SUCCESS;
  57790. }
  57791. }
  57792. 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)
  57793. {
  57794. ma_result result = MA_SUCCESS;
  57795. ma_uint64 totalFramesProcessed;
  57796. ma_format format;
  57797. ma_uint32 channels;
  57798. /* Safety. */
  57799. if (pFramesRead != NULL) {
  57800. *pFramesRead = 0;
  57801. }
  57802. if (frameCount == 0) {
  57803. return MA_INVALID_ARGS;
  57804. }
  57805. /* We cannot be using the data source after it's been uninitialized. */
  57806. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57807. if (pDataStream == NULL) {
  57808. return MA_INVALID_ARGS;
  57809. }
  57810. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57811. return MA_INVALID_OPERATION;
  57812. }
  57813. /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */
  57814. if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) {
  57815. return MA_BUSY;
  57816. }
  57817. ma_resource_manager_data_stream_get_data_format(pDataStream, &format, &channels, NULL, NULL, 0);
  57818. /* Reading is implemented in terms of map/unmap. We need to run this in a loop because mapping is clamped against page boundaries. */
  57819. totalFramesProcessed = 0;
  57820. while (totalFramesProcessed < frameCount) {
  57821. void* pMappedFrames;
  57822. ma_uint64 mappedFrameCount;
  57823. mappedFrameCount = frameCount - totalFramesProcessed;
  57824. result = ma_resource_manager_data_stream_map(pDataStream, &pMappedFrames, &mappedFrameCount);
  57825. if (result != MA_SUCCESS) {
  57826. break;
  57827. }
  57828. /* 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. */
  57829. if (pFramesOut != NULL) {
  57830. ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, format, channels), pMappedFrames, mappedFrameCount, format, channels);
  57831. }
  57832. totalFramesProcessed += mappedFrameCount;
  57833. result = ma_resource_manager_data_stream_unmap(pDataStream, mappedFrameCount);
  57834. if (result != MA_SUCCESS) {
  57835. 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. */
  57836. }
  57837. }
  57838. if (pFramesRead != NULL) {
  57839. *pFramesRead = totalFramesProcessed;
  57840. }
  57841. if (result == MA_SUCCESS && totalFramesProcessed == 0) {
  57842. result = MA_AT_END;
  57843. }
  57844. return result;
  57845. }
  57846. MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex)
  57847. {
  57848. ma_job job;
  57849. ma_result streamResult;
  57850. streamResult = ma_resource_manager_data_stream_result(pDataStream);
  57851. /* We cannot be using the data source after it's been uninitialized. */
  57852. MA_ASSERT(streamResult != MA_UNAVAILABLE);
  57853. if (pDataStream == NULL) {
  57854. return MA_INVALID_ARGS;
  57855. }
  57856. if (streamResult != MA_SUCCESS && streamResult != MA_BUSY) {
  57857. return MA_INVALID_OPERATION;
  57858. }
  57859. /* If we're not already seeking and we're sitting on the same frame, just make this a no-op. */
  57860. if (ma_atomic_load_32(&pDataStream->seekCounter) == 0) {
  57861. if (ma_atomic_load_64(&pDataStream->absoluteCursor) == frameIndex) {
  57862. return MA_SUCCESS;
  57863. }
  57864. }
  57865. /* 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. */
  57866. ma_atomic_fetch_add_32(&pDataStream->seekCounter, 1);
  57867. /* Update the absolute cursor so that ma_resource_manager_data_stream_get_cursor_in_pcm_frames() returns the new position. */
  57868. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, frameIndex);
  57869. /*
  57870. 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
  57871. 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
  57872. the first page.
  57873. */
  57874. pDataStream->relativeCursor = 0;
  57875. pDataStream->currentPageIndex = 0;
  57876. ma_atomic_exchange_32(&pDataStream->isPageValid[0], MA_FALSE);
  57877. ma_atomic_exchange_32(&pDataStream->isPageValid[1], MA_FALSE);
  57878. /* 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. */
  57879. ma_atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_FALSE);
  57880. /*
  57881. 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
  57882. are invalid and any content contained within them will be discarded and replaced with newly decoded data.
  57883. */
  57884. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM);
  57885. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  57886. job.data.resourceManager.seekDataStream.pDataStream = pDataStream;
  57887. job.data.resourceManager.seekDataStream.frameIndex = frameIndex;
  57888. return ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  57889. }
  57890. 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)
  57891. {
  57892. /* We cannot be using the data source after it's been uninitialized. */
  57893. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57894. if (pFormat != NULL) {
  57895. *pFormat = ma_format_unknown;
  57896. }
  57897. if (pChannels != NULL) {
  57898. *pChannels = 0;
  57899. }
  57900. if (pSampleRate != NULL) {
  57901. *pSampleRate = 0;
  57902. }
  57903. if (pChannelMap != NULL) {
  57904. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  57905. }
  57906. if (pDataStream == NULL) {
  57907. return MA_INVALID_ARGS;
  57908. }
  57909. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  57910. return MA_INVALID_OPERATION;
  57911. }
  57912. /*
  57913. 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
  57914. such that the application is responsible for ensuring it's not called while uninitializing so it should be safe.
  57915. */
  57916. return ma_data_source_get_data_format(&pDataStream->decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  57917. }
  57918. MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor)
  57919. {
  57920. ma_result result;
  57921. if (pCursor == NULL) {
  57922. return MA_INVALID_ARGS;
  57923. }
  57924. *pCursor = 0;
  57925. /* We cannot be using the data source after it's been uninitialized. */
  57926. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  57927. if (pDataStream == NULL) {
  57928. return MA_INVALID_ARGS;
  57929. }
  57930. /*
  57931. If the stream is in an erroneous state we need to return an invalid operation. We can allow
  57932. this to be called when the data stream is in a busy state because the caller may have asked
  57933. for an initial seek position and it's convenient to return that as the cursor position.
  57934. */
  57935. result = ma_resource_manager_data_stream_result(pDataStream);
  57936. if (result != MA_SUCCESS && result != MA_BUSY) {
  57937. return MA_INVALID_OPERATION;
  57938. }
  57939. *pCursor = ma_atomic_load_64(&pDataStream->absoluteCursor);
  57940. return MA_SUCCESS;
  57941. }
  57942. MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength)
  57943. {
  57944. ma_result streamResult;
  57945. if (pLength == NULL) {
  57946. return MA_INVALID_ARGS;
  57947. }
  57948. *pLength = 0;
  57949. streamResult = ma_resource_manager_data_stream_result(pDataStream);
  57950. /* We cannot be using the data source after it's been uninitialized. */
  57951. MA_ASSERT(streamResult != MA_UNAVAILABLE);
  57952. if (pDataStream == NULL) {
  57953. return MA_INVALID_ARGS;
  57954. }
  57955. if (streamResult != MA_SUCCESS) {
  57956. return streamResult;
  57957. }
  57958. /*
  57959. 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
  57960. calculated when we initialized it on the job thread.
  57961. */
  57962. *pLength = pDataStream->totalLengthInPCMFrames;
  57963. if (*pLength == 0) {
  57964. return MA_NOT_IMPLEMENTED; /* Some decoders may not have a known length. */
  57965. }
  57966. return MA_SUCCESS;
  57967. }
  57968. MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream)
  57969. {
  57970. if (pDataStream == NULL) {
  57971. return MA_INVALID_ARGS;
  57972. }
  57973. return (ma_result)ma_atomic_load_i32(&pDataStream->result);
  57974. }
  57975. MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping)
  57976. {
  57977. return ma_data_source_set_looping(pDataStream, isLooping);
  57978. }
  57979. MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream)
  57980. {
  57981. if (pDataStream == NULL) {
  57982. return MA_FALSE;
  57983. }
  57984. return ma_atomic_load_32((ma_bool32*)&pDataStream->isLooping); /* Naughty const-cast. Value won't change from here in practice (maybe from another thread). */
  57985. }
  57986. MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames)
  57987. {
  57988. ma_uint32 pageIndex0;
  57989. ma_uint32 pageIndex1;
  57990. ma_uint32 relativeCursor;
  57991. ma_uint64 availableFrames;
  57992. if (pAvailableFrames == NULL) {
  57993. return MA_INVALID_ARGS;
  57994. }
  57995. *pAvailableFrames = 0;
  57996. if (pDataStream == NULL) {
  57997. return MA_INVALID_ARGS;
  57998. }
  57999. pageIndex0 = pDataStream->currentPageIndex;
  58000. pageIndex1 = (pDataStream->currentPageIndex + 1) & 0x01;
  58001. relativeCursor = pDataStream->relativeCursor;
  58002. availableFrames = 0;
  58003. if (ma_atomic_load_32(&pDataStream->isPageValid[pageIndex0])) {
  58004. availableFrames += ma_atomic_load_32(&pDataStream->pageFrameCount[pageIndex0]) - relativeCursor;
  58005. if (ma_atomic_load_32(&pDataStream->isPageValid[pageIndex1])) {
  58006. availableFrames += ma_atomic_load_32(&pDataStream->pageFrameCount[pageIndex1]);
  58007. }
  58008. }
  58009. *pAvailableFrames = availableFrames;
  58010. return MA_SUCCESS;
  58011. }
  58012. 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)
  58013. {
  58014. if (pDataSource == NULL) {
  58015. return MA_INVALID_ARGS;
  58016. }
  58017. MA_ZERO_OBJECT(pDataSource);
  58018. if (pConfig == NULL) {
  58019. return MA_INVALID_ARGS;
  58020. }
  58021. if (pResourceManager == NULL) {
  58022. return MA_INVALID_ARGS;
  58023. }
  58024. pDataSource->flags = pConfig->flags;
  58025. return MA_SUCCESS;
  58026. }
  58027. 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)
  58028. {
  58029. ma_result result;
  58030. result = ma_resource_manager_data_source_preinit(pResourceManager, pConfig, pDataSource);
  58031. if (result != MA_SUCCESS) {
  58032. return result;
  58033. }
  58034. /* The data source itself is just a data stream or a data buffer. */
  58035. if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58036. return ma_resource_manager_data_stream_init_ex(pResourceManager, pConfig, &pDataSource->backend.stream);
  58037. } else {
  58038. return ma_resource_manager_data_buffer_init_ex(pResourceManager, pConfig, &pDataSource->backend.buffer);
  58039. }
  58040. }
  58041. 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)
  58042. {
  58043. ma_resource_manager_data_source_config config;
  58044. config = ma_resource_manager_data_source_config_init();
  58045. config.pFilePath = pName;
  58046. config.flags = flags;
  58047. config.pNotifications = pNotifications;
  58048. return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource);
  58049. }
  58050. 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)
  58051. {
  58052. ma_resource_manager_data_source_config config;
  58053. config = ma_resource_manager_data_source_config_init();
  58054. config.pFilePathW = pName;
  58055. config.flags = flags;
  58056. config.pNotifications = pNotifications;
  58057. return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource);
  58058. }
  58059. 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)
  58060. {
  58061. ma_result result;
  58062. ma_resource_manager_data_source_config config;
  58063. if (pExistingDataSource == NULL) {
  58064. return MA_INVALID_ARGS;
  58065. }
  58066. config = ma_resource_manager_data_source_config_init();
  58067. config.flags = pExistingDataSource->flags;
  58068. result = ma_resource_manager_data_source_preinit(pResourceManager, &config, pDataSource);
  58069. if (result != MA_SUCCESS) {
  58070. return result;
  58071. }
  58072. /* Copying can only be done from data buffers. Streams cannot be copied. */
  58073. if ((pExistingDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58074. return MA_INVALID_OPERATION;
  58075. }
  58076. return ma_resource_manager_data_buffer_init_copy(pResourceManager, &pExistingDataSource->backend.buffer, &pDataSource->backend.buffer);
  58077. }
  58078. MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource)
  58079. {
  58080. if (pDataSource == NULL) {
  58081. return MA_INVALID_ARGS;
  58082. }
  58083. /* All we need to is uninitialize the underlying data buffer or data stream. */
  58084. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58085. return ma_resource_manager_data_stream_uninit(&pDataSource->backend.stream);
  58086. } else {
  58087. return ma_resource_manager_data_buffer_uninit(&pDataSource->backend.buffer);
  58088. }
  58089. }
  58090. 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)
  58091. {
  58092. /* Safety. */
  58093. if (pFramesRead != NULL) {
  58094. *pFramesRead = 0;
  58095. }
  58096. if (pDataSource == NULL) {
  58097. return MA_INVALID_ARGS;
  58098. }
  58099. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58100. return ma_resource_manager_data_stream_read_pcm_frames(&pDataSource->backend.stream, pFramesOut, frameCount, pFramesRead);
  58101. } else {
  58102. return ma_resource_manager_data_buffer_read_pcm_frames(&pDataSource->backend.buffer, pFramesOut, frameCount, pFramesRead);
  58103. }
  58104. }
  58105. MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex)
  58106. {
  58107. if (pDataSource == NULL) {
  58108. return MA_INVALID_ARGS;
  58109. }
  58110. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58111. return ma_resource_manager_data_stream_seek_to_pcm_frame(&pDataSource->backend.stream, frameIndex);
  58112. } else {
  58113. return ma_resource_manager_data_buffer_seek_to_pcm_frame(&pDataSource->backend.buffer, frameIndex);
  58114. }
  58115. }
  58116. MA_API ma_result ma_resource_manager_data_source_map(ma_resource_manager_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount)
  58117. {
  58118. if (pDataSource == NULL) {
  58119. return MA_INVALID_ARGS;
  58120. }
  58121. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58122. return ma_resource_manager_data_stream_map(&pDataSource->backend.stream, ppFramesOut, pFrameCount);
  58123. } else {
  58124. return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */
  58125. }
  58126. }
  58127. MA_API ma_result ma_resource_manager_data_source_unmap(ma_resource_manager_data_source* pDataSource, ma_uint64 frameCount)
  58128. {
  58129. if (pDataSource == NULL) {
  58130. return MA_INVALID_ARGS;
  58131. }
  58132. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58133. return ma_resource_manager_data_stream_unmap(&pDataSource->backend.stream, frameCount);
  58134. } else {
  58135. return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */
  58136. }
  58137. }
  58138. 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)
  58139. {
  58140. if (pDataSource == NULL) {
  58141. return MA_INVALID_ARGS;
  58142. }
  58143. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58144. return ma_resource_manager_data_stream_get_data_format(&pDataSource->backend.stream, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  58145. } else {
  58146. return ma_resource_manager_data_buffer_get_data_format(&pDataSource->backend.buffer, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  58147. }
  58148. }
  58149. MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor)
  58150. {
  58151. if (pDataSource == NULL) {
  58152. return MA_INVALID_ARGS;
  58153. }
  58154. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58155. return ma_resource_manager_data_stream_get_cursor_in_pcm_frames(&pDataSource->backend.stream, pCursor);
  58156. } else {
  58157. return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(&pDataSource->backend.buffer, pCursor);
  58158. }
  58159. }
  58160. MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength)
  58161. {
  58162. if (pDataSource == NULL) {
  58163. return MA_INVALID_ARGS;
  58164. }
  58165. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58166. return ma_resource_manager_data_stream_get_length_in_pcm_frames(&pDataSource->backend.stream, pLength);
  58167. } else {
  58168. return ma_resource_manager_data_buffer_get_length_in_pcm_frames(&pDataSource->backend.buffer, pLength);
  58169. }
  58170. }
  58171. MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource)
  58172. {
  58173. if (pDataSource == NULL) {
  58174. return MA_INVALID_ARGS;
  58175. }
  58176. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58177. return ma_resource_manager_data_stream_result(&pDataSource->backend.stream);
  58178. } else {
  58179. return ma_resource_manager_data_buffer_result(&pDataSource->backend.buffer);
  58180. }
  58181. }
  58182. MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping)
  58183. {
  58184. if (pDataSource == NULL) {
  58185. return MA_INVALID_ARGS;
  58186. }
  58187. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58188. return ma_resource_manager_data_stream_set_looping(&pDataSource->backend.stream, isLooping);
  58189. } else {
  58190. return ma_resource_manager_data_buffer_set_looping(&pDataSource->backend.buffer, isLooping);
  58191. }
  58192. }
  58193. MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource)
  58194. {
  58195. if (pDataSource == NULL) {
  58196. return MA_FALSE;
  58197. }
  58198. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58199. return ma_resource_manager_data_stream_is_looping(&pDataSource->backend.stream);
  58200. } else {
  58201. return ma_resource_manager_data_buffer_is_looping(&pDataSource->backend.buffer);
  58202. }
  58203. }
  58204. MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames)
  58205. {
  58206. if (pAvailableFrames == NULL) {
  58207. return MA_INVALID_ARGS;
  58208. }
  58209. *pAvailableFrames = 0;
  58210. if (pDataSource == NULL) {
  58211. return MA_INVALID_ARGS;
  58212. }
  58213. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  58214. return ma_resource_manager_data_stream_get_available_frames(&pDataSource->backend.stream, pAvailableFrames);
  58215. } else {
  58216. return ma_resource_manager_data_buffer_get_available_frames(&pDataSource->backend.buffer, pAvailableFrames);
  58217. }
  58218. }
  58219. MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob)
  58220. {
  58221. if (pResourceManager == NULL) {
  58222. return MA_INVALID_ARGS;
  58223. }
  58224. return ma_job_queue_post(&pResourceManager->jobQueue, pJob);
  58225. }
  58226. MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager)
  58227. {
  58228. ma_job job = ma_job_init(MA_JOB_TYPE_QUIT);
  58229. return ma_resource_manager_post_job(pResourceManager, &job);
  58230. }
  58231. MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob)
  58232. {
  58233. if (pResourceManager == NULL) {
  58234. return MA_INVALID_ARGS;
  58235. }
  58236. return ma_job_queue_next(&pResourceManager->jobQueue, pJob);
  58237. }
  58238. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob)
  58239. {
  58240. ma_result result = MA_SUCCESS;
  58241. ma_resource_manager* pResourceManager;
  58242. ma_resource_manager_data_buffer_node* pDataBufferNode;
  58243. MA_ASSERT(pJob != NULL);
  58244. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.loadDataBufferNode.pResourceManager;
  58245. MA_ASSERT(pResourceManager != NULL);
  58246. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.loadDataBufferNode.pDataBufferNode;
  58247. MA_ASSERT(pDataBufferNode != NULL);
  58248. MA_ASSERT(pDataBufferNode->isDataOwnedByResourceManager == MA_TRUE); /* The data should always be owned by the resource manager. */
  58249. /* 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. */
  58250. if (pJob->order != ma_atomic_load_32(&pDataBufferNode->executionPointer)) {
  58251. 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. */
  58252. }
  58253. /* First thing we need to do is check whether or not the data buffer is getting deleted. If so we just abort. */
  58254. if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) != MA_BUSY) {
  58255. result = ma_resource_manager_data_buffer_node_result(pDataBufferNode); /* The data buffer may be getting deleted before it's even been loaded. */
  58256. goto done;
  58257. }
  58258. /*
  58259. We're ready to start loading. Essentially what we're doing here is initializing the data supply
  58260. of the node. Once this is complete, data buffers can have their connectors initialized which
  58261. will allow then to have audio data read from them.
  58262. Note that when the data supply type has been moved away from "unknown", that is when other threads
  58263. will determine that the node is available for data delivery and the data buffer connectors can be
  58264. initialized. Therefore, it's important that it is set after the data supply has been initialized.
  58265. */
  58266. if ((pJob->data.resourceManager.loadDataBufferNode.flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) != 0) {
  58267. /*
  58268. Decoding. This is the complex case because we're not going to be doing the entire decoding
  58269. process here. Instead it's going to be split of multiple jobs and loaded in pages. The
  58270. reason for this is to evenly distribute decoding time across multiple sounds, rather than
  58271. having one huge sound hog all the available processing resources.
  58272. The first thing we do is initialize a decoder. This is allocated on the heap and is passed
  58273. around to the paging jobs. When the last paging job has completed it's processing, it'll
  58274. free the decoder for us.
  58275. This job does not do any actual decoding. It instead just posts a PAGE_DATA_BUFFER_NODE job
  58276. which is where the actual decoding work will be done. However, once this job is complete,
  58277. the node will be in a state where data buffer connectors can be initialized.
  58278. */
  58279. ma_decoder* pDecoder; /* <-- Free'd on the last page decode. */
  58280. ma_job pageDataBufferNodeJob;
  58281. /* Allocate the decoder by initializing a decoded data supply. */
  58282. 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);
  58283. /*
  58284. Don't ever propagate an MA_BUSY result code or else the resource manager will think the
  58285. node is just busy decoding rather than in an error state. This should never happen, but
  58286. including this logic for safety just in case.
  58287. */
  58288. if (result == MA_BUSY) {
  58289. result = MA_ERROR;
  58290. }
  58291. if (result != MA_SUCCESS) {
  58292. if (pJob->data.resourceManager.loadDataBufferNode.pFilePath != NULL) {
  58293. 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));
  58294. } else {
  58295. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  58296. 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));
  58297. #endif
  58298. }
  58299. goto done;
  58300. }
  58301. /*
  58302. At this point the node's data supply is initialized and other threads can start initializing
  58303. their data buffer connectors. However, no data will actually be available until we start to
  58304. actually decode it. To do this, we need to post a paging job which is where the decoding
  58305. work is done.
  58306. Note that if an error occurred at an earlier point, this section will have been skipped.
  58307. */
  58308. pageDataBufferNodeJob = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE);
  58309. pageDataBufferNodeJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  58310. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pResourceManager = pResourceManager;
  58311. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDataBufferNode = pDataBufferNode;
  58312. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDecoder = pDecoder;
  58313. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneNotification = pJob->data.resourceManager.loadDataBufferNode.pDoneNotification;
  58314. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneFence = pJob->data.resourceManager.loadDataBufferNode.pDoneFence;
  58315. /* The job has been set up so it can now be posted. */
  58316. result = ma_resource_manager_post_job(pResourceManager, &pageDataBufferNodeJob);
  58317. /*
  58318. When we get here, we want to make sure the result code is set to MA_BUSY. The reason for
  58319. this is that the result will be copied over to the node's internal result variable. In
  58320. this case, since the decoding is still in-progress, we need to make sure the result code
  58321. is set to MA_BUSY.
  58322. */
  58323. if (result != MA_SUCCESS) {
  58324. 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));
  58325. ma_decoder_uninit(pDecoder);
  58326. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  58327. } else {
  58328. result = MA_BUSY;
  58329. }
  58330. } else {
  58331. /* No decoding. This is the simple case. We need only read the file content into memory and we're done. */
  58332. result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pJob->data.resourceManager.loadDataBufferNode.pFilePath, pJob->data.resourceManager.loadDataBufferNode.pFilePathW);
  58333. }
  58334. done:
  58335. /* File paths are no longer needed. */
  58336. ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePath, &pResourceManager->config.allocationCallbacks);
  58337. ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePathW, &pResourceManager->config.allocationCallbacks);
  58338. /*
  58339. 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
  58340. 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
  58341. 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
  58342. 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
  58343. other error code would cause the buffer to look like it's in a state that it's not.
  58344. */
  58345. ma_atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result);
  58346. /* At this point initialization is complete and we can signal the notification if any. */
  58347. if (pJob->data.resourceManager.loadDataBufferNode.pInitNotification != NULL) {
  58348. ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pInitNotification);
  58349. }
  58350. if (pJob->data.resourceManager.loadDataBufferNode.pInitFence != NULL) {
  58351. ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pInitFence);
  58352. }
  58353. /* If we have a success result it means we've fully loaded the buffer. This will happen in the non-decoding case. */
  58354. if (result != MA_BUSY) {
  58355. if (pJob->data.resourceManager.loadDataBufferNode.pDoneNotification != NULL) {
  58356. ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pDoneNotification);
  58357. }
  58358. if (pJob->data.resourceManager.loadDataBufferNode.pDoneFence != NULL) {
  58359. ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pDoneFence);
  58360. }
  58361. }
  58362. /* Increment the node's execution pointer so that the next jobs can be processed. This is how we keep decoding of pages in-order. */
  58363. ma_atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  58364. /* A busy result should be considered successful from the point of view of the job system. */
  58365. if (result == MA_BUSY) {
  58366. result = MA_SUCCESS;
  58367. }
  58368. return result;
  58369. }
  58370. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob)
  58371. {
  58372. ma_resource_manager* pResourceManager;
  58373. ma_resource_manager_data_buffer_node* pDataBufferNode;
  58374. MA_ASSERT(pJob != NULL);
  58375. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.freeDataBufferNode.pResourceManager;
  58376. MA_ASSERT(pResourceManager != NULL);
  58377. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.freeDataBufferNode.pDataBufferNode;
  58378. MA_ASSERT(pDataBufferNode != NULL);
  58379. if (pJob->order != ma_atomic_load_32(&pDataBufferNode->executionPointer)) {
  58380. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58381. }
  58382. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  58383. /* The event needs to be signalled last. */
  58384. if (pJob->data.resourceManager.freeDataBufferNode.pDoneNotification != NULL) {
  58385. ma_async_notification_signal(pJob->data.resourceManager.freeDataBufferNode.pDoneNotification);
  58386. }
  58387. if (pJob->data.resourceManager.freeDataBufferNode.pDoneFence != NULL) {
  58388. ma_fence_release(pJob->data.resourceManager.freeDataBufferNode.pDoneFence);
  58389. }
  58390. ma_atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  58391. return MA_SUCCESS;
  58392. }
  58393. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob)
  58394. {
  58395. ma_result result = MA_SUCCESS;
  58396. ma_resource_manager* pResourceManager;
  58397. ma_resource_manager_data_buffer_node* pDataBufferNode;
  58398. MA_ASSERT(pJob != NULL);
  58399. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.pageDataBufferNode.pResourceManager;
  58400. MA_ASSERT(pResourceManager != NULL);
  58401. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.pageDataBufferNode.pDataBufferNode;
  58402. MA_ASSERT(pDataBufferNode != NULL);
  58403. if (pJob->order != ma_atomic_load_32(&pDataBufferNode->executionPointer)) {
  58404. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58405. }
  58406. /* Don't do any more decoding if the data buffer has started the uninitialization process. */
  58407. result = ma_resource_manager_data_buffer_node_result(pDataBufferNode);
  58408. if (result != MA_BUSY) {
  58409. goto done;
  58410. }
  58411. /* We're ready to decode the next page. */
  58412. result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, (ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder);
  58413. /*
  58414. If we have a success code by this point, we want to post another job. We're going to set the
  58415. result back to MA_BUSY to make it clear that there's still more to load.
  58416. */
  58417. if (result == MA_SUCCESS) {
  58418. ma_job newJob;
  58419. newJob = *pJob; /* Everything is the same as the input job, except the execution order. */
  58420. newJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); /* We need a fresh execution order. */
  58421. result = ma_resource_manager_post_job(pResourceManager, &newJob);
  58422. /* Since the sound isn't yet fully decoded we want the status to be set to busy. */
  58423. if (result == MA_SUCCESS) {
  58424. result = MA_BUSY;
  58425. }
  58426. }
  58427. done:
  58428. /* If there's still more to decode the result will be set to MA_BUSY. Otherwise we can free the decoder. */
  58429. if (result != MA_BUSY) {
  58430. ma_decoder_uninit((ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder);
  58431. ma_free(pJob->data.resourceManager.pageDataBufferNode.pDecoder, &pResourceManager->config.allocationCallbacks);
  58432. }
  58433. /* If we reached the end we need to treat it as successful. */
  58434. if (result == MA_AT_END) {
  58435. result = MA_SUCCESS;
  58436. }
  58437. /* Make sure we set the result of node in case some error occurred. */
  58438. ma_atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result);
  58439. /* Signal the notification after setting the result in case the notification callback wants to inspect the result code. */
  58440. if (result != MA_BUSY) {
  58441. if (pJob->data.resourceManager.pageDataBufferNode.pDoneNotification != NULL) {
  58442. ma_async_notification_signal(pJob->data.resourceManager.pageDataBufferNode.pDoneNotification);
  58443. }
  58444. if (pJob->data.resourceManager.pageDataBufferNode.pDoneFence != NULL) {
  58445. ma_fence_release(pJob->data.resourceManager.pageDataBufferNode.pDoneFence);
  58446. }
  58447. }
  58448. ma_atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  58449. return result;
  58450. }
  58451. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob)
  58452. {
  58453. ma_result result = MA_SUCCESS;
  58454. ma_resource_manager* pResourceManager;
  58455. ma_resource_manager_data_buffer* pDataBuffer;
  58456. ma_resource_manager_data_supply_type dataSupplyType = ma_resource_manager_data_supply_type_unknown;
  58457. ma_bool32 isConnectorInitialized = MA_FALSE;
  58458. /*
  58459. All we're doing here is checking if the node has finished loading. If not, we just re-post the job
  58460. and keep waiting. Otherwise we increment the execution counter and set the buffer's result code.
  58461. */
  58462. MA_ASSERT(pJob != NULL);
  58463. pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.loadDataBuffer.pDataBuffer;
  58464. MA_ASSERT(pDataBuffer != NULL);
  58465. pResourceManager = pDataBuffer->pResourceManager;
  58466. if (pJob->order != ma_atomic_load_32(&pDataBuffer->executionPointer)) {
  58467. 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. */
  58468. }
  58469. /*
  58470. First thing we need to do is check whether or not the data buffer is getting deleted. If so we
  58471. just abort, but making sure we increment the execution pointer.
  58472. */
  58473. result = ma_resource_manager_data_buffer_result(pDataBuffer);
  58474. if (result != MA_BUSY) {
  58475. goto done; /* <-- This will ensure the exucution pointer is incremented. */
  58476. } else {
  58477. result = MA_SUCCESS; /* <-- Make sure this is reset. */
  58478. }
  58479. /* Try initializing the connector if we haven't already. */
  58480. isConnectorInitialized = ma_resource_manager_data_buffer_has_connector(pDataBuffer);
  58481. if (isConnectorInitialized == MA_FALSE) {
  58482. dataSupplyType = ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode);
  58483. if (dataSupplyType != ma_resource_manager_data_supply_type_unknown) {
  58484. /* We can now initialize the connector. If this fails, we need to abort. It's very rare for this to fail. */
  58485. ma_resource_manager_data_source_config dataSourceConfig; /* For setting initial looping state and range. */
  58486. dataSourceConfig = ma_resource_manager_data_source_config_init();
  58487. dataSourceConfig.rangeBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeBegInPCMFrames;
  58488. dataSourceConfig.rangeEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeEndInPCMFrames;
  58489. dataSourceConfig.loopPointBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames;
  58490. dataSourceConfig.loopPointEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames;
  58491. dataSourceConfig.isLooping = pJob->data.resourceManager.loadDataBuffer.isLooping;
  58492. result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, &dataSourceConfig, pJob->data.resourceManager.loadDataBuffer.pInitNotification, pJob->data.resourceManager.loadDataBuffer.pInitFence);
  58493. if (result != MA_SUCCESS) {
  58494. 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));
  58495. goto done;
  58496. }
  58497. } else {
  58498. /* 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. */
  58499. }
  58500. } else {
  58501. /* The connector is already initialized. Nothing to do here. */
  58502. }
  58503. /*
  58504. If the data node is still loading, we need to repost the job and *not* increment the execution
  58505. pointer (i.e. we need to not fall through to the "done" label).
  58506. There is a hole between here and the where the data connector is initialized where the data
  58507. buffer node may have finished initializing. We need to check for this by checking the result of
  58508. the data buffer node and whether or not we had an unknown data supply type at the time of
  58509. trying to initialize the data connector.
  58510. */
  58511. result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode);
  58512. if (result == MA_BUSY || (result == MA_SUCCESS && isConnectorInitialized == MA_FALSE && dataSupplyType == ma_resource_manager_data_supply_type_unknown)) {
  58513. return ma_resource_manager_post_job(pResourceManager, pJob);
  58514. }
  58515. done:
  58516. /* Only move away from a busy code so that we don't trash any existing error codes. */
  58517. ma_atomic_compare_and_swap_i32(&pDataBuffer->result, MA_BUSY, result);
  58518. /* Only signal the other threads after the result has been set just for cleanliness sake. */
  58519. if (pJob->data.resourceManager.loadDataBuffer.pDoneNotification != NULL) {
  58520. ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pDoneNotification);
  58521. }
  58522. if (pJob->data.resourceManager.loadDataBuffer.pDoneFence != NULL) {
  58523. ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pDoneFence);
  58524. }
  58525. /*
  58526. If at this point the data buffer has not had it's connector initialized, it means the
  58527. notification event was never signalled which means we need to signal it here.
  58528. */
  58529. if (ma_resource_manager_data_buffer_has_connector(pDataBuffer) == MA_FALSE && result != MA_SUCCESS) {
  58530. if (pJob->data.resourceManager.loadDataBuffer.pInitNotification != NULL) {
  58531. ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pInitNotification);
  58532. }
  58533. if (pJob->data.resourceManager.loadDataBuffer.pInitFence != NULL) {
  58534. ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pInitFence);
  58535. }
  58536. }
  58537. ma_atomic_fetch_add_32(&pDataBuffer->executionPointer, 1);
  58538. return result;
  58539. }
  58540. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob)
  58541. {
  58542. ma_resource_manager* pResourceManager;
  58543. ma_resource_manager_data_buffer* pDataBuffer;
  58544. MA_ASSERT(pJob != NULL);
  58545. pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.freeDataBuffer.pDataBuffer;
  58546. MA_ASSERT(pDataBuffer != NULL);
  58547. pResourceManager = pDataBuffer->pResourceManager;
  58548. if (pJob->order != ma_atomic_load_32(&pDataBuffer->executionPointer)) {
  58549. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58550. }
  58551. ma_resource_manager_data_buffer_uninit_internal(pDataBuffer);
  58552. /* The event needs to be signalled last. */
  58553. if (pJob->data.resourceManager.freeDataBuffer.pDoneNotification != NULL) {
  58554. ma_async_notification_signal(pJob->data.resourceManager.freeDataBuffer.pDoneNotification);
  58555. }
  58556. if (pJob->data.resourceManager.freeDataBuffer.pDoneFence != NULL) {
  58557. ma_fence_release(pJob->data.resourceManager.freeDataBuffer.pDoneFence);
  58558. }
  58559. ma_atomic_fetch_add_32(&pDataBuffer->executionPointer, 1);
  58560. return MA_SUCCESS;
  58561. }
  58562. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob)
  58563. {
  58564. ma_result result = MA_SUCCESS;
  58565. ma_decoder_config decoderConfig;
  58566. ma_uint32 pageBufferSizeInBytes;
  58567. ma_resource_manager* pResourceManager;
  58568. ma_resource_manager_data_stream* pDataStream;
  58569. MA_ASSERT(pJob != NULL);
  58570. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.loadDataStream.pDataStream;
  58571. MA_ASSERT(pDataStream != NULL);
  58572. pResourceManager = pDataStream->pResourceManager;
  58573. if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) {
  58574. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58575. }
  58576. if (ma_resource_manager_data_stream_result(pDataStream) != MA_BUSY) {
  58577. result = MA_INVALID_OPERATION; /* Most likely the data stream is being uninitialized. */
  58578. goto done;
  58579. }
  58580. /* We need to initialize the decoder first so we can determine the size of the pages. */
  58581. decoderConfig = ma_resource_manager__init_decoder_config(pResourceManager);
  58582. if (pJob->data.resourceManager.loadDataStream.pFilePath != NULL) {
  58583. result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePath, &decoderConfig, &pDataStream->decoder);
  58584. } else {
  58585. result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePathW, &decoderConfig, &pDataStream->decoder);
  58586. }
  58587. if (result != MA_SUCCESS) {
  58588. goto done;
  58589. }
  58590. /* Retrieve the total length of the file before marking the decoder as loaded. */
  58591. if ((pDataStream->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) {
  58592. result = ma_decoder_get_length_in_pcm_frames(&pDataStream->decoder, &pDataStream->totalLengthInPCMFrames);
  58593. if (result != MA_SUCCESS) {
  58594. goto done; /* Failed to retrieve the length. */
  58595. }
  58596. } else {
  58597. pDataStream->totalLengthInPCMFrames = 0;
  58598. }
  58599. /*
  58600. 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
  58601. and we don't want to have another thread trying to access the decoder while it's scanning.
  58602. */
  58603. pDataStream->isDecoderInitialized = MA_TRUE;
  58604. /* We have the decoder so we can now initialize our page buffer. */
  58605. pageBufferSizeInBytes = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream) * 2 * ma_get_bytes_per_frame(pDataStream->decoder.outputFormat, pDataStream->decoder.outputChannels);
  58606. pDataStream->pPageData = ma_malloc(pageBufferSizeInBytes, &pResourceManager->config.allocationCallbacks);
  58607. if (pDataStream->pPageData == NULL) {
  58608. ma_decoder_uninit(&pDataStream->decoder);
  58609. result = MA_OUT_OF_MEMORY;
  58610. goto done;
  58611. }
  58612. /* Seek to our initial seek point before filling the initial pages. */
  58613. ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.loadDataStream.initialSeekPoint);
  58614. /* We have our decoder and our page buffer, so now we need to fill our pages. */
  58615. ma_resource_manager_data_stream_fill_pages(pDataStream);
  58616. /* And now we're done. We want to make sure the result is MA_SUCCESS. */
  58617. result = MA_SUCCESS;
  58618. done:
  58619. ma_free(pJob->data.resourceManager.loadDataStream.pFilePath, &pResourceManager->config.allocationCallbacks);
  58620. ma_free(pJob->data.resourceManager.loadDataStream.pFilePathW, &pResourceManager->config.allocationCallbacks);
  58621. /* 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). */
  58622. ma_atomic_compare_and_swap_i32(&pDataStream->result, MA_BUSY, result);
  58623. /* Only signal the other threads after the result has been set just for cleanliness sake. */
  58624. if (pJob->data.resourceManager.loadDataStream.pInitNotification != NULL) {
  58625. ma_async_notification_signal(pJob->data.resourceManager.loadDataStream.pInitNotification);
  58626. }
  58627. if (pJob->data.resourceManager.loadDataStream.pInitFence != NULL) {
  58628. ma_fence_release(pJob->data.resourceManager.loadDataStream.pInitFence);
  58629. }
  58630. ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  58631. return result;
  58632. }
  58633. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob)
  58634. {
  58635. ma_resource_manager* pResourceManager;
  58636. ma_resource_manager_data_stream* pDataStream;
  58637. MA_ASSERT(pJob != NULL);
  58638. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.freeDataStream.pDataStream;
  58639. MA_ASSERT(pDataStream != NULL);
  58640. pResourceManager = pDataStream->pResourceManager;
  58641. if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) {
  58642. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58643. }
  58644. /* If our status is not MA_UNAVAILABLE we have a bug somewhere. */
  58645. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) == MA_UNAVAILABLE);
  58646. if (pDataStream->isDecoderInitialized) {
  58647. ma_decoder_uninit(&pDataStream->decoder);
  58648. }
  58649. if (pDataStream->pPageData != NULL) {
  58650. ma_free(pDataStream->pPageData, &pResourceManager->config.allocationCallbacks);
  58651. pDataStream->pPageData = NULL; /* Just in case... */
  58652. }
  58653. ma_data_source_uninit(&pDataStream->ds);
  58654. /* The event needs to be signalled last. */
  58655. if (pJob->data.resourceManager.freeDataStream.pDoneNotification != NULL) {
  58656. ma_async_notification_signal(pJob->data.resourceManager.freeDataStream.pDoneNotification);
  58657. }
  58658. if (pJob->data.resourceManager.freeDataStream.pDoneFence != NULL) {
  58659. ma_fence_release(pJob->data.resourceManager.freeDataStream.pDoneFence);
  58660. }
  58661. /*ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1);*/
  58662. return MA_SUCCESS;
  58663. }
  58664. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob)
  58665. {
  58666. ma_result result = MA_SUCCESS;
  58667. ma_resource_manager* pResourceManager;
  58668. ma_resource_manager_data_stream* pDataStream;
  58669. MA_ASSERT(pJob != NULL);
  58670. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.pageDataStream.pDataStream;
  58671. MA_ASSERT(pDataStream != NULL);
  58672. pResourceManager = pDataStream->pResourceManager;
  58673. if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) {
  58674. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58675. }
  58676. /* For streams, the status should be MA_SUCCESS. */
  58677. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  58678. result = MA_INVALID_OPERATION;
  58679. goto done;
  58680. }
  58681. ma_resource_manager_data_stream_fill_page(pDataStream, pJob->data.resourceManager.pageDataStream.pageIndex);
  58682. done:
  58683. ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  58684. return result;
  58685. }
  58686. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob)
  58687. {
  58688. ma_result result = MA_SUCCESS;
  58689. ma_resource_manager* pResourceManager;
  58690. ma_resource_manager_data_stream* pDataStream;
  58691. MA_ASSERT(pJob != NULL);
  58692. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.seekDataStream.pDataStream;
  58693. MA_ASSERT(pDataStream != NULL);
  58694. pResourceManager = pDataStream->pResourceManager;
  58695. if (pJob->order != ma_atomic_load_32(&pDataStream->executionPointer)) {
  58696. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  58697. }
  58698. /* For streams the status should be MA_SUCCESS for this to do anything. */
  58699. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS || pDataStream->isDecoderInitialized == MA_FALSE) {
  58700. result = MA_INVALID_OPERATION;
  58701. goto done;
  58702. }
  58703. /*
  58704. 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
  58705. instead of initializing the decoder, we seek to a frame.
  58706. */
  58707. ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.seekDataStream.frameIndex);
  58708. /* After seeking we'll need to reload the pages. */
  58709. ma_resource_manager_data_stream_fill_pages(pDataStream);
  58710. /* We need to let the public API know that we're done seeking. */
  58711. ma_atomic_fetch_sub_32(&pDataStream->seekCounter, 1);
  58712. done:
  58713. ma_atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  58714. return result;
  58715. }
  58716. MA_API ma_result ma_resource_manager_process_job(ma_resource_manager* pResourceManager, ma_job* pJob)
  58717. {
  58718. if (pResourceManager == NULL || pJob == NULL) {
  58719. return MA_INVALID_ARGS;
  58720. }
  58721. return ma_job_process(pJob);
  58722. }
  58723. MA_API ma_result ma_resource_manager_process_next_job(ma_resource_manager* pResourceManager)
  58724. {
  58725. ma_result result;
  58726. ma_job job;
  58727. if (pResourceManager == NULL) {
  58728. return MA_INVALID_ARGS;
  58729. }
  58730. /* This will return MA_CANCELLED if the next job is a quit job. */
  58731. result = ma_resource_manager_next_job(pResourceManager, &job);
  58732. if (result != MA_SUCCESS) {
  58733. return result;
  58734. }
  58735. return ma_job_process(&job);
  58736. }
  58737. #else
  58738. /* 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. */
  58739. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58740. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58741. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58742. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58743. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58744. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58745. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58746. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58747. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  58748. #endif /* MA_NO_RESOURCE_MANAGER */
  58749. #ifndef MA_NO_NODE_GRAPH
  58750. /* 10ms @ 48K = 480. Must never exceed 65535. */
  58751. #ifndef MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS
  58752. #define MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS 480
  58753. #endif
  58754. 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);
  58755. 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)
  58756. {
  58757. #ifndef MA_NO_GENERATION
  58758. {
  58759. ma_waveform_config waveformConfig;
  58760. ma_waveform waveform;
  58761. waveformConfig = ma_waveform_config_init(format, channels, sampleRate, ma_waveform_type_sine, 1.0, 400);
  58762. ma_waveform_init(&waveformConfig, &waveform);
  58763. ma_waveform_read_pcm_frames(&waveform, pFramesOut, frameCount, NULL);
  58764. }
  58765. #else
  58766. {
  58767. (void)pFramesOut;
  58768. (void)frameCount;
  58769. (void)format;
  58770. (void)channels;
  58771. (void)sampleRate;
  58772. #if defined(MA_DEBUG_OUTPUT)
  58773. {
  58774. #if _MSC_VER
  58775. #pragma message ("ma_debug_fill_pcm_frames_with_sine_wave() will do nothing because MA_NO_GENERATION is enabled.")
  58776. #endif
  58777. }
  58778. #endif
  58779. }
  58780. #endif
  58781. }
  58782. MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels)
  58783. {
  58784. ma_node_graph_config config;
  58785. MA_ZERO_OBJECT(&config);
  58786. config.channels = channels;
  58787. config.nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS;
  58788. return config;
  58789. }
  58790. static void ma_node_graph_set_is_reading(ma_node_graph* pNodeGraph, ma_bool32 isReading)
  58791. {
  58792. MA_ASSERT(pNodeGraph != NULL);
  58793. ma_atomic_exchange_32(&pNodeGraph->isReading, isReading);
  58794. }
  58795. #if 0
  58796. static ma_bool32 ma_node_graph_is_reading(ma_node_graph* pNodeGraph)
  58797. {
  58798. MA_ASSERT(pNodeGraph != NULL);
  58799. return ma_atomic_load_32(&pNodeGraph->isReading);
  58800. }
  58801. #endif
  58802. static void ma_node_graph_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58803. {
  58804. ma_node_graph* pNodeGraph = (ma_node_graph*)pNode;
  58805. ma_uint64 framesRead;
  58806. ma_node_graph_read_pcm_frames(pNodeGraph, ppFramesOut[0], *pFrameCountOut, &framesRead);
  58807. *pFrameCountOut = (ma_uint32)framesRead; /* Safe cast. */
  58808. (void)ppFramesIn;
  58809. (void)pFrameCountIn;
  58810. }
  58811. static ma_node_vtable g_node_graph_node_vtable =
  58812. {
  58813. ma_node_graph_node_process_pcm_frames,
  58814. NULL, /* onGetRequiredInputFrameCount */
  58815. 0, /* 0 input buses. */
  58816. 1, /* 1 output bus. */
  58817. 0 /* Flags. */
  58818. };
  58819. static void ma_node_graph_endpoint_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58820. {
  58821. MA_ASSERT(pNode != NULL);
  58822. MA_ASSERT(ma_node_get_input_bus_count(pNode) == 1);
  58823. MA_ASSERT(ma_node_get_output_bus_count(pNode) == 1);
  58824. /* Input channel count needs to be the same as the output channel count. */
  58825. MA_ASSERT(ma_node_get_input_channels(pNode, 0) == ma_node_get_output_channels(pNode, 0));
  58826. /* We don't need to do anything here because it's a passthrough. */
  58827. (void)pNode;
  58828. (void)ppFramesIn;
  58829. (void)pFrameCountIn;
  58830. (void)ppFramesOut;
  58831. (void)pFrameCountOut;
  58832. #if 0
  58833. /* The data has already been mixed. We just need to move it to the output buffer. */
  58834. if (ppFramesIn != NULL) {
  58835. ma_copy_pcm_frames(ppFramesOut[0], ppFramesIn[0], *pFrameCountOut, ma_format_f32, ma_node_get_output_channels(pNode, 0));
  58836. }
  58837. #endif
  58838. }
  58839. static ma_node_vtable g_node_graph_endpoint_vtable =
  58840. {
  58841. ma_node_graph_endpoint_process_pcm_frames,
  58842. NULL, /* onGetRequiredInputFrameCount */
  58843. 1, /* 1 input bus. */
  58844. 1, /* 1 output bus. */
  58845. MA_NODE_FLAG_PASSTHROUGH /* Flags. The endpoint is a passthrough. */
  58846. };
  58847. MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph)
  58848. {
  58849. ma_result result;
  58850. ma_node_config baseConfig;
  58851. ma_node_config endpointConfig;
  58852. if (pNodeGraph == NULL) {
  58853. return MA_INVALID_ARGS;
  58854. }
  58855. MA_ZERO_OBJECT(pNodeGraph);
  58856. pNodeGraph->nodeCacheCapInFrames = pConfig->nodeCacheCapInFrames;
  58857. if (pNodeGraph->nodeCacheCapInFrames == 0) {
  58858. pNodeGraph->nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS;
  58859. }
  58860. /* Base node so we can use the node graph as a node into another graph. */
  58861. baseConfig = ma_node_config_init();
  58862. baseConfig.vtable = &g_node_graph_node_vtable;
  58863. baseConfig.pOutputChannels = &pConfig->channels;
  58864. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pNodeGraph->base);
  58865. if (result != MA_SUCCESS) {
  58866. return result;
  58867. }
  58868. /* Endpoint. */
  58869. endpointConfig = ma_node_config_init();
  58870. endpointConfig.vtable = &g_node_graph_endpoint_vtable;
  58871. endpointConfig.pInputChannels = &pConfig->channels;
  58872. endpointConfig.pOutputChannels = &pConfig->channels;
  58873. result = ma_node_init(pNodeGraph, &endpointConfig, pAllocationCallbacks, &pNodeGraph->endpoint);
  58874. if (result != MA_SUCCESS) {
  58875. ma_node_uninit(&pNodeGraph->base, pAllocationCallbacks);
  58876. return result;
  58877. }
  58878. return MA_SUCCESS;
  58879. }
  58880. MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks)
  58881. {
  58882. if (pNodeGraph == NULL) {
  58883. return;
  58884. }
  58885. ma_node_uninit(&pNodeGraph->endpoint, pAllocationCallbacks);
  58886. }
  58887. MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph)
  58888. {
  58889. if (pNodeGraph == NULL) {
  58890. return NULL;
  58891. }
  58892. return &pNodeGraph->endpoint;
  58893. }
  58894. MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  58895. {
  58896. ma_result result = MA_SUCCESS;
  58897. ma_uint64 totalFramesRead;
  58898. ma_uint32 channels;
  58899. if (pFramesRead != NULL) {
  58900. *pFramesRead = 0; /* Safety. */
  58901. }
  58902. if (pNodeGraph == NULL) {
  58903. return MA_INVALID_ARGS;
  58904. }
  58905. channels = ma_node_get_output_channels(&pNodeGraph->endpoint, 0);
  58906. /* We'll be nice and try to do a full read of all frameCount frames. */
  58907. totalFramesRead = 0;
  58908. while (totalFramesRead < frameCount) {
  58909. ma_uint32 framesJustRead;
  58910. ma_uint64 framesToRead = frameCount - totalFramesRead;
  58911. if (framesToRead > 0xFFFFFFFF) {
  58912. framesToRead = 0xFFFFFFFF;
  58913. }
  58914. ma_node_graph_set_is_reading(pNodeGraph, MA_TRUE);
  58915. {
  58916. 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));
  58917. }
  58918. ma_node_graph_set_is_reading(pNodeGraph, MA_FALSE);
  58919. totalFramesRead += framesJustRead;
  58920. if (result != MA_SUCCESS) {
  58921. break;
  58922. }
  58923. /* Abort if we weren't able to read any frames or else we risk getting stuck in a loop. */
  58924. if (framesJustRead == 0) {
  58925. break;
  58926. }
  58927. }
  58928. /* 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. */
  58929. if (totalFramesRead < frameCount) {
  58930. ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, ma_format_f32, channels), (frameCount - totalFramesRead), ma_format_f32, channels);
  58931. }
  58932. if (pFramesRead != NULL) {
  58933. *pFramesRead = totalFramesRead;
  58934. }
  58935. return result;
  58936. }
  58937. MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph)
  58938. {
  58939. if (pNodeGraph == NULL) {
  58940. return 0;
  58941. }
  58942. return ma_node_get_output_channels(&pNodeGraph->endpoint, 0);
  58943. }
  58944. MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph)
  58945. {
  58946. if (pNodeGraph == NULL) {
  58947. return 0;
  58948. }
  58949. return ma_node_get_time(&pNodeGraph->endpoint); /* Global time is just the local time of the endpoint. */
  58950. }
  58951. MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime)
  58952. {
  58953. if (pNodeGraph == NULL) {
  58954. return MA_INVALID_ARGS;
  58955. }
  58956. return ma_node_set_time(&pNodeGraph->endpoint, globalTime); /* Global time is just the local time of the endpoint. */
  58957. }
  58958. #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. */
  58959. static ma_result ma_node_output_bus_init(ma_node* pNode, ma_uint32 outputBusIndex, ma_uint32 channels, ma_node_output_bus* pOutputBus)
  58960. {
  58961. MA_ASSERT(pOutputBus != NULL);
  58962. MA_ASSERT(outputBusIndex < MA_MAX_NODE_BUS_COUNT);
  58963. MA_ASSERT(outputBusIndex < ma_node_get_output_bus_count(pNode));
  58964. MA_ASSERT(channels < 256);
  58965. MA_ZERO_OBJECT(pOutputBus);
  58966. if (channels == 0) {
  58967. return MA_INVALID_ARGS;
  58968. }
  58969. pOutputBus->pNode = pNode;
  58970. pOutputBus->outputBusIndex = (ma_uint8)outputBusIndex;
  58971. pOutputBus->channels = (ma_uint8)channels;
  58972. pOutputBus->flags = MA_NODE_OUTPUT_BUS_FLAG_HAS_READ; /* <-- Important that this flag is set by default. */
  58973. pOutputBus->volume = 1;
  58974. return MA_SUCCESS;
  58975. }
  58976. static void ma_node_output_bus_lock(ma_node_output_bus* pOutputBus)
  58977. {
  58978. ma_spinlock_lock(&pOutputBus->lock);
  58979. }
  58980. static void ma_node_output_bus_unlock(ma_node_output_bus* pOutputBus)
  58981. {
  58982. ma_spinlock_unlock(&pOutputBus->lock);
  58983. }
  58984. static ma_uint32 ma_node_output_bus_get_channels(const ma_node_output_bus* pOutputBus)
  58985. {
  58986. return pOutputBus->channels;
  58987. }
  58988. static void ma_node_output_bus_set_has_read(ma_node_output_bus* pOutputBus, ma_bool32 hasRead)
  58989. {
  58990. if (hasRead) {
  58991. ma_atomic_fetch_or_32(&pOutputBus->flags, MA_NODE_OUTPUT_BUS_FLAG_HAS_READ);
  58992. } else {
  58993. ma_atomic_fetch_and_32(&pOutputBus->flags, (ma_uint32)~MA_NODE_OUTPUT_BUS_FLAG_HAS_READ);
  58994. }
  58995. }
  58996. static ma_bool32 ma_node_output_bus_has_read(ma_node_output_bus* pOutputBus)
  58997. {
  58998. return (ma_atomic_load_32(&pOutputBus->flags) & MA_NODE_OUTPUT_BUS_FLAG_HAS_READ) != 0;
  58999. }
  59000. static void ma_node_output_bus_set_is_attached(ma_node_output_bus* pOutputBus, ma_bool32 isAttached)
  59001. {
  59002. ma_atomic_exchange_32(&pOutputBus->isAttached, isAttached);
  59003. }
  59004. static ma_bool32 ma_node_output_bus_is_attached(ma_node_output_bus* pOutputBus)
  59005. {
  59006. return ma_atomic_load_32(&pOutputBus->isAttached);
  59007. }
  59008. static ma_result ma_node_output_bus_set_volume(ma_node_output_bus* pOutputBus, float volume)
  59009. {
  59010. MA_ASSERT(pOutputBus != NULL);
  59011. if (volume < 0.0f) {
  59012. volume = 0.0f;
  59013. }
  59014. ma_atomic_exchange_f32(&pOutputBus->volume, volume);
  59015. return MA_SUCCESS;
  59016. }
  59017. static float ma_node_output_bus_get_volume(const ma_node_output_bus* pOutputBus)
  59018. {
  59019. return ma_atomic_load_f32((float*)&pOutputBus->volume);
  59020. }
  59021. static ma_result ma_node_input_bus_init(ma_uint32 channels, ma_node_input_bus* pInputBus)
  59022. {
  59023. MA_ASSERT(pInputBus != NULL);
  59024. MA_ASSERT(channels < 256);
  59025. MA_ZERO_OBJECT(pInputBus);
  59026. if (channels == 0) {
  59027. return MA_INVALID_ARGS;
  59028. }
  59029. pInputBus->channels = (ma_uint8)channels;
  59030. return MA_SUCCESS;
  59031. }
  59032. static void ma_node_input_bus_lock(ma_node_input_bus* pInputBus)
  59033. {
  59034. MA_ASSERT(pInputBus != NULL);
  59035. ma_spinlock_lock(&pInputBus->lock);
  59036. }
  59037. static void ma_node_input_bus_unlock(ma_node_input_bus* pInputBus)
  59038. {
  59039. MA_ASSERT(pInputBus != NULL);
  59040. ma_spinlock_unlock(&pInputBus->lock);
  59041. }
  59042. static void ma_node_input_bus_next_begin(ma_node_input_bus* pInputBus)
  59043. {
  59044. ma_atomic_fetch_add_32(&pInputBus->nextCounter, 1);
  59045. }
  59046. static void ma_node_input_bus_next_end(ma_node_input_bus* pInputBus)
  59047. {
  59048. ma_atomic_fetch_sub_32(&pInputBus->nextCounter, 1);
  59049. }
  59050. static ma_uint32 ma_node_input_bus_get_next_counter(ma_node_input_bus* pInputBus)
  59051. {
  59052. return ma_atomic_load_32(&pInputBus->nextCounter);
  59053. }
  59054. static ma_uint32 ma_node_input_bus_get_channels(const ma_node_input_bus* pInputBus)
  59055. {
  59056. return pInputBus->channels;
  59057. }
  59058. static void ma_node_input_bus_detach__no_output_bus_lock(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  59059. {
  59060. MA_ASSERT(pInputBus != NULL);
  59061. MA_ASSERT(pOutputBus != NULL);
  59062. /*
  59063. Mark the output bus as detached first. This will prevent future iterations on the audio thread
  59064. from iterating this output bus.
  59065. */
  59066. ma_node_output_bus_set_is_attached(pOutputBus, MA_FALSE);
  59067. /*
  59068. We cannot use the output bus lock here since it'll be getting used at a higher level, but we do
  59069. still need to use the input bus lock since we'll be updating pointers on two different output
  59070. buses. The same rules apply here as the attaching case. Although we're using a lock here, we're
  59071. *not* using a lock when iterating over the list in the audio thread. We therefore need to craft
  59072. this in a way such that the iteration on the audio thread doesn't break.
  59073. The the first thing to do is swap out the "next" pointer of the previous output bus with the
  59074. new "next" output bus. This is the operation that matters for iteration on the audio thread.
  59075. After that, the previous pointer on the new "next" pointer needs to be updated, after which
  59076. point the linked list will be in a good state.
  59077. */
  59078. ma_node_input_bus_lock(pInputBus);
  59079. {
  59080. ma_node_output_bus* pOldPrev = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pPrev);
  59081. ma_node_output_bus* pOldNext = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pNext);
  59082. if (pOldPrev != NULL) {
  59083. ma_atomic_exchange_ptr(&pOldPrev->pNext, pOldNext); /* <-- This is where the output bus is detached from the list. */
  59084. }
  59085. if (pOldNext != NULL) {
  59086. ma_atomic_exchange_ptr(&pOldNext->pPrev, pOldPrev); /* <-- This is required for detachment. */
  59087. }
  59088. }
  59089. ma_node_input_bus_unlock(pInputBus);
  59090. /* At this point the output bus is detached and the linked list is completely unaware of it. Reset some data for safety. */
  59091. ma_atomic_exchange_ptr(&pOutputBus->pNext, NULL); /* Using atomic exchanges here, mainly for the benefit of analysis tools which don't always recognize spinlocks. */
  59092. ma_atomic_exchange_ptr(&pOutputBus->pPrev, NULL); /* As above. */
  59093. pOutputBus->pInputNode = NULL;
  59094. pOutputBus->inputNodeInputBusIndex = 0;
  59095. /*
  59096. For thread-safety reasons, we don't want to be returning from this straight away. We need to
  59097. wait for the audio thread to finish with the output bus. There's two things we need to wait
  59098. for. The first is the part that selects the next output bus in the list, and the other is the
  59099. part that reads from the output bus. Basically all we're doing is waiting for the input bus
  59100. to stop referencing the output bus.
  59101. We're doing this part last because we want the section above to run while the audio thread
  59102. is finishing up with the output bus, just for efficiency reasons. We marked the output bus as
  59103. detached right at the top of this function which is going to prevent the audio thread from
  59104. iterating the output bus again.
  59105. */
  59106. /* Part 1: Wait for the current iteration to complete. */
  59107. while (ma_node_input_bus_get_next_counter(pInputBus) > 0) {
  59108. ma_yield();
  59109. }
  59110. /* Part 2: Wait for any reads to complete. */
  59111. while (ma_atomic_load_32(&pOutputBus->refCount) > 0) {
  59112. ma_yield();
  59113. }
  59114. /*
  59115. At this point we're done detaching and we can be guaranteed that the audio thread is not going
  59116. to attempt to reference this output bus again (until attached again).
  59117. */
  59118. }
  59119. #if 0 /* Not used at the moment, but leaving here in case I need it later. */
  59120. static void ma_node_input_bus_detach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  59121. {
  59122. MA_ASSERT(pInputBus != NULL);
  59123. MA_ASSERT(pOutputBus != NULL);
  59124. ma_node_output_bus_lock(pOutputBus);
  59125. {
  59126. ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus);
  59127. }
  59128. ma_node_output_bus_unlock(pOutputBus);
  59129. }
  59130. #endif
  59131. static void ma_node_input_bus_attach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus, ma_node* pNewInputNode, ma_uint32 inputNodeInputBusIndex)
  59132. {
  59133. MA_ASSERT(pInputBus != NULL);
  59134. MA_ASSERT(pOutputBus != NULL);
  59135. ma_node_output_bus_lock(pOutputBus);
  59136. {
  59137. ma_node_output_bus* pOldInputNode = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pInputNode);
  59138. /* Detach from any existing attachment first if necessary. */
  59139. if (pOldInputNode != NULL) {
  59140. ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus);
  59141. }
  59142. /*
  59143. At this point we can be sure the output bus is not attached to anything. The linked list in the
  59144. old input bus has been updated so that pOutputBus will not get iterated again.
  59145. */
  59146. pOutputBus->pInputNode = pNewInputNode; /* No need for an atomic assignment here because modification of this variable always happens within a lock. */
  59147. pOutputBus->inputNodeInputBusIndex = (ma_uint8)inputNodeInputBusIndex;
  59148. /*
  59149. Now we need to attach the output bus to the linked list. This involves updating two pointers on
  59150. two different output buses so I'm going to go ahead and keep this simple and just use a lock.
  59151. There are ways to do this without a lock, but it's just too hard to maintain for it's value.
  59152. Although we're locking here, it's important to remember that we're *not* locking when iterating
  59153. and reading audio data since that'll be running on the audio thread. As a result we need to be
  59154. careful how we craft this so that we don't break iteration. What we're going to do is always
  59155. attach the new item so that it becomes the first item in the list. That way, as we're iterating
  59156. we won't break any links in the list and iteration will continue safely. The detaching case will
  59157. also be crafted in a way as to not break list iteration. It's important to remember to use
  59158. atomic exchanges here since no locking is happening on the audio thread during iteration.
  59159. */
  59160. ma_node_input_bus_lock(pInputBus);
  59161. {
  59162. ma_node_output_bus* pNewPrev = &pInputBus->head;
  59163. ma_node_output_bus* pNewNext = (ma_node_output_bus*)ma_atomic_load_ptr(&pInputBus->head.pNext);
  59164. /* Update the local output bus. */
  59165. ma_atomic_exchange_ptr(&pOutputBus->pPrev, pNewPrev);
  59166. ma_atomic_exchange_ptr(&pOutputBus->pNext, pNewNext);
  59167. /* Update the other output buses to point back to the local output bus. */
  59168. ma_atomic_exchange_ptr(&pInputBus->head.pNext, pOutputBus); /* <-- This is where the output bus is actually attached to the input bus. */
  59169. /* Do the previous pointer last. This is only used for detachment. */
  59170. if (pNewNext != NULL) {
  59171. ma_atomic_exchange_ptr(&pNewNext->pPrev, pOutputBus);
  59172. }
  59173. }
  59174. ma_node_input_bus_unlock(pInputBus);
  59175. /*
  59176. Mark the node as attached last. This is used to controlling whether or the output bus will be
  59177. iterated on the audio thread. Mainly required for detachment purposes.
  59178. */
  59179. ma_node_output_bus_set_is_attached(pOutputBus, MA_TRUE);
  59180. }
  59181. ma_node_output_bus_unlock(pOutputBus);
  59182. }
  59183. static ma_node_output_bus* ma_node_input_bus_next(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  59184. {
  59185. ma_node_output_bus* pNext;
  59186. MA_ASSERT(pInputBus != NULL);
  59187. if (pOutputBus == NULL) {
  59188. return NULL;
  59189. }
  59190. ma_node_input_bus_next_begin(pInputBus);
  59191. {
  59192. pNext = pOutputBus;
  59193. for (;;) {
  59194. pNext = (ma_node_output_bus*)ma_atomic_load_ptr(&pNext->pNext);
  59195. if (pNext == NULL) {
  59196. break; /* Reached the end. */
  59197. }
  59198. if (ma_node_output_bus_is_attached(pNext) == MA_FALSE) {
  59199. continue; /* The node is not attached. Keep checking. */
  59200. }
  59201. /* The next node has been selected. */
  59202. break;
  59203. }
  59204. /* We need to increment the reference count of the selected node. */
  59205. if (pNext != NULL) {
  59206. ma_atomic_fetch_add_32(&pNext->refCount, 1);
  59207. }
  59208. /* The previous node is no longer being referenced. */
  59209. ma_atomic_fetch_sub_32(&pOutputBus->refCount, 1);
  59210. }
  59211. ma_node_input_bus_next_end(pInputBus);
  59212. return pNext;
  59213. }
  59214. static ma_node_output_bus* ma_node_input_bus_first(ma_node_input_bus* pInputBus)
  59215. {
  59216. return ma_node_input_bus_next(pInputBus, &pInputBus->head);
  59217. }
  59218. 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)
  59219. {
  59220. ma_result result = MA_SUCCESS;
  59221. ma_node_output_bus* pOutputBus;
  59222. ma_node_output_bus* pFirst;
  59223. ma_uint32 inputChannels;
  59224. ma_bool32 doesOutputBufferHaveContent = MA_FALSE;
  59225. (void)pInputNode; /* Not currently used. */
  59226. /*
  59227. This will be called from the audio thread which means we can't be doing any locking. Basically,
  59228. this function will not perfom any locking, whereas attaching and detaching will, but crafted in
  59229. such a way that we don't need to perform any locking here. The important thing to remember is
  59230. to always iterate in a forward direction.
  59231. In order to process any data we need to first read from all input buses. That's where this
  59232. function comes in. This iterates over each of the attachments and accumulates/mixes them. We
  59233. also convert the channels to the nodes output channel count before mixing. We want to do this
  59234. channel conversion so that the caller of this function can invoke the processing callback
  59235. without having to do it themselves.
  59236. When we iterate over each of the attachments on the input bus, we need to read as much data as
  59237. we can from each of them so that we don't end up with holes between each of the attachments. To
  59238. do this, we need to read from each attachment in a loop and read as many frames as we can, up
  59239. to `frameCount`.
  59240. */
  59241. MA_ASSERT(pInputNode != NULL);
  59242. 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. */
  59243. *pFramesRead = 0; /* Safety. */
  59244. inputChannels = ma_node_input_bus_get_channels(pInputBus);
  59245. /*
  59246. We need to be careful with how we call ma_node_input_bus_first() and ma_node_input_bus_next(). They
  59247. are both critical to our lock-free thread-safety system. We can only call ma_node_input_bus_first()
  59248. once per iteration, however we have an optimization to checks whether or not it's the first item in
  59249. the list. We therefore need to store a pointer to the first item rather than repeatedly calling
  59250. ma_node_input_bus_first(). It's safe to keep hold of this pointer, so long as we don't dereference it
  59251. after calling ma_node_input_bus_next(), which we won't be.
  59252. */
  59253. pFirst = ma_node_input_bus_first(pInputBus);
  59254. if (pFirst == NULL) {
  59255. return MA_SUCCESS; /* No attachments. Read nothing. */
  59256. }
  59257. for (pOutputBus = pFirst; pOutputBus != NULL; pOutputBus = ma_node_input_bus_next(pInputBus, pOutputBus)) {
  59258. ma_uint32 framesProcessed = 0;
  59259. ma_bool32 isSilentOutput = MA_FALSE;
  59260. MA_ASSERT(pOutputBus->pNode != NULL);
  59261. MA_ASSERT(((ma_node_base*)pOutputBus->pNode)->vtable != NULL);
  59262. isSilentOutput = (((ma_node_base*)pOutputBus->pNode)->vtable->flags & MA_NODE_FLAG_SILENT_OUTPUT) != 0;
  59263. if (pFramesOut != NULL) {
  59264. /* Read. */
  59265. float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)];
  59266. ma_uint32 tempCapInFrames = ma_countof(temp) / inputChannels;
  59267. while (framesProcessed < frameCount) {
  59268. float* pRunningFramesOut;
  59269. ma_uint32 framesToRead;
  59270. ma_uint32 framesJustRead;
  59271. framesToRead = frameCount - framesProcessed;
  59272. if (framesToRead > tempCapInFrames) {
  59273. framesToRead = tempCapInFrames;
  59274. }
  59275. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(pFramesOut, framesProcessed, inputChannels);
  59276. if (doesOutputBufferHaveContent == MA_FALSE) {
  59277. /* Fast path. First attachment. We just read straight into the output buffer (no mixing required). */
  59278. result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, pRunningFramesOut, framesToRead, &framesJustRead, globalTime + framesProcessed);
  59279. } else {
  59280. /* Slow path. Not the first attachment. Mixing required. */
  59281. result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, temp, framesToRead, &framesJustRead, globalTime + framesProcessed);
  59282. if (result == MA_SUCCESS || result == MA_AT_END) {
  59283. if (isSilentOutput == MA_FALSE) { /* Don't mix if the node outputs silence. */
  59284. ma_mix_pcm_frames_f32(pRunningFramesOut, temp, framesJustRead, inputChannels, /*volume*/1);
  59285. }
  59286. }
  59287. }
  59288. framesProcessed += framesJustRead;
  59289. /* If we reached the end or otherwise failed to read any data we need to finish up with this output node. */
  59290. if (result != MA_SUCCESS) {
  59291. break;
  59292. }
  59293. /* If we didn't read anything, abort so we don't get stuck in a loop. */
  59294. if (framesJustRead == 0) {
  59295. break;
  59296. }
  59297. }
  59298. /* If it's the first attachment we didn't do any mixing. Any leftover samples need to be silenced. */
  59299. if (pOutputBus == pFirst && framesProcessed < frameCount) {
  59300. ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, framesProcessed, ma_format_f32, inputChannels), (frameCount - framesProcessed), ma_format_f32, inputChannels);
  59301. }
  59302. if (isSilentOutput == MA_FALSE) {
  59303. doesOutputBufferHaveContent = MA_TRUE;
  59304. }
  59305. } else {
  59306. /* Seek. */
  59307. ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, NULL, frameCount, &framesProcessed, globalTime);
  59308. }
  59309. }
  59310. /* If we didn't output anything, output silence. */
  59311. if (doesOutputBufferHaveContent == MA_FALSE && pFramesOut != NULL) {
  59312. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, inputChannels);
  59313. }
  59314. /* In this path we always "process" the entire amount. */
  59315. *pFramesRead = frameCount;
  59316. return result;
  59317. }
  59318. MA_API ma_node_config ma_node_config_init(void)
  59319. {
  59320. ma_node_config config;
  59321. MA_ZERO_OBJECT(&config);
  59322. config.initialState = ma_node_state_started; /* Nodes are started by default. */
  59323. config.inputBusCount = MA_NODE_BUS_COUNT_UNKNOWN;
  59324. config.outputBusCount = MA_NODE_BUS_COUNT_UNKNOWN;
  59325. return config;
  59326. }
  59327. static ma_result ma_node_detach_full(ma_node* pNode);
  59328. static float* ma_node_get_cached_input_ptr(ma_node* pNode, ma_uint32 inputBusIndex)
  59329. {
  59330. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59331. ma_uint32 iInputBus;
  59332. float* pBasePtr;
  59333. MA_ASSERT(pNodeBase != NULL);
  59334. /* Input data is stored at the front of the buffer. */
  59335. pBasePtr = pNodeBase->pCachedData;
  59336. for (iInputBus = 0; iInputBus < inputBusIndex; iInputBus += 1) {
  59337. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]);
  59338. }
  59339. return pBasePtr;
  59340. }
  59341. static float* ma_node_get_cached_output_ptr(ma_node* pNode, ma_uint32 outputBusIndex)
  59342. {
  59343. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59344. ma_uint32 iInputBus;
  59345. ma_uint32 iOutputBus;
  59346. float* pBasePtr;
  59347. MA_ASSERT(pNodeBase != NULL);
  59348. /* Cached output data starts after the input data. */
  59349. pBasePtr = pNodeBase->pCachedData;
  59350. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) {
  59351. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]);
  59352. }
  59353. for (iOutputBus = 0; iOutputBus < outputBusIndex; iOutputBus += 1) {
  59354. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iOutputBus]);
  59355. }
  59356. return pBasePtr;
  59357. }
  59358. typedef struct
  59359. {
  59360. size_t sizeInBytes;
  59361. size_t inputBusOffset;
  59362. size_t outputBusOffset;
  59363. size_t cachedDataOffset;
  59364. ma_uint32 inputBusCount; /* So it doesn't have to be calculated twice. */
  59365. ma_uint32 outputBusCount; /* So it doesn't have to be calculated twice. */
  59366. } ma_node_heap_layout;
  59367. static ma_result ma_node_translate_bus_counts(const ma_node_config* pConfig, ma_uint32* pInputBusCount, ma_uint32* pOutputBusCount)
  59368. {
  59369. ma_uint32 inputBusCount;
  59370. ma_uint32 outputBusCount;
  59371. MA_ASSERT(pConfig != NULL);
  59372. MA_ASSERT(pInputBusCount != NULL);
  59373. MA_ASSERT(pOutputBusCount != NULL);
  59374. /* 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. */
  59375. if (pConfig->vtable->inputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) {
  59376. inputBusCount = pConfig->inputBusCount;
  59377. } else {
  59378. inputBusCount = pConfig->vtable->inputBusCount;
  59379. if (pConfig->inputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->inputBusCount != pConfig->vtable->inputBusCount) {
  59380. return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */
  59381. }
  59382. }
  59383. if (pConfig->vtable->outputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) {
  59384. outputBusCount = pConfig->outputBusCount;
  59385. } else {
  59386. outputBusCount = pConfig->vtable->outputBusCount;
  59387. if (pConfig->outputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->outputBusCount != pConfig->vtable->outputBusCount) {
  59388. return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */
  59389. }
  59390. }
  59391. /* Bus counts must be within limits. */
  59392. if (inputBusCount > MA_MAX_NODE_BUS_COUNT || outputBusCount > MA_MAX_NODE_BUS_COUNT) {
  59393. return MA_INVALID_ARGS;
  59394. }
  59395. /* We must have channel counts for each bus. */
  59396. if ((inputBusCount > 0 && pConfig->pInputChannels == NULL) || (outputBusCount > 0 && pConfig->pOutputChannels == NULL)) {
  59397. return MA_INVALID_ARGS; /* You must specify channel counts for each input and output bus. */
  59398. }
  59399. /* Some special rules for passthrough nodes. */
  59400. if ((pConfig->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  59401. if ((pConfig->vtable->inputBusCount != 0 && pConfig->vtable->inputBusCount != 1) || pConfig->vtable->outputBusCount != 1) {
  59402. return MA_INVALID_ARGS; /* Passthrough nodes must have exactly 1 output bus and either 0 or 1 input bus. */
  59403. }
  59404. if (pConfig->pInputChannels[0] != pConfig->pOutputChannels[0]) {
  59405. return MA_INVALID_ARGS; /* Passthrough nodes must have the same number of channels between input and output nodes. */
  59406. }
  59407. }
  59408. *pInputBusCount = inputBusCount;
  59409. *pOutputBusCount = outputBusCount;
  59410. return MA_SUCCESS;
  59411. }
  59412. static ma_result ma_node_get_heap_layout(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, ma_node_heap_layout* pHeapLayout)
  59413. {
  59414. ma_result result;
  59415. ma_uint32 inputBusCount;
  59416. ma_uint32 outputBusCount;
  59417. MA_ASSERT(pHeapLayout != NULL);
  59418. MA_ZERO_OBJECT(pHeapLayout);
  59419. if (pConfig == NULL || pConfig->vtable == NULL || pConfig->vtable->onProcess == NULL) {
  59420. return MA_INVALID_ARGS;
  59421. }
  59422. result = ma_node_translate_bus_counts(pConfig, &inputBusCount, &outputBusCount);
  59423. if (result != MA_SUCCESS) {
  59424. return result;
  59425. }
  59426. pHeapLayout->sizeInBytes = 0;
  59427. /* Input buses. */
  59428. if (inputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) {
  59429. pHeapLayout->inputBusOffset = pHeapLayout->sizeInBytes;
  59430. pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_input_bus) * inputBusCount);
  59431. } else {
  59432. pHeapLayout->inputBusOffset = MA_SIZE_MAX; /* MA_SIZE_MAX indicates that no heap allocation is required for the input bus. */
  59433. }
  59434. /* Output buses. */
  59435. if (outputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) {
  59436. pHeapLayout->outputBusOffset = pHeapLayout->sizeInBytes;
  59437. pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_output_bus) * outputBusCount);
  59438. } else {
  59439. pHeapLayout->outputBusOffset = MA_SIZE_MAX;
  59440. }
  59441. /*
  59442. Cached audio data.
  59443. We need to allocate memory for a caching both input and output data. We have an optimization
  59444. where no caching is necessary for specific conditions:
  59445. - The node has 0 inputs and 1 output.
  59446. When a node meets the above conditions, no cache is allocated.
  59447. The size choice for this buffer is a little bit finicky. We don't want to be too wasteful by
  59448. allocating too much, but at the same time we want it be large enough so that enough frames can
  59449. be processed for each call to ma_node_read_pcm_frames() so that it keeps things efficient. For
  59450. now I'm going with 10ms @ 48K which is 480 frames per bus. This is configurable at compile
  59451. time. It might also be worth investigating whether or not this can be configured at run time.
  59452. */
  59453. if (inputBusCount == 0 && outputBusCount == 1) {
  59454. /* Fast path. No cache needed. */
  59455. pHeapLayout->cachedDataOffset = MA_SIZE_MAX;
  59456. } else {
  59457. /* Slow path. Cache needed. */
  59458. size_t cachedDataSizeInBytes = 0;
  59459. ma_uint32 iBus;
  59460. for (iBus = 0; iBus < inputBusCount; iBus += 1) {
  59461. cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pInputChannels[iBus]);
  59462. }
  59463. for (iBus = 0; iBus < outputBusCount; iBus += 1) {
  59464. cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pOutputChannels[iBus]);
  59465. }
  59466. pHeapLayout->cachedDataOffset = pHeapLayout->sizeInBytes;
  59467. pHeapLayout->sizeInBytes += ma_align_64(cachedDataSizeInBytes);
  59468. }
  59469. /*
  59470. Not technically part of the heap, but we can output the input and output bus counts so we can
  59471. avoid a redundant call to ma_node_translate_bus_counts().
  59472. */
  59473. pHeapLayout->inputBusCount = inputBusCount;
  59474. pHeapLayout->outputBusCount = outputBusCount;
  59475. /* Make sure allocation size is aligned. */
  59476. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  59477. return MA_SUCCESS;
  59478. }
  59479. MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes)
  59480. {
  59481. ma_result result;
  59482. ma_node_heap_layout heapLayout;
  59483. if (pHeapSizeInBytes == NULL) {
  59484. return MA_INVALID_ARGS;
  59485. }
  59486. *pHeapSizeInBytes = 0;
  59487. result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout);
  59488. if (result != MA_SUCCESS) {
  59489. return result;
  59490. }
  59491. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  59492. return MA_SUCCESS;
  59493. }
  59494. MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode)
  59495. {
  59496. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59497. ma_result result;
  59498. ma_node_heap_layout heapLayout;
  59499. ma_uint32 iInputBus;
  59500. ma_uint32 iOutputBus;
  59501. if (pNodeBase == NULL) {
  59502. return MA_INVALID_ARGS;
  59503. }
  59504. MA_ZERO_OBJECT(pNodeBase);
  59505. result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout);
  59506. if (result != MA_SUCCESS) {
  59507. return result;
  59508. }
  59509. pNodeBase->_pHeap = pHeap;
  59510. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  59511. pNodeBase->pNodeGraph = pNodeGraph;
  59512. pNodeBase->vtable = pConfig->vtable;
  59513. pNodeBase->state = pConfig->initialState;
  59514. pNodeBase->stateTimes[ma_node_state_started] = 0;
  59515. pNodeBase->stateTimes[ma_node_state_stopped] = (ma_uint64)(ma_int64)-1; /* Weird casting for VC6 compatibility. */
  59516. pNodeBase->inputBusCount = heapLayout.inputBusCount;
  59517. pNodeBase->outputBusCount = heapLayout.outputBusCount;
  59518. if (heapLayout.inputBusOffset != MA_SIZE_MAX) {
  59519. pNodeBase->pInputBuses = (ma_node_input_bus*)ma_offset_ptr(pHeap, heapLayout.inputBusOffset);
  59520. } else {
  59521. pNodeBase->pInputBuses = pNodeBase->_inputBuses;
  59522. }
  59523. if (heapLayout.outputBusOffset != MA_SIZE_MAX) {
  59524. pNodeBase->pOutputBuses = (ma_node_output_bus*)ma_offset_ptr(pHeap, heapLayout.outputBusOffset);
  59525. } else {
  59526. pNodeBase->pOutputBuses = pNodeBase->_outputBuses;
  59527. }
  59528. if (heapLayout.cachedDataOffset != MA_SIZE_MAX) {
  59529. pNodeBase->pCachedData = (float*)ma_offset_ptr(pHeap, heapLayout.cachedDataOffset);
  59530. pNodeBase->cachedDataCapInFramesPerBus = pNodeGraph->nodeCacheCapInFrames;
  59531. } else {
  59532. pNodeBase->pCachedData = NULL;
  59533. }
  59534. /* We need to run an initialization step for each input and output bus. */
  59535. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) {
  59536. result = ma_node_input_bus_init(pConfig->pInputChannels[iInputBus], &pNodeBase->pInputBuses[iInputBus]);
  59537. if (result != MA_SUCCESS) {
  59538. return result;
  59539. }
  59540. }
  59541. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) {
  59542. result = ma_node_output_bus_init(pNodeBase, iOutputBus, pConfig->pOutputChannels[iOutputBus], &pNodeBase->pOutputBuses[iOutputBus]);
  59543. if (result != MA_SUCCESS) {
  59544. return result;
  59545. }
  59546. }
  59547. /* The cached data needs to be initialized to silence (or a sine wave tone if we're debugging). */
  59548. if (pNodeBase->pCachedData != NULL) {
  59549. ma_uint32 iBus;
  59550. #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. */
  59551. /* For safety we'll go ahead and default the buffer to silence. */
  59552. for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) {
  59553. 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]));
  59554. }
  59555. for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) {
  59556. 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]));
  59557. }
  59558. #else
  59559. /* For debugging. Default to a sine wave. */
  59560. for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) {
  59561. 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);
  59562. }
  59563. for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) {
  59564. 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);
  59565. }
  59566. #endif
  59567. }
  59568. return MA_SUCCESS;
  59569. }
  59570. MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode)
  59571. {
  59572. ma_result result;
  59573. size_t heapSizeInBytes;
  59574. void* pHeap;
  59575. result = ma_node_get_heap_size(pNodeGraph, pConfig, &heapSizeInBytes);
  59576. if (result != MA_SUCCESS) {
  59577. return result;
  59578. }
  59579. if (heapSizeInBytes > 0) {
  59580. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  59581. if (pHeap == NULL) {
  59582. return MA_OUT_OF_MEMORY;
  59583. }
  59584. } else {
  59585. pHeap = NULL;
  59586. }
  59587. result = ma_node_init_preallocated(pNodeGraph, pConfig, pHeap, pNode);
  59588. if (result != MA_SUCCESS) {
  59589. ma_free(pHeap, pAllocationCallbacks);
  59590. return result;
  59591. }
  59592. ((ma_node_base*)pNode)->_ownsHeap = MA_TRUE;
  59593. return MA_SUCCESS;
  59594. }
  59595. MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  59596. {
  59597. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59598. if (pNodeBase == NULL) {
  59599. return;
  59600. }
  59601. /*
  59602. The first thing we need to do is fully detach the node. This will detach all inputs and
  59603. outputs. We need to do this first because it will sever the connection with the node graph and
  59604. allow us to complete uninitialization without needing to worry about thread-safety with the
  59605. audio thread. The detachment process will wait for any local processing of the node to finish.
  59606. */
  59607. ma_node_detach_full(pNode);
  59608. /*
  59609. At this point the node should be completely unreferenced by the node graph and we can finish up
  59610. the uninitialization process without needing to worry about thread-safety.
  59611. */
  59612. if (pNodeBase->_ownsHeap) {
  59613. ma_free(pNodeBase->_pHeap, pAllocationCallbacks);
  59614. }
  59615. }
  59616. MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode)
  59617. {
  59618. if (pNode == NULL) {
  59619. return NULL;
  59620. }
  59621. return ((const ma_node_base*)pNode)->pNodeGraph;
  59622. }
  59623. MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode)
  59624. {
  59625. if (pNode == NULL) {
  59626. return 0;
  59627. }
  59628. return ((ma_node_base*)pNode)->inputBusCount;
  59629. }
  59630. MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode)
  59631. {
  59632. if (pNode == NULL) {
  59633. return 0;
  59634. }
  59635. return ((ma_node_base*)pNode)->outputBusCount;
  59636. }
  59637. MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex)
  59638. {
  59639. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59640. if (pNode == NULL) {
  59641. return 0;
  59642. }
  59643. if (inputBusIndex >= ma_node_get_input_bus_count(pNode)) {
  59644. return 0; /* Invalid bus index. */
  59645. }
  59646. return ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[inputBusIndex]);
  59647. }
  59648. MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex)
  59649. {
  59650. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59651. if (pNode == NULL) {
  59652. return 0;
  59653. }
  59654. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59655. return 0; /* Invalid bus index. */
  59656. }
  59657. return ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[outputBusIndex]);
  59658. }
  59659. static ma_result ma_node_detach_full(ma_node* pNode)
  59660. {
  59661. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59662. ma_uint32 iInputBus;
  59663. if (pNodeBase == NULL) {
  59664. return MA_INVALID_ARGS;
  59665. }
  59666. /*
  59667. Make sure the node is completely detached first. This will not return until the output bus is
  59668. guaranteed to no longer be referenced by the audio thread.
  59669. */
  59670. ma_node_detach_all_output_buses(pNode);
  59671. /*
  59672. At this point all output buses will have been detached from the graph and we can be guaranteed
  59673. that none of it's input nodes will be getting processed by the graph. We can detach these
  59674. without needing to worry about the audio thread touching them.
  59675. */
  59676. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNode); iInputBus += 1) {
  59677. ma_node_input_bus* pInputBus;
  59678. ma_node_output_bus* pOutputBus;
  59679. pInputBus = &pNodeBase->pInputBuses[iInputBus];
  59680. /*
  59681. This is important. We cannot be using ma_node_input_bus_first() or ma_node_input_bus_next(). Those
  59682. functions are specifically for the audio thread. We'll instead just manually iterate using standard
  59683. linked list logic. We don't need to worry about the audio thread referencing these because the step
  59684. above severed the connection to the graph.
  59685. */
  59686. for (pOutputBus = (ma_node_output_bus*)ma_atomic_load_ptr(&pInputBus->head.pNext); pOutputBus != NULL; pOutputBus = (ma_node_output_bus*)ma_atomic_load_ptr(&pOutputBus->pNext)) {
  59687. ma_node_detach_output_bus(pOutputBus->pNode, pOutputBus->outputBusIndex); /* This won't do any waiting in practice and should be efficient. */
  59688. }
  59689. }
  59690. return MA_SUCCESS;
  59691. }
  59692. MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex)
  59693. {
  59694. ma_result result = MA_SUCCESS;
  59695. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59696. ma_node_base* pInputNodeBase;
  59697. if (pNode == NULL) {
  59698. return MA_INVALID_ARGS;
  59699. }
  59700. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59701. return MA_INVALID_ARGS; /* Invalid output bus index. */
  59702. }
  59703. /* We need to lock the output bus because we need to inspect the input node and grab it's input bus. */
  59704. ma_node_output_bus_lock(&pNodeBase->pOutputBuses[outputBusIndex]);
  59705. {
  59706. pInputNodeBase = (ma_node_base*)pNodeBase->pOutputBuses[outputBusIndex].pInputNode;
  59707. if (pInputNodeBase != NULL) {
  59708. ma_node_input_bus_detach__no_output_bus_lock(&pInputNodeBase->pInputBuses[pNodeBase->pOutputBuses[outputBusIndex].inputNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex]);
  59709. }
  59710. }
  59711. ma_node_output_bus_unlock(&pNodeBase->pOutputBuses[outputBusIndex]);
  59712. return result;
  59713. }
  59714. MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode)
  59715. {
  59716. ma_uint32 iOutputBus;
  59717. if (pNode == NULL) {
  59718. return MA_INVALID_ARGS;
  59719. }
  59720. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNode); iOutputBus += 1) {
  59721. ma_node_detach_output_bus(pNode, iOutputBus);
  59722. }
  59723. return MA_SUCCESS;
  59724. }
  59725. MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex)
  59726. {
  59727. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59728. ma_node_base* pOtherNodeBase = (ma_node_base*)pOtherNode;
  59729. if (pNodeBase == NULL || pOtherNodeBase == NULL) {
  59730. return MA_INVALID_ARGS;
  59731. }
  59732. if (pNodeBase == pOtherNodeBase) {
  59733. return MA_INVALID_OPERATION; /* Cannot attach a node to itself. */
  59734. }
  59735. if (outputBusIndex >= ma_node_get_output_bus_count(pNode) || otherNodeInputBusIndex >= ma_node_get_input_bus_count(pOtherNode)) {
  59736. return MA_INVALID_OPERATION; /* Invalid bus index. */
  59737. }
  59738. /* The output channel count of the output node must be the same as the input channel count of the input node. */
  59739. if (ma_node_get_output_channels(pNode, outputBusIndex) != ma_node_get_input_channels(pOtherNode, otherNodeInputBusIndex)) {
  59740. return MA_INVALID_OPERATION; /* Channel count is incompatible. */
  59741. }
  59742. /* This will deal with detaching if the output bus is already attached to something. */
  59743. ma_node_input_bus_attach(&pOtherNodeBase->pInputBuses[otherNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex], pOtherNode, otherNodeInputBusIndex);
  59744. return MA_SUCCESS;
  59745. }
  59746. MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume)
  59747. {
  59748. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59749. if (pNodeBase == NULL) {
  59750. return MA_INVALID_ARGS;
  59751. }
  59752. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59753. return MA_INVALID_ARGS; /* Invalid bus index. */
  59754. }
  59755. return ma_node_output_bus_set_volume(&pNodeBase->pOutputBuses[outputBusIndex], volume);
  59756. }
  59757. MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex)
  59758. {
  59759. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59760. if (pNodeBase == NULL) {
  59761. return 0;
  59762. }
  59763. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  59764. return 0; /* Invalid bus index. */
  59765. }
  59766. return ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]);
  59767. }
  59768. MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state)
  59769. {
  59770. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59771. if (pNodeBase == NULL) {
  59772. return MA_INVALID_ARGS;
  59773. }
  59774. ma_atomic_exchange_i32(&pNodeBase->state, state);
  59775. return MA_SUCCESS;
  59776. }
  59777. MA_API ma_node_state ma_node_get_state(const ma_node* pNode)
  59778. {
  59779. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  59780. if (pNodeBase == NULL) {
  59781. return ma_node_state_stopped;
  59782. }
  59783. return (ma_node_state)ma_atomic_load_i32(&pNodeBase->state);
  59784. }
  59785. MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime)
  59786. {
  59787. if (pNode == NULL) {
  59788. return MA_INVALID_ARGS;
  59789. }
  59790. /* Validation check for safety since we'll be using this as an index into stateTimes[]. */
  59791. if (state != ma_node_state_started && state != ma_node_state_stopped) {
  59792. return MA_INVALID_ARGS;
  59793. }
  59794. ma_atomic_exchange_64(&((ma_node_base*)pNode)->stateTimes[state], globalTime);
  59795. return MA_SUCCESS;
  59796. }
  59797. MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state)
  59798. {
  59799. if (pNode == NULL) {
  59800. return 0;
  59801. }
  59802. /* Validation check for safety since we'll be using this as an index into stateTimes[]. */
  59803. if (state != ma_node_state_started && state != ma_node_state_stopped) {
  59804. return 0;
  59805. }
  59806. return ma_atomic_load_64(&((ma_node_base*)pNode)->stateTimes[state]);
  59807. }
  59808. MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime)
  59809. {
  59810. if (pNode == NULL) {
  59811. return ma_node_state_stopped;
  59812. }
  59813. return ma_node_get_state_by_time_range(pNode, globalTime, globalTime);
  59814. }
  59815. MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd)
  59816. {
  59817. ma_node_state state;
  59818. if (pNode == NULL) {
  59819. return ma_node_state_stopped;
  59820. }
  59821. state = ma_node_get_state(pNode);
  59822. /* An explicitly stopped node is always stopped. */
  59823. if (state == ma_node_state_stopped) {
  59824. return ma_node_state_stopped;
  59825. }
  59826. /*
  59827. Getting here means the node is marked as started, but it may still not be truly started due to
  59828. it's start time not having been reached yet. Also, the stop time may have also been reached in
  59829. which case it'll be considered stopped.
  59830. */
  59831. if (ma_node_get_state_time(pNode, ma_node_state_started) > globalTimeBeg) {
  59832. return ma_node_state_stopped; /* Start time has not yet been reached. */
  59833. }
  59834. if (ma_node_get_state_time(pNode, ma_node_state_stopped) <= globalTimeEnd) {
  59835. return ma_node_state_stopped; /* Stop time has been reached. */
  59836. }
  59837. /* Getting here means the node is marked as started and is within it's start/stop times. */
  59838. return ma_node_state_started;
  59839. }
  59840. MA_API ma_uint64 ma_node_get_time(const ma_node* pNode)
  59841. {
  59842. if (pNode == NULL) {
  59843. return 0;
  59844. }
  59845. return ma_atomic_load_64(&((ma_node_base*)pNode)->localTime);
  59846. }
  59847. MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime)
  59848. {
  59849. if (pNode == NULL) {
  59850. return MA_INVALID_ARGS;
  59851. }
  59852. ma_atomic_exchange_64(&((ma_node_base*)pNode)->localTime, localTime);
  59853. return MA_SUCCESS;
  59854. }
  59855. static void ma_node_process_pcm_frames_internal(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59856. {
  59857. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59858. MA_ASSERT(pNode != NULL);
  59859. if (pNodeBase->vtable->onProcess) {
  59860. pNodeBase->vtable->onProcess(pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut);
  59861. }
  59862. }
  59863. 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)
  59864. {
  59865. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  59866. ma_result result = MA_SUCCESS;
  59867. ma_uint32 iInputBus;
  59868. ma_uint32 iOutputBus;
  59869. ma_uint32 inputBusCount;
  59870. ma_uint32 outputBusCount;
  59871. ma_uint32 totalFramesRead = 0;
  59872. float* ppFramesIn[MA_MAX_NODE_BUS_COUNT];
  59873. float* ppFramesOut[MA_MAX_NODE_BUS_COUNT];
  59874. ma_uint64 globalTimeBeg;
  59875. ma_uint64 globalTimeEnd;
  59876. ma_uint64 startTime;
  59877. ma_uint64 stopTime;
  59878. ma_uint32 timeOffsetBeg;
  59879. ma_uint32 timeOffsetEnd;
  59880. ma_uint32 frameCountIn;
  59881. ma_uint32 frameCountOut;
  59882. /*
  59883. pFramesRead is mandatory. It must be used to determine how many frames were read. It's normal and
  59884. expected that the number of frames read may be different to that requested. Therefore, the caller
  59885. must look at this value to correctly determine how many frames were read.
  59886. */
  59887. 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. */
  59888. if (pFramesRead == NULL) {
  59889. return MA_INVALID_ARGS;
  59890. }
  59891. *pFramesRead = 0; /* Safety. */
  59892. if (pNodeBase == NULL) {
  59893. return MA_INVALID_ARGS;
  59894. }
  59895. if (outputBusIndex >= ma_node_get_output_bus_count(pNodeBase)) {
  59896. return MA_INVALID_ARGS; /* Invalid output bus index. */
  59897. }
  59898. /* Don't do anything if we're in a stopped state. */
  59899. if (ma_node_get_state_by_time_range(pNode, globalTime, globalTime + frameCount) != ma_node_state_started) {
  59900. return MA_SUCCESS; /* We're in a stopped state. This is not an error - we just need to not read anything. */
  59901. }
  59902. globalTimeBeg = globalTime;
  59903. globalTimeEnd = globalTime + frameCount;
  59904. startTime = ma_node_get_state_time(pNode, ma_node_state_started);
  59905. stopTime = ma_node_get_state_time(pNode, ma_node_state_stopped);
  59906. /*
  59907. At this point we know that we are inside our start/stop times. However, we may need to adjust
  59908. our frame count and output pointer to accommodate since we could be straddling the time period
  59909. that this function is getting called for.
  59910. It's possible (and likely) that the start time does not line up with the output buffer. We
  59911. therefore need to offset it by a number of frames to accommodate. The same thing applies for
  59912. the stop time.
  59913. */
  59914. timeOffsetBeg = (globalTimeBeg < startTime) ? (ma_uint32)(globalTimeEnd - startTime) : 0;
  59915. timeOffsetEnd = (globalTimeEnd > stopTime) ? (ma_uint32)(globalTimeEnd - stopTime) : 0;
  59916. /* Trim based on the start offset. We need to silence the start of the buffer. */
  59917. if (timeOffsetBeg > 0) {
  59918. ma_silence_pcm_frames(pFramesOut, timeOffsetBeg, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex));
  59919. pFramesOut += timeOffsetBeg * ma_node_get_output_channels(pNode, outputBusIndex);
  59920. frameCount -= timeOffsetBeg;
  59921. }
  59922. /* 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. */
  59923. if (timeOffsetEnd > 0) {
  59924. frameCount -= timeOffsetEnd;
  59925. }
  59926. /* We run on different paths depending on the bus counts. */
  59927. inputBusCount = ma_node_get_input_bus_count(pNode);
  59928. outputBusCount = ma_node_get_output_bus_count(pNode);
  59929. /*
  59930. Run a simplified path when there are no inputs and one output. In this case there's nothing to
  59931. actually read and we can go straight to output. This is a very common scenario because the vast
  59932. majority of data source nodes will use this setup so this optimization I think is worthwhile.
  59933. */
  59934. if (inputBusCount == 0 && outputBusCount == 1) {
  59935. /* Fast path. No need to read from input and no need for any caching. */
  59936. frameCountIn = 0;
  59937. frameCountOut = frameCount; /* Just read as much as we can. The callback will return what was actually read. */
  59938. ppFramesOut[0] = pFramesOut;
  59939. /*
  59940. If it's a passthrough we won't be expecting the callback to output anything, so we'll
  59941. need to pre-silence the output buffer.
  59942. */
  59943. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  59944. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex));
  59945. }
  59946. ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut);
  59947. totalFramesRead = frameCountOut;
  59948. } else {
  59949. /* Slow path. Need to read input data. */
  59950. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  59951. /*
  59952. Fast path. We're running a passthrough. We need to read directly into the output buffer, but
  59953. still fire the callback so that event handling and trigger nodes can do their thing. Since
  59954. it's a passthrough there's no need for any kind of caching logic.
  59955. */
  59956. MA_ASSERT(outputBusCount == inputBusCount);
  59957. MA_ASSERT(outputBusCount == 1);
  59958. MA_ASSERT(outputBusIndex == 0);
  59959. /* We just read directly from input bus to output buffer, and then afterwards fire the callback. */
  59960. ppFramesOut[0] = pFramesOut;
  59961. ppFramesIn[0] = ppFramesOut[0];
  59962. result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[0], ppFramesIn[0], frameCount, &totalFramesRead, globalTime);
  59963. if (result == MA_SUCCESS) {
  59964. /* Even though it's a passthrough, we still need to fire the callback. */
  59965. frameCountIn = totalFramesRead;
  59966. frameCountOut = totalFramesRead;
  59967. if (totalFramesRead > 0) {
  59968. 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. */
  59969. }
  59970. /*
  59971. A passthrough should never have modified the input and output frame counts. If you're
  59972. triggering these assers you need to fix your processing callback.
  59973. */
  59974. MA_ASSERT(frameCountIn == totalFramesRead);
  59975. MA_ASSERT(frameCountOut == totalFramesRead);
  59976. }
  59977. } else {
  59978. /* Slow path. Need to do caching. */
  59979. ma_uint32 framesToProcessIn;
  59980. ma_uint32 framesToProcessOut;
  59981. ma_bool32 consumeNullInput = MA_FALSE;
  59982. /*
  59983. We use frameCount as a basis for the number of frames to read since that's what's being
  59984. requested, however we still need to clamp it to whatever can fit in the cache.
  59985. This will also be used as the basis for determining how many input frames to read. This is
  59986. not ideal because it can result in too many input frames being read which introduces latency.
  59987. To solve this, nodes can implement an optional callback called onGetRequiredInputFrameCount
  59988. which is used as hint to miniaudio as to how many input frames it needs to read at a time. This
  59989. callback is completely optional, and if it's not set, miniaudio will assume `frameCount`.
  59990. This function will be called multiple times for each period of time, once for each output node.
  59991. We cannot read from each input node each time this function is called. Instead we need to check
  59992. whether or not this is first output bus to be read from for this time period, and if so, read
  59993. from our input data.
  59994. To determine whether or not we're ready to read data, we check a flag. There will be one flag
  59995. for each output. When the flag is set, it means data has been read previously and that we're
  59996. ready to advance time forward for our input nodes by reading fresh data.
  59997. */
  59998. framesToProcessOut = frameCount;
  59999. if (framesToProcessOut > pNodeBase->cachedDataCapInFramesPerBus) {
  60000. framesToProcessOut = pNodeBase->cachedDataCapInFramesPerBus;
  60001. }
  60002. framesToProcessIn = frameCount;
  60003. if (pNodeBase->vtable->onGetRequiredInputFrameCount) {
  60004. pNodeBase->vtable->onGetRequiredInputFrameCount(pNode, framesToProcessOut, &framesToProcessIn); /* <-- It does not matter if this fails. */
  60005. }
  60006. if (framesToProcessIn > pNodeBase->cachedDataCapInFramesPerBus) {
  60007. framesToProcessIn = pNodeBase->cachedDataCapInFramesPerBus;
  60008. }
  60009. MA_ASSERT(framesToProcessIn <= 0xFFFF);
  60010. MA_ASSERT(framesToProcessOut <= 0xFFFF);
  60011. if (ma_node_output_bus_has_read(&pNodeBase->pOutputBuses[outputBusIndex])) {
  60012. /* Getting here means we need to do another round of processing. */
  60013. pNodeBase->cachedFrameCountOut = 0;
  60014. for (;;) {
  60015. frameCountOut = 0;
  60016. /*
  60017. We need to prepare our output frame pointers for processing. In the same iteration we need
  60018. to mark every output bus as unread so that future calls to this function for different buses
  60019. for the current time period don't pull in data when they should instead be reading from cache.
  60020. */
  60021. for (iOutputBus = 0; iOutputBus < outputBusCount; iOutputBus += 1) {
  60022. 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. */
  60023. ppFramesOut[iOutputBus] = ma_node_get_cached_output_ptr(pNode, iOutputBus);
  60024. }
  60025. /* We only need to read from input buses if there isn't already some data in the cache. */
  60026. if (pNodeBase->cachedFrameCountIn == 0) {
  60027. ma_uint32 maxFramesReadIn = 0;
  60028. /* Here is where we pull in data from the input buses. This is what will trigger an advance in time. */
  60029. for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) {
  60030. ma_uint32 framesRead;
  60031. /* The first thing to do is get the offset within our bulk allocation to store this input data. */
  60032. ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus);
  60033. /* 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. */
  60034. result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[iInputBus], ppFramesIn[iInputBus], framesToProcessIn, &framesRead, globalTime);
  60035. if (result != MA_SUCCESS) {
  60036. /* It doesn't really matter if we fail because we'll just fill with silence. */
  60037. framesRead = 0; /* Just for safety, but I don't think it's really needed. */
  60038. }
  60039. /* TODO: Minor optimization opportunity here. If no frames were read and the buffer is already filled with silence, no need to re-silence it. */
  60040. /* Any leftover frames need to silenced for safety. */
  60041. if (framesRead < framesToProcessIn) {
  60042. 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));
  60043. }
  60044. maxFramesReadIn = ma_max(maxFramesReadIn, framesRead);
  60045. }
  60046. /* This was a fresh load of input data so reset our consumption counter. */
  60047. pNodeBase->consumedFrameCountIn = 0;
  60048. /*
  60049. We don't want to keep processing if there's nothing to process, so set the number of cached
  60050. input frames to the maximum number we read from each attachment (the lesser will be padded
  60051. with silence). If we didn't read anything, this will be set to 0 and the entire buffer will
  60052. have been assigned to silence. This being equal to 0 is an important property for us because
  60053. it allows us to detect when NULL can be passed into the processing callback for the input
  60054. buffer for the purpose of continuous processing.
  60055. */
  60056. pNodeBase->cachedFrameCountIn = (ma_uint16)maxFramesReadIn;
  60057. } else {
  60058. /* We don't need to read anything, but we do need to prepare our input frame pointers. */
  60059. for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) {
  60060. ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus) + (pNodeBase->consumedFrameCountIn * ma_node_get_input_channels(pNodeBase, iInputBus));
  60061. }
  60062. }
  60063. /*
  60064. At this point we have our input data so now we need to do some processing. Sneaky little
  60065. optimization here - we can set the pointer to the output buffer for this output bus so
  60066. that the final copy into the output buffer is done directly by onProcess().
  60067. */
  60068. if (pFramesOut != NULL) {
  60069. ppFramesOut[outputBusIndex] = ma_offset_pcm_frames_ptr_f32(pFramesOut, pNodeBase->cachedFrameCountOut, ma_node_get_output_channels(pNode, outputBusIndex));
  60070. }
  60071. /* Give the processing function the entire capacity of the output buffer. */
  60072. frameCountOut = (framesToProcessOut - pNodeBase->cachedFrameCountOut);
  60073. /*
  60074. We need to treat nodes with continuous processing a little differently. For these ones,
  60075. we always want to fire the callback with the requested number of frames, regardless of
  60076. pNodeBase->cachedFrameCountIn, which could be 0. Also, we want to check if we can pass
  60077. in NULL for the input buffer to the callback.
  60078. */
  60079. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_CONTINUOUS_PROCESSING) != 0) {
  60080. /* We're using continuous processing. Make sure we specify the whole frame count at all times. */
  60081. frameCountIn = framesToProcessIn; /* Give the processing function as much input data as we've got in the buffer, including any silenced padding from short reads. */
  60082. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_ALLOW_NULL_INPUT) != 0 && pNodeBase->consumedFrameCountIn == 0 && pNodeBase->cachedFrameCountIn == 0) {
  60083. consumeNullInput = MA_TRUE;
  60084. } else {
  60085. consumeNullInput = MA_FALSE;
  60086. }
  60087. /*
  60088. Since we're using continuous processing we're always passing in a full frame count
  60089. regardless of how much input data was read. If this is greater than what we read as
  60090. input, we'll end up with an underflow. We instead need to make sure our cached frame
  60091. count is set to the number of frames we'll be passing to the data callback. Not
  60092. doing this will result in an underflow when we "consume" the cached data later on.
  60093. Note that this check needs to be done after the "consumeNullInput" check above because
  60094. we use the property of cachedFrameCountIn being 0 to determine whether or not we
  60095. should be passing in a null pointer to the processing callback for when the node is
  60096. configured with MA_NODE_FLAG_ALLOW_NULL_INPUT.
  60097. */
  60098. if (pNodeBase->cachedFrameCountIn < (ma_uint16)frameCountIn) {
  60099. pNodeBase->cachedFrameCountIn = (ma_uint16)frameCountIn;
  60100. }
  60101. } else {
  60102. frameCountIn = pNodeBase->cachedFrameCountIn; /* Give the processing function as much valid input data as we've got. */
  60103. consumeNullInput = MA_FALSE;
  60104. }
  60105. /*
  60106. Process data slightly differently depending on whether or not we're consuming NULL
  60107. input (checked just above).
  60108. */
  60109. if (consumeNullInput) {
  60110. ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut);
  60111. } else {
  60112. /*
  60113. We want to skip processing if there's no input data, but we can only do that safely if
  60114. we know that there is no chance of any output frames being produced. If continuous
  60115. processing is being used, this won't be a problem because the input frame count will
  60116. always be non-0. However, if continuous processing is *not* enabled and input and output
  60117. data is processed at different rates, we still need to process that last input frame
  60118. because there could be a few excess output frames needing to be produced from cached
  60119. data. The `MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES` flag is used as the indicator for
  60120. determining whether or not we need to process the node even when there are no input
  60121. frames available right now.
  60122. */
  60123. if (frameCountIn > 0 || (pNodeBase->vtable->flags & MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES) != 0) {
  60124. 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. */
  60125. } else {
  60126. frameCountOut = 0; /* No data was processed. */
  60127. }
  60128. }
  60129. /*
  60130. Thanks to our sneaky optimization above we don't need to do any data copying directly into
  60131. the output buffer - the onProcess() callback just did that for us. We do, however, need to
  60132. apply the number of input and output frames that were processed. Note that due to continuous
  60133. processing above, we need to do explicit checks here. If we just consumed a NULL input
  60134. buffer it means that no actual input data was processed from the internal buffers and we
  60135. don't want to be modifying any counters.
  60136. */
  60137. if (consumeNullInput == MA_FALSE) {
  60138. pNodeBase->consumedFrameCountIn += (ma_uint16)frameCountIn;
  60139. pNodeBase->cachedFrameCountIn -= (ma_uint16)frameCountIn;
  60140. }
  60141. /* The cached output frame count is always equal to what we just read. */
  60142. pNodeBase->cachedFrameCountOut += (ma_uint16)frameCountOut;
  60143. /* 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. */
  60144. if (pNodeBase->cachedFrameCountOut == framesToProcessOut || (frameCountOut == 0 && frameCountIn == 0)) {
  60145. break;
  60146. }
  60147. }
  60148. } else {
  60149. /*
  60150. We're not needing to read anything from the input buffer so just read directly from our
  60151. already-processed data.
  60152. */
  60153. if (pFramesOut != NULL) {
  60154. 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));
  60155. }
  60156. }
  60157. /* The number of frames read is always equal to the number of cached output frames. */
  60158. totalFramesRead = pNodeBase->cachedFrameCountOut;
  60159. /* Now that we've read the data, make sure our read flag is set. */
  60160. ma_node_output_bus_set_has_read(&pNodeBase->pOutputBuses[outputBusIndex], MA_TRUE);
  60161. }
  60162. }
  60163. /* Apply volume, if necessary. */
  60164. ma_apply_volume_factor_f32(pFramesOut, totalFramesRead * ma_node_get_output_channels(pNodeBase, outputBusIndex), ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]));
  60165. /* Advance our local time forward. */
  60166. ma_atomic_fetch_add_64(&pNodeBase->localTime, (ma_uint64)totalFramesRead);
  60167. *pFramesRead = totalFramesRead + timeOffsetBeg; /* Must include the silenced section at the start of the buffer. */
  60168. return result;
  60169. }
  60170. /* Data source node. */
  60171. MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource)
  60172. {
  60173. ma_data_source_node_config config;
  60174. MA_ZERO_OBJECT(&config);
  60175. config.nodeConfig = ma_node_config_init();
  60176. config.pDataSource = pDataSource;
  60177. return config;
  60178. }
  60179. static void ma_data_source_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60180. {
  60181. ma_data_source_node* pDataSourceNode = (ma_data_source_node*)pNode;
  60182. ma_format format;
  60183. ma_uint32 channels;
  60184. ma_uint32 frameCount;
  60185. ma_uint64 framesRead = 0;
  60186. MA_ASSERT(pDataSourceNode != NULL);
  60187. MA_ASSERT(pDataSourceNode->pDataSource != NULL);
  60188. MA_ASSERT(ma_node_get_input_bus_count(pDataSourceNode) == 0);
  60189. MA_ASSERT(ma_node_get_output_bus_count(pDataSourceNode) == 1);
  60190. /* We don't want to read from ppFramesIn at all. Instead we read from the data source. */
  60191. (void)ppFramesIn;
  60192. (void)pFrameCountIn;
  60193. frameCount = *pFrameCountOut;
  60194. /* miniaudio should never be calling this with a frame count of zero. */
  60195. MA_ASSERT(frameCount > 0);
  60196. if (ma_data_source_get_data_format(pDataSourceNode->pDataSource, &format, &channels, NULL, NULL, 0) == MA_SUCCESS) { /* <-- Don't care about sample rate here. */
  60197. /* The node graph system requires samples be in floating point format. This is checked in ma_data_source_node_init(). */
  60198. MA_ASSERT(format == ma_format_f32);
  60199. (void)format; /* Just to silence some static analysis tools. */
  60200. ma_data_source_read_pcm_frames(pDataSourceNode->pDataSource, ppFramesOut[0], frameCount, &framesRead);
  60201. }
  60202. *pFrameCountOut = (ma_uint32)framesRead;
  60203. }
  60204. static ma_node_vtable g_ma_data_source_node_vtable =
  60205. {
  60206. ma_data_source_node_process_pcm_frames,
  60207. NULL, /* onGetRequiredInputFrameCount */
  60208. 0, /* 0 input buses. */
  60209. 1, /* 1 output bus. */
  60210. 0
  60211. };
  60212. 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)
  60213. {
  60214. ma_result result;
  60215. ma_format format; /* For validating the format, which must be ma_format_f32. */
  60216. ma_uint32 channels; /* For specifying the channel count of the output bus. */
  60217. ma_node_config baseConfig;
  60218. if (pDataSourceNode == NULL) {
  60219. return MA_INVALID_ARGS;
  60220. }
  60221. MA_ZERO_OBJECT(pDataSourceNode);
  60222. if (pConfig == NULL) {
  60223. return MA_INVALID_ARGS;
  60224. }
  60225. 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. */
  60226. if (result != MA_SUCCESS) {
  60227. return result;
  60228. }
  60229. 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. */
  60230. if (format != ma_format_f32) {
  60231. return MA_INVALID_ARGS; /* Invalid format. */
  60232. }
  60233. /* The channel count is defined by the data source. If the caller has manually changed the channels we just ignore it. */
  60234. baseConfig = pConfig->nodeConfig;
  60235. baseConfig.vtable = &g_ma_data_source_node_vtable; /* Explicitly set the vtable here to prevent callers from setting it incorrectly. */
  60236. /*
  60237. The channel count is defined by the data source. It is invalid for the caller to manually set
  60238. the channel counts in the config. `ma_data_source_node_config_init()` will have defaulted the
  60239. channel count pointer to NULL which is how it must remain. If you trigger any of these asserts
  60240. it means you're explicitly setting the channel count. Instead, configure the output channel
  60241. count of your data source to be the necessary channel count.
  60242. */
  60243. if (baseConfig.pOutputChannels != NULL) {
  60244. return MA_INVALID_ARGS;
  60245. }
  60246. baseConfig.pOutputChannels = &channels;
  60247. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDataSourceNode->base);
  60248. if (result != MA_SUCCESS) {
  60249. return result;
  60250. }
  60251. pDataSourceNode->pDataSource = pConfig->pDataSource;
  60252. return MA_SUCCESS;
  60253. }
  60254. MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60255. {
  60256. ma_node_uninit(&pDataSourceNode->base, pAllocationCallbacks);
  60257. }
  60258. MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping)
  60259. {
  60260. if (pDataSourceNode == NULL) {
  60261. return MA_INVALID_ARGS;
  60262. }
  60263. return ma_data_source_set_looping(pDataSourceNode->pDataSource, isLooping);
  60264. }
  60265. MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode)
  60266. {
  60267. if (pDataSourceNode == NULL) {
  60268. return MA_FALSE;
  60269. }
  60270. return ma_data_source_is_looping(pDataSourceNode->pDataSource);
  60271. }
  60272. /* Splitter Node. */
  60273. MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels)
  60274. {
  60275. ma_splitter_node_config config;
  60276. MA_ZERO_OBJECT(&config);
  60277. config.nodeConfig = ma_node_config_init();
  60278. config.channels = channels;
  60279. config.outputBusCount = 2;
  60280. return config;
  60281. }
  60282. static void ma_splitter_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60283. {
  60284. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  60285. ma_uint32 iOutputBus;
  60286. ma_uint32 channels;
  60287. MA_ASSERT(pNodeBase != NULL);
  60288. MA_ASSERT(ma_node_get_input_bus_count(pNodeBase) == 1);
  60289. /* We don't need to consider the input frame count - it'll be the same as the output frame count and we process everything. */
  60290. (void)pFrameCountIn;
  60291. /* NOTE: This assumes the same number of channels for all inputs and outputs. This was checked in ma_splitter_node_init(). */
  60292. channels = ma_node_get_input_channels(pNodeBase, 0);
  60293. /* Splitting is just copying the first input bus and copying it over to each output bus. */
  60294. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) {
  60295. ma_copy_pcm_frames(ppFramesOut[iOutputBus], ppFramesIn[0], *pFrameCountOut, ma_format_f32, channels);
  60296. }
  60297. }
  60298. static ma_node_vtable g_ma_splitter_node_vtable =
  60299. {
  60300. ma_splitter_node_process_pcm_frames,
  60301. NULL, /* onGetRequiredInputFrameCount */
  60302. 1, /* 1 input bus. */
  60303. MA_NODE_BUS_COUNT_UNKNOWN, /* The output bus count is specified on a per-node basis. */
  60304. 0
  60305. };
  60306. 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)
  60307. {
  60308. ma_result result;
  60309. ma_node_config baseConfig;
  60310. ma_uint32 pInputChannels[1];
  60311. ma_uint32 pOutputChannels[MA_MAX_NODE_BUS_COUNT];
  60312. ma_uint32 iOutputBus;
  60313. if (pSplitterNode == NULL) {
  60314. return MA_INVALID_ARGS;
  60315. }
  60316. MA_ZERO_OBJECT(pSplitterNode);
  60317. if (pConfig == NULL) {
  60318. return MA_INVALID_ARGS;
  60319. }
  60320. if (pConfig->outputBusCount > MA_MAX_NODE_BUS_COUNT) {
  60321. return MA_INVALID_ARGS; /* Too many output buses. */
  60322. }
  60323. /* Splitters require the same number of channels between inputs and outputs. */
  60324. pInputChannels[0] = pConfig->channels;
  60325. for (iOutputBus = 0; iOutputBus < pConfig->outputBusCount; iOutputBus += 1) {
  60326. pOutputChannels[iOutputBus] = pConfig->channels;
  60327. }
  60328. baseConfig = pConfig->nodeConfig;
  60329. baseConfig.vtable = &g_ma_splitter_node_vtable;
  60330. baseConfig.pInputChannels = pInputChannels;
  60331. baseConfig.pOutputChannels = pOutputChannels;
  60332. baseConfig.outputBusCount = pConfig->outputBusCount;
  60333. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pSplitterNode->base);
  60334. if (result != MA_SUCCESS) {
  60335. return result; /* Failed to initialize the base node. */
  60336. }
  60337. return MA_SUCCESS;
  60338. }
  60339. MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60340. {
  60341. ma_node_uninit(pSplitterNode, pAllocationCallbacks);
  60342. }
  60343. /*
  60344. Biquad Node
  60345. */
  60346. 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)
  60347. {
  60348. ma_biquad_node_config config;
  60349. config.nodeConfig = ma_node_config_init();
  60350. config.biquad = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  60351. return config;
  60352. }
  60353. static void ma_biquad_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60354. {
  60355. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  60356. MA_ASSERT(pNode != NULL);
  60357. (void)pFrameCountIn;
  60358. ma_biquad_process_pcm_frames(&pLPFNode->biquad, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60359. }
  60360. static ma_node_vtable g_ma_biquad_node_vtable =
  60361. {
  60362. ma_biquad_node_process_pcm_frames,
  60363. NULL, /* onGetRequiredInputFrameCount */
  60364. 1, /* One input. */
  60365. 1, /* One output. */
  60366. 0 /* Default flags. */
  60367. };
  60368. 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)
  60369. {
  60370. ma_result result;
  60371. ma_node_config baseNodeConfig;
  60372. if (pNode == NULL) {
  60373. return MA_INVALID_ARGS;
  60374. }
  60375. MA_ZERO_OBJECT(pNode);
  60376. if (pConfig == NULL) {
  60377. return MA_INVALID_ARGS;
  60378. }
  60379. if (pConfig->biquad.format != ma_format_f32) {
  60380. return MA_INVALID_ARGS; /* The format must be f32. */
  60381. }
  60382. result = ma_biquad_init(&pConfig->biquad, pAllocationCallbacks, &pNode->biquad);
  60383. if (result != MA_SUCCESS) {
  60384. return result;
  60385. }
  60386. baseNodeConfig = ma_node_config_init();
  60387. baseNodeConfig.vtable = &g_ma_biquad_node_vtable;
  60388. baseNodeConfig.pInputChannels = &pConfig->biquad.channels;
  60389. baseNodeConfig.pOutputChannels = &pConfig->biquad.channels;
  60390. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60391. if (result != MA_SUCCESS) {
  60392. return result;
  60393. }
  60394. return result;
  60395. }
  60396. MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode)
  60397. {
  60398. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  60399. MA_ASSERT(pNode != NULL);
  60400. return ma_biquad_reinit(pConfig, &pLPFNode->biquad);
  60401. }
  60402. MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60403. {
  60404. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  60405. if (pNode == NULL) {
  60406. return;
  60407. }
  60408. ma_node_uninit(pNode, pAllocationCallbacks);
  60409. ma_biquad_uninit(&pLPFNode->biquad, pAllocationCallbacks);
  60410. }
  60411. /*
  60412. Low Pass Filter Node
  60413. */
  60414. MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  60415. {
  60416. ma_lpf_node_config config;
  60417. config.nodeConfig = ma_node_config_init();
  60418. config.lpf = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  60419. return config;
  60420. }
  60421. static void ma_lpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60422. {
  60423. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  60424. MA_ASSERT(pNode != NULL);
  60425. (void)pFrameCountIn;
  60426. ma_lpf_process_pcm_frames(&pLPFNode->lpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60427. }
  60428. static ma_node_vtable g_ma_lpf_node_vtable =
  60429. {
  60430. ma_lpf_node_process_pcm_frames,
  60431. NULL, /* onGetRequiredInputFrameCount */
  60432. 1, /* One input. */
  60433. 1, /* One output. */
  60434. 0 /* Default flags. */
  60435. };
  60436. 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)
  60437. {
  60438. ma_result result;
  60439. ma_node_config baseNodeConfig;
  60440. if (pNode == NULL) {
  60441. return MA_INVALID_ARGS;
  60442. }
  60443. MA_ZERO_OBJECT(pNode);
  60444. if (pConfig == NULL) {
  60445. return MA_INVALID_ARGS;
  60446. }
  60447. if (pConfig->lpf.format != ma_format_f32) {
  60448. return MA_INVALID_ARGS; /* The format must be f32. */
  60449. }
  60450. result = ma_lpf_init(&pConfig->lpf, pAllocationCallbacks, &pNode->lpf);
  60451. if (result != MA_SUCCESS) {
  60452. return result;
  60453. }
  60454. baseNodeConfig = ma_node_config_init();
  60455. baseNodeConfig.vtable = &g_ma_lpf_node_vtable;
  60456. baseNodeConfig.pInputChannels = &pConfig->lpf.channels;
  60457. baseNodeConfig.pOutputChannels = &pConfig->lpf.channels;
  60458. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60459. if (result != MA_SUCCESS) {
  60460. return result;
  60461. }
  60462. return result;
  60463. }
  60464. MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode)
  60465. {
  60466. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  60467. if (pNode == NULL) {
  60468. return MA_INVALID_ARGS;
  60469. }
  60470. return ma_lpf_reinit(pConfig, &pLPFNode->lpf);
  60471. }
  60472. MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60473. {
  60474. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  60475. if (pNode == NULL) {
  60476. return;
  60477. }
  60478. ma_node_uninit(pNode, pAllocationCallbacks);
  60479. ma_lpf_uninit(&pLPFNode->lpf, pAllocationCallbacks);
  60480. }
  60481. /*
  60482. High Pass Filter Node
  60483. */
  60484. MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  60485. {
  60486. ma_hpf_node_config config;
  60487. config.nodeConfig = ma_node_config_init();
  60488. config.hpf = ma_hpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  60489. return config;
  60490. }
  60491. static void ma_hpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60492. {
  60493. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  60494. MA_ASSERT(pNode != NULL);
  60495. (void)pFrameCountIn;
  60496. ma_hpf_process_pcm_frames(&pHPFNode->hpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60497. }
  60498. static ma_node_vtable g_ma_hpf_node_vtable =
  60499. {
  60500. ma_hpf_node_process_pcm_frames,
  60501. NULL, /* onGetRequiredInputFrameCount */
  60502. 1, /* One input. */
  60503. 1, /* One output. */
  60504. 0 /* Default flags. */
  60505. };
  60506. 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)
  60507. {
  60508. ma_result result;
  60509. ma_node_config baseNodeConfig;
  60510. if (pNode == NULL) {
  60511. return MA_INVALID_ARGS;
  60512. }
  60513. MA_ZERO_OBJECT(pNode);
  60514. if (pConfig == NULL) {
  60515. return MA_INVALID_ARGS;
  60516. }
  60517. if (pConfig->hpf.format != ma_format_f32) {
  60518. return MA_INVALID_ARGS; /* The format must be f32. */
  60519. }
  60520. result = ma_hpf_init(&pConfig->hpf, pAllocationCallbacks, &pNode->hpf);
  60521. if (result != MA_SUCCESS) {
  60522. return result;
  60523. }
  60524. baseNodeConfig = ma_node_config_init();
  60525. baseNodeConfig.vtable = &g_ma_hpf_node_vtable;
  60526. baseNodeConfig.pInputChannels = &pConfig->hpf.channels;
  60527. baseNodeConfig.pOutputChannels = &pConfig->hpf.channels;
  60528. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60529. if (result != MA_SUCCESS) {
  60530. return result;
  60531. }
  60532. return result;
  60533. }
  60534. MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode)
  60535. {
  60536. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  60537. if (pNode == NULL) {
  60538. return MA_INVALID_ARGS;
  60539. }
  60540. return ma_hpf_reinit(pConfig, &pHPFNode->hpf);
  60541. }
  60542. MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60543. {
  60544. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  60545. if (pNode == NULL) {
  60546. return;
  60547. }
  60548. ma_node_uninit(pNode, pAllocationCallbacks);
  60549. ma_hpf_uninit(&pHPFNode->hpf, pAllocationCallbacks);
  60550. }
  60551. /*
  60552. Band Pass Filter Node
  60553. */
  60554. MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  60555. {
  60556. ma_bpf_node_config config;
  60557. config.nodeConfig = ma_node_config_init();
  60558. config.bpf = ma_bpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  60559. return config;
  60560. }
  60561. static void ma_bpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60562. {
  60563. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  60564. MA_ASSERT(pNode != NULL);
  60565. (void)pFrameCountIn;
  60566. ma_bpf_process_pcm_frames(&pBPFNode->bpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60567. }
  60568. static ma_node_vtable g_ma_bpf_node_vtable =
  60569. {
  60570. ma_bpf_node_process_pcm_frames,
  60571. NULL, /* onGetRequiredInputFrameCount */
  60572. 1, /* One input. */
  60573. 1, /* One output. */
  60574. 0 /* Default flags. */
  60575. };
  60576. 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)
  60577. {
  60578. ma_result result;
  60579. ma_node_config baseNodeConfig;
  60580. if (pNode == NULL) {
  60581. return MA_INVALID_ARGS;
  60582. }
  60583. MA_ZERO_OBJECT(pNode);
  60584. if (pConfig == NULL) {
  60585. return MA_INVALID_ARGS;
  60586. }
  60587. if (pConfig->bpf.format != ma_format_f32) {
  60588. return MA_INVALID_ARGS; /* The format must be f32. */
  60589. }
  60590. result = ma_bpf_init(&pConfig->bpf, pAllocationCallbacks, &pNode->bpf);
  60591. if (result != MA_SUCCESS) {
  60592. return result;
  60593. }
  60594. baseNodeConfig = ma_node_config_init();
  60595. baseNodeConfig.vtable = &g_ma_bpf_node_vtable;
  60596. baseNodeConfig.pInputChannels = &pConfig->bpf.channels;
  60597. baseNodeConfig.pOutputChannels = &pConfig->bpf.channels;
  60598. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60599. if (result != MA_SUCCESS) {
  60600. return result;
  60601. }
  60602. return result;
  60603. }
  60604. MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode)
  60605. {
  60606. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  60607. if (pNode == NULL) {
  60608. return MA_INVALID_ARGS;
  60609. }
  60610. return ma_bpf_reinit(pConfig, &pBPFNode->bpf);
  60611. }
  60612. MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60613. {
  60614. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  60615. if (pNode == NULL) {
  60616. return;
  60617. }
  60618. ma_node_uninit(pNode, pAllocationCallbacks);
  60619. ma_bpf_uninit(&pBPFNode->bpf, pAllocationCallbacks);
  60620. }
  60621. /*
  60622. Notching Filter Node
  60623. */
  60624. MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
  60625. {
  60626. ma_notch_node_config config;
  60627. config.nodeConfig = ma_node_config_init();
  60628. config.notch = ma_notch2_config_init(ma_format_f32, channels, sampleRate, q, frequency);
  60629. return config;
  60630. }
  60631. static void ma_notch_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60632. {
  60633. ma_notch_node* pBPFNode = (ma_notch_node*)pNode;
  60634. MA_ASSERT(pNode != NULL);
  60635. (void)pFrameCountIn;
  60636. ma_notch2_process_pcm_frames(&pBPFNode->notch, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60637. }
  60638. static ma_node_vtable g_ma_notch_node_vtable =
  60639. {
  60640. ma_notch_node_process_pcm_frames,
  60641. NULL, /* onGetRequiredInputFrameCount */
  60642. 1, /* One input. */
  60643. 1, /* One output. */
  60644. 0 /* Default flags. */
  60645. };
  60646. 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)
  60647. {
  60648. ma_result result;
  60649. ma_node_config baseNodeConfig;
  60650. if (pNode == NULL) {
  60651. return MA_INVALID_ARGS;
  60652. }
  60653. MA_ZERO_OBJECT(pNode);
  60654. if (pConfig == NULL) {
  60655. return MA_INVALID_ARGS;
  60656. }
  60657. if (pConfig->notch.format != ma_format_f32) {
  60658. return MA_INVALID_ARGS; /* The format must be f32. */
  60659. }
  60660. result = ma_notch2_init(&pConfig->notch, pAllocationCallbacks, &pNode->notch);
  60661. if (result != MA_SUCCESS) {
  60662. return result;
  60663. }
  60664. baseNodeConfig = ma_node_config_init();
  60665. baseNodeConfig.vtable = &g_ma_notch_node_vtable;
  60666. baseNodeConfig.pInputChannels = &pConfig->notch.channels;
  60667. baseNodeConfig.pOutputChannels = &pConfig->notch.channels;
  60668. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60669. if (result != MA_SUCCESS) {
  60670. return result;
  60671. }
  60672. return result;
  60673. }
  60674. MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode)
  60675. {
  60676. ma_notch_node* pNotchNode = (ma_notch_node*)pNode;
  60677. if (pNode == NULL) {
  60678. return MA_INVALID_ARGS;
  60679. }
  60680. return ma_notch2_reinit(pConfig, &pNotchNode->notch);
  60681. }
  60682. MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60683. {
  60684. ma_notch_node* pNotchNode = (ma_notch_node*)pNode;
  60685. if (pNode == NULL) {
  60686. return;
  60687. }
  60688. ma_node_uninit(pNode, pAllocationCallbacks);
  60689. ma_notch2_uninit(&pNotchNode->notch, pAllocationCallbacks);
  60690. }
  60691. /*
  60692. Peaking Filter Node
  60693. */
  60694. MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  60695. {
  60696. ma_peak_node_config config;
  60697. config.nodeConfig = ma_node_config_init();
  60698. config.peak = ma_peak2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  60699. return config;
  60700. }
  60701. static void ma_peak_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60702. {
  60703. ma_peak_node* pBPFNode = (ma_peak_node*)pNode;
  60704. MA_ASSERT(pNode != NULL);
  60705. (void)pFrameCountIn;
  60706. ma_peak2_process_pcm_frames(&pBPFNode->peak, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60707. }
  60708. static ma_node_vtable g_ma_peak_node_vtable =
  60709. {
  60710. ma_peak_node_process_pcm_frames,
  60711. NULL, /* onGetRequiredInputFrameCount */
  60712. 1, /* One input. */
  60713. 1, /* One output. */
  60714. 0 /* Default flags. */
  60715. };
  60716. 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)
  60717. {
  60718. ma_result result;
  60719. ma_node_config baseNodeConfig;
  60720. if (pNode == NULL) {
  60721. return MA_INVALID_ARGS;
  60722. }
  60723. MA_ZERO_OBJECT(pNode);
  60724. if (pConfig == NULL) {
  60725. return MA_INVALID_ARGS;
  60726. }
  60727. if (pConfig->peak.format != ma_format_f32) {
  60728. return MA_INVALID_ARGS; /* The format must be f32. */
  60729. }
  60730. result = ma_peak2_init(&pConfig->peak, pAllocationCallbacks, &pNode->peak);
  60731. if (result != MA_SUCCESS) {
  60732. ma_node_uninit(pNode, pAllocationCallbacks);
  60733. return result;
  60734. }
  60735. baseNodeConfig = ma_node_config_init();
  60736. baseNodeConfig.vtable = &g_ma_peak_node_vtable;
  60737. baseNodeConfig.pInputChannels = &pConfig->peak.channels;
  60738. baseNodeConfig.pOutputChannels = &pConfig->peak.channels;
  60739. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60740. if (result != MA_SUCCESS) {
  60741. return result;
  60742. }
  60743. return result;
  60744. }
  60745. MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode)
  60746. {
  60747. ma_peak_node* pPeakNode = (ma_peak_node*)pNode;
  60748. if (pNode == NULL) {
  60749. return MA_INVALID_ARGS;
  60750. }
  60751. return ma_peak2_reinit(pConfig, &pPeakNode->peak);
  60752. }
  60753. MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60754. {
  60755. ma_peak_node* pPeakNode = (ma_peak_node*)pNode;
  60756. if (pNode == NULL) {
  60757. return;
  60758. }
  60759. ma_node_uninit(pNode, pAllocationCallbacks);
  60760. ma_peak2_uninit(&pPeakNode->peak, pAllocationCallbacks);
  60761. }
  60762. /*
  60763. Low Shelf Filter Node
  60764. */
  60765. MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  60766. {
  60767. ma_loshelf_node_config config;
  60768. config.nodeConfig = ma_node_config_init();
  60769. config.loshelf = ma_loshelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  60770. return config;
  60771. }
  60772. static void ma_loshelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60773. {
  60774. ma_loshelf_node* pBPFNode = (ma_loshelf_node*)pNode;
  60775. MA_ASSERT(pNode != NULL);
  60776. (void)pFrameCountIn;
  60777. ma_loshelf2_process_pcm_frames(&pBPFNode->loshelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60778. }
  60779. static ma_node_vtable g_ma_loshelf_node_vtable =
  60780. {
  60781. ma_loshelf_node_process_pcm_frames,
  60782. NULL, /* onGetRequiredInputFrameCount */
  60783. 1, /* One input. */
  60784. 1, /* One output. */
  60785. 0 /* Default flags. */
  60786. };
  60787. 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)
  60788. {
  60789. ma_result result;
  60790. ma_node_config baseNodeConfig;
  60791. if (pNode == NULL) {
  60792. return MA_INVALID_ARGS;
  60793. }
  60794. MA_ZERO_OBJECT(pNode);
  60795. if (pConfig == NULL) {
  60796. return MA_INVALID_ARGS;
  60797. }
  60798. if (pConfig->loshelf.format != ma_format_f32) {
  60799. return MA_INVALID_ARGS; /* The format must be f32. */
  60800. }
  60801. result = ma_loshelf2_init(&pConfig->loshelf, pAllocationCallbacks, &pNode->loshelf);
  60802. if (result != MA_SUCCESS) {
  60803. return result;
  60804. }
  60805. baseNodeConfig = ma_node_config_init();
  60806. baseNodeConfig.vtable = &g_ma_loshelf_node_vtable;
  60807. baseNodeConfig.pInputChannels = &pConfig->loshelf.channels;
  60808. baseNodeConfig.pOutputChannels = &pConfig->loshelf.channels;
  60809. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60810. if (result != MA_SUCCESS) {
  60811. return result;
  60812. }
  60813. return result;
  60814. }
  60815. MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode)
  60816. {
  60817. ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode;
  60818. if (pNode == NULL) {
  60819. return MA_INVALID_ARGS;
  60820. }
  60821. return ma_loshelf2_reinit(pConfig, &pLoshelfNode->loshelf);
  60822. }
  60823. MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60824. {
  60825. ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode;
  60826. if (pNode == NULL) {
  60827. return;
  60828. }
  60829. ma_node_uninit(pNode, pAllocationCallbacks);
  60830. ma_loshelf2_uninit(&pLoshelfNode->loshelf, pAllocationCallbacks);
  60831. }
  60832. /*
  60833. High Shelf Filter Node
  60834. */
  60835. MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  60836. {
  60837. ma_hishelf_node_config config;
  60838. config.nodeConfig = ma_node_config_init();
  60839. config.hishelf = ma_hishelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  60840. return config;
  60841. }
  60842. static void ma_hishelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60843. {
  60844. ma_hishelf_node* pBPFNode = (ma_hishelf_node*)pNode;
  60845. MA_ASSERT(pNode != NULL);
  60846. (void)pFrameCountIn;
  60847. ma_hishelf2_process_pcm_frames(&pBPFNode->hishelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60848. }
  60849. static ma_node_vtable g_ma_hishelf_node_vtable =
  60850. {
  60851. ma_hishelf_node_process_pcm_frames,
  60852. NULL, /* onGetRequiredInputFrameCount */
  60853. 1, /* One input. */
  60854. 1, /* One output. */
  60855. 0 /* Default flags. */
  60856. };
  60857. 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)
  60858. {
  60859. ma_result result;
  60860. ma_node_config baseNodeConfig;
  60861. if (pNode == NULL) {
  60862. return MA_INVALID_ARGS;
  60863. }
  60864. MA_ZERO_OBJECT(pNode);
  60865. if (pConfig == NULL) {
  60866. return MA_INVALID_ARGS;
  60867. }
  60868. if (pConfig->hishelf.format != ma_format_f32) {
  60869. return MA_INVALID_ARGS; /* The format must be f32. */
  60870. }
  60871. result = ma_hishelf2_init(&pConfig->hishelf, pAllocationCallbacks, &pNode->hishelf);
  60872. if (result != MA_SUCCESS) {
  60873. return result;
  60874. }
  60875. baseNodeConfig = ma_node_config_init();
  60876. baseNodeConfig.vtable = &g_ma_hishelf_node_vtable;
  60877. baseNodeConfig.pInputChannels = &pConfig->hishelf.channels;
  60878. baseNodeConfig.pOutputChannels = &pConfig->hishelf.channels;
  60879. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  60880. if (result != MA_SUCCESS) {
  60881. return result;
  60882. }
  60883. return result;
  60884. }
  60885. MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode)
  60886. {
  60887. ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode;
  60888. if (pNode == NULL) {
  60889. return MA_INVALID_ARGS;
  60890. }
  60891. return ma_hishelf2_reinit(pConfig, &pHishelfNode->hishelf);
  60892. }
  60893. MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60894. {
  60895. ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode;
  60896. if (pNode == NULL) {
  60897. return;
  60898. }
  60899. ma_node_uninit(pNode, pAllocationCallbacks);
  60900. ma_hishelf2_uninit(&pHishelfNode->hishelf, pAllocationCallbacks);
  60901. }
  60902. MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay)
  60903. {
  60904. ma_delay_node_config config;
  60905. config.nodeConfig = ma_node_config_init();
  60906. config.delay = ma_delay_config_init(channels, sampleRate, delayInFrames, decay);
  60907. return config;
  60908. }
  60909. static void ma_delay_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  60910. {
  60911. ma_delay_node* pDelayNode = (ma_delay_node*)pNode;
  60912. (void)pFrameCountIn;
  60913. ma_delay_process_pcm_frames(&pDelayNode->delay, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  60914. }
  60915. static ma_node_vtable g_ma_delay_node_vtable =
  60916. {
  60917. ma_delay_node_process_pcm_frames,
  60918. NULL,
  60919. 1, /* 1 input channels. */
  60920. 1, /* 1 output channel. */
  60921. MA_NODE_FLAG_CONTINUOUS_PROCESSING /* Delay requires continuous processing to ensure the tail get's processed. */
  60922. };
  60923. 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)
  60924. {
  60925. ma_result result;
  60926. ma_node_config baseConfig;
  60927. if (pDelayNode == NULL) {
  60928. return MA_INVALID_ARGS;
  60929. }
  60930. MA_ZERO_OBJECT(pDelayNode);
  60931. result = ma_delay_init(&pConfig->delay, pAllocationCallbacks, &pDelayNode->delay);
  60932. if (result != MA_SUCCESS) {
  60933. return result;
  60934. }
  60935. baseConfig = pConfig->nodeConfig;
  60936. baseConfig.vtable = &g_ma_delay_node_vtable;
  60937. baseConfig.pInputChannels = &pConfig->delay.channels;
  60938. baseConfig.pOutputChannels = &pConfig->delay.channels;
  60939. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDelayNode->baseNode);
  60940. if (result != MA_SUCCESS) {
  60941. ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks);
  60942. return result;
  60943. }
  60944. return result;
  60945. }
  60946. MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks)
  60947. {
  60948. if (pDelayNode == NULL) {
  60949. return;
  60950. }
  60951. /* The base node is always uninitialized first. */
  60952. ma_node_uninit(pDelayNode, pAllocationCallbacks);
  60953. ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks);
  60954. }
  60955. MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value)
  60956. {
  60957. if (pDelayNode == NULL) {
  60958. return;
  60959. }
  60960. ma_delay_set_wet(&pDelayNode->delay, value);
  60961. }
  60962. MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode)
  60963. {
  60964. if (pDelayNode == NULL) {
  60965. return 0;
  60966. }
  60967. return ma_delay_get_wet(&pDelayNode->delay);
  60968. }
  60969. MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value)
  60970. {
  60971. if (pDelayNode == NULL) {
  60972. return;
  60973. }
  60974. ma_delay_set_dry(&pDelayNode->delay, value);
  60975. }
  60976. MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode)
  60977. {
  60978. if (pDelayNode == NULL) {
  60979. return 0;
  60980. }
  60981. return ma_delay_get_dry(&pDelayNode->delay);
  60982. }
  60983. MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value)
  60984. {
  60985. if (pDelayNode == NULL) {
  60986. return;
  60987. }
  60988. ma_delay_set_decay(&pDelayNode->delay, value);
  60989. }
  60990. MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode)
  60991. {
  60992. if (pDelayNode == NULL) {
  60993. return 0;
  60994. }
  60995. return ma_delay_get_decay(&pDelayNode->delay);
  60996. }
  60997. #endif /* MA_NO_NODE_GRAPH */
  60998. /* SECTION: miniaudio_engine.c */
  60999. #if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH)
  61000. /**************************************************************************************************************************************************************
  61001. Engine
  61002. **************************************************************************************************************************************************************/
  61003. #define MA_SEEK_TARGET_NONE (~(ma_uint64)0)
  61004. static void ma_sound_set_at_end(ma_sound* pSound, ma_bool32 atEnd)
  61005. {
  61006. MA_ASSERT(pSound != NULL);
  61007. ma_atomic_exchange_32(&pSound->atEnd, atEnd);
  61008. /* Fire any callbacks or events. */
  61009. if (atEnd) {
  61010. if (pSound->endCallback != NULL) {
  61011. pSound->endCallback(pSound->pEndCallbackUserData, pSound);
  61012. }
  61013. }
  61014. }
  61015. static ma_bool32 ma_sound_get_at_end(const ma_sound* pSound)
  61016. {
  61017. MA_ASSERT(pSound != NULL);
  61018. return ma_atomic_load_32(&pSound->atEnd);
  61019. }
  61020. MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags)
  61021. {
  61022. ma_engine_node_config config;
  61023. MA_ZERO_OBJECT(&config);
  61024. config.pEngine = pEngine;
  61025. config.type = type;
  61026. config.isPitchDisabled = (flags & MA_SOUND_FLAG_NO_PITCH) != 0;
  61027. config.isSpatializationDisabled = (flags & MA_SOUND_FLAG_NO_SPATIALIZATION) != 0;
  61028. config.monoExpansionMode = pEngine->monoExpansionMode;
  61029. return config;
  61030. }
  61031. static void ma_engine_node_update_pitch_if_required(ma_engine_node* pEngineNode)
  61032. {
  61033. ma_bool32 isUpdateRequired = MA_FALSE;
  61034. float newPitch;
  61035. MA_ASSERT(pEngineNode != NULL);
  61036. newPitch = ma_atomic_load_explicit_f32(&pEngineNode->pitch, ma_atomic_memory_order_acquire);
  61037. if (pEngineNode->oldPitch != newPitch) {
  61038. pEngineNode->oldPitch = newPitch;
  61039. isUpdateRequired = MA_TRUE;
  61040. }
  61041. if (pEngineNode->oldDopplerPitch != pEngineNode->spatializer.dopplerPitch) {
  61042. pEngineNode->oldDopplerPitch = pEngineNode->spatializer.dopplerPitch;
  61043. isUpdateRequired = MA_TRUE;
  61044. }
  61045. if (isUpdateRequired) {
  61046. float basePitch = (float)pEngineNode->sampleRate / ma_engine_get_sample_rate(pEngineNode->pEngine);
  61047. ma_linear_resampler_set_rate_ratio(&pEngineNode->resampler, basePitch * pEngineNode->oldPitch * pEngineNode->oldDopplerPitch);
  61048. }
  61049. }
  61050. static ma_bool32 ma_engine_node_is_pitching_enabled(const ma_engine_node* pEngineNode)
  61051. {
  61052. MA_ASSERT(pEngineNode != NULL);
  61053. /* Don't try to be clever by skiping resampling in the pitch=1 case or else you'll glitch when moving away from 1. */
  61054. return !ma_atomic_load_explicit_32(&pEngineNode->isPitchDisabled, ma_atomic_memory_order_acquire);
  61055. }
  61056. static ma_bool32 ma_engine_node_is_spatialization_enabled(const ma_engine_node* pEngineNode)
  61057. {
  61058. MA_ASSERT(pEngineNode != NULL);
  61059. return !ma_atomic_load_explicit_32(&pEngineNode->isSpatializationDisabled, ma_atomic_memory_order_acquire);
  61060. }
  61061. static ma_uint64 ma_engine_node_get_required_input_frame_count(const ma_engine_node* pEngineNode, ma_uint64 outputFrameCount)
  61062. {
  61063. ma_uint64 inputFrameCount = 0;
  61064. if (ma_engine_node_is_pitching_enabled(pEngineNode)) {
  61065. ma_result result = ma_linear_resampler_get_required_input_frame_count(&pEngineNode->resampler, outputFrameCount, &inputFrameCount);
  61066. if (result != MA_SUCCESS) {
  61067. inputFrameCount = 0;
  61068. }
  61069. } else {
  61070. inputFrameCount = outputFrameCount; /* No resampling, so 1:1. */
  61071. }
  61072. return inputFrameCount;
  61073. }
  61074. static ma_result ma_engine_node_set_volume(ma_engine_node* pEngineNode, float volume)
  61075. {
  61076. if (pEngineNode == NULL) {
  61077. return MA_INVALID_ARGS;
  61078. }
  61079. ma_atomic_float_set(&pEngineNode->volume, volume);
  61080. /* If we're not smoothing we should bypass the volume gainer entirely. */
  61081. if (pEngineNode->volumeSmoothTimeInPCMFrames == 0) {
  61082. /* We should always have an active spatializer because it can be enabled and disabled dynamically. We can just use that for hodling our volume. */
  61083. ma_spatializer_set_master_volume(&pEngineNode->spatializer, volume);
  61084. } else {
  61085. /* We're using volume smoothing, so apply the master volume to the gainer. */
  61086. ma_gainer_set_gain(&pEngineNode->volumeGainer, volume);
  61087. }
  61088. return MA_SUCCESS;
  61089. }
  61090. static ma_result ma_engine_node_get_volume(const ma_engine_node* pEngineNode, float* pVolume)
  61091. {
  61092. if (pVolume == NULL) {
  61093. return MA_INVALID_ARGS;
  61094. }
  61095. *pVolume = 0.0f;
  61096. if (pEngineNode == NULL) {
  61097. return MA_INVALID_ARGS;
  61098. }
  61099. *pVolume = ma_atomic_float_get((ma_atomic_float*)&pEngineNode->volume);
  61100. return MA_SUCCESS;
  61101. }
  61102. static void ma_engine_node_process_pcm_frames__general(ma_engine_node* pEngineNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  61103. {
  61104. ma_uint32 frameCountIn;
  61105. ma_uint32 frameCountOut;
  61106. ma_uint32 totalFramesProcessedIn;
  61107. ma_uint32 totalFramesProcessedOut;
  61108. ma_uint32 channelsIn;
  61109. ma_uint32 channelsOut;
  61110. ma_bool32 isPitchingEnabled;
  61111. ma_bool32 isFadingEnabled;
  61112. ma_bool32 isSpatializationEnabled;
  61113. ma_bool32 isPanningEnabled;
  61114. ma_bool32 isVolumeSmoothingEnabled;
  61115. frameCountIn = *pFrameCountIn;
  61116. frameCountOut = *pFrameCountOut;
  61117. channelsIn = ma_spatializer_get_input_channels(&pEngineNode->spatializer);
  61118. channelsOut = ma_spatializer_get_output_channels(&pEngineNode->spatializer);
  61119. totalFramesProcessedIn = 0;
  61120. totalFramesProcessedOut = 0;
  61121. /* Update the fader if applicable. */
  61122. {
  61123. ma_uint64 fadeLengthInFrames = ma_atomic_uint64_get(&pEngineNode->fadeSettings.fadeLengthInFrames);
  61124. if (fadeLengthInFrames != ~(ma_uint64)0) {
  61125. float fadeVolumeBeg = ma_atomic_float_get(&pEngineNode->fadeSettings.volumeBeg);
  61126. float fadeVolumeEnd = ma_atomic_float_get(&pEngineNode->fadeSettings.volumeEnd);
  61127. ma_int64 fadeStartOffsetInFrames = (ma_int64)ma_atomic_uint64_get(&pEngineNode->fadeSettings.absoluteGlobalTimeInFrames);
  61128. if (fadeStartOffsetInFrames == (ma_int64)(~(ma_uint64)0)) {
  61129. fadeStartOffsetInFrames = 0;
  61130. } else {
  61131. fadeStartOffsetInFrames -= ma_engine_get_time_in_pcm_frames(pEngineNode->pEngine);
  61132. }
  61133. ma_fader_set_fade_ex(&pEngineNode->fader, fadeVolumeBeg, fadeVolumeEnd, fadeLengthInFrames, fadeStartOffsetInFrames);
  61134. /* Reset the fade length so we don't erroneously apply it again. */
  61135. ma_atomic_uint64_set(&pEngineNode->fadeSettings.fadeLengthInFrames, ~(ma_uint64)0);
  61136. }
  61137. }
  61138. isPitchingEnabled = ma_engine_node_is_pitching_enabled(pEngineNode);
  61139. isFadingEnabled = pEngineNode->fader.volumeBeg != 1 || pEngineNode->fader.volumeEnd != 1;
  61140. isSpatializationEnabled = ma_engine_node_is_spatialization_enabled(pEngineNode);
  61141. isPanningEnabled = pEngineNode->panner.pan != 0 && channelsOut != 1;
  61142. isVolumeSmoothingEnabled = pEngineNode->volumeSmoothTimeInPCMFrames > 0;
  61143. /* Keep going while we've still got data available for processing. */
  61144. while (totalFramesProcessedOut < frameCountOut) {
  61145. /*
  61146. We need to process in a specific order. We always do resampling first because it's likely
  61147. we're going to be increasing the channel count after spatialization. Also, I want to do
  61148. fading based on the output sample rate.
  61149. We'll first read into a buffer from the resampler. Then we'll do all processing that
  61150. operates on the on the input channel count. We'll then get the spatializer to output to
  61151. the output buffer and then do all effects from that point directly in the output buffer
  61152. in-place.
  61153. Note that we're always running the resampler if pitching is enabled, even when the pitch
  61154. is 1. If we try to be clever and skip resampling when the pitch is 1, we'll get a glitch
  61155. when we move away from 1, back to 1, and then away from 1 again. We'll want to implement
  61156. any pitch=1 optimizations in the resampler itself.
  61157. There's a small optimization here that we'll utilize since it might be a fairly common
  61158. case. When the input and output channel counts are the same, we'll read straight into the
  61159. output buffer from the resampler and do everything in-place.
  61160. */
  61161. const float* pRunningFramesIn;
  61162. float* pRunningFramesOut;
  61163. float* pWorkingBuffer; /* This is the buffer that we'll be processing frames in. This is in input channels. */
  61164. float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)];
  61165. ma_uint32 tempCapInFrames = ma_countof(temp) / channelsIn;
  61166. ma_uint32 framesAvailableIn;
  61167. ma_uint32 framesAvailableOut;
  61168. ma_uint32 framesJustProcessedIn;
  61169. ma_uint32 framesJustProcessedOut;
  61170. ma_bool32 isWorkingBufferValid = MA_FALSE;
  61171. framesAvailableIn = frameCountIn - totalFramesProcessedIn;
  61172. framesAvailableOut = frameCountOut - totalFramesProcessedOut;
  61173. pRunningFramesIn = ma_offset_pcm_frames_const_ptr_f32(ppFramesIn[0], totalFramesProcessedIn, channelsIn);
  61174. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesProcessedOut, channelsOut);
  61175. if (channelsIn == channelsOut) {
  61176. /* Fast path. Channel counts are the same. No need for an intermediary input buffer. */
  61177. pWorkingBuffer = pRunningFramesOut;
  61178. } else {
  61179. /* Slow path. Channel counts are different. Need to use an intermediary input buffer. */
  61180. pWorkingBuffer = temp;
  61181. if (framesAvailableOut > tempCapInFrames) {
  61182. framesAvailableOut = tempCapInFrames;
  61183. }
  61184. }
  61185. /* First is resampler. */
  61186. if (isPitchingEnabled) {
  61187. ma_uint64 resampleFrameCountIn = framesAvailableIn;
  61188. ma_uint64 resampleFrameCountOut = framesAvailableOut;
  61189. ma_linear_resampler_process_pcm_frames(&pEngineNode->resampler, pRunningFramesIn, &resampleFrameCountIn, pWorkingBuffer, &resampleFrameCountOut);
  61190. isWorkingBufferValid = MA_TRUE;
  61191. framesJustProcessedIn = (ma_uint32)resampleFrameCountIn;
  61192. framesJustProcessedOut = (ma_uint32)resampleFrameCountOut;
  61193. } else {
  61194. framesJustProcessedIn = ma_min(framesAvailableIn, framesAvailableOut);
  61195. framesJustProcessedOut = framesJustProcessedIn; /* When no resampling is being performed, the number of output frames is the same as input frames. */
  61196. }
  61197. /* Fading. */
  61198. if (isFadingEnabled) {
  61199. if (isWorkingBufferValid) {
  61200. ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut); /* In-place processing. */
  61201. } else {
  61202. ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut);
  61203. isWorkingBufferValid = MA_TRUE;
  61204. }
  61205. }
  61206. /*
  61207. If we're using smoothing, we won't be applying volume via the spatializer, but instead from a ma_gainer. In this case
  61208. we'll want to apply our volume now.
  61209. */
  61210. if (isVolumeSmoothingEnabled) {
  61211. if (isWorkingBufferValid) {
  61212. ma_gainer_process_pcm_frames(&pEngineNode->volumeGainer, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut);
  61213. } else {
  61214. ma_gainer_process_pcm_frames(&pEngineNode->volumeGainer, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut);
  61215. isWorkingBufferValid = MA_TRUE;
  61216. }
  61217. }
  61218. /*
  61219. If at this point we still haven't actually done anything with the working buffer we need
  61220. to just read straight from the input buffer.
  61221. */
  61222. if (isWorkingBufferValid == MA_FALSE) {
  61223. 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. */
  61224. }
  61225. /* Spatialization. */
  61226. if (isSpatializationEnabled) {
  61227. ma_uint32 iListener;
  61228. /*
  61229. When determining the listener to use, we first check to see if the sound is pinned to a
  61230. specific listener. If so, we use that. Otherwise we just use the closest listener.
  61231. */
  61232. if (pEngineNode->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pEngineNode->pinnedListenerIndex < ma_engine_get_listener_count(pEngineNode->pEngine)) {
  61233. iListener = pEngineNode->pinnedListenerIndex;
  61234. } else {
  61235. ma_vec3f spatializerPosition = ma_spatializer_get_position(&pEngineNode->spatializer);
  61236. iListener = ma_engine_find_closest_listener(pEngineNode->pEngine, spatializerPosition.x, spatializerPosition.y, spatializerPosition.z);
  61237. }
  61238. ma_spatializer_process_pcm_frames(&pEngineNode->spatializer, &pEngineNode->pEngine->listeners[iListener], pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut);
  61239. } else {
  61240. /* No spatialization, but we still need to do channel conversion and master volume. */
  61241. float volume;
  61242. ma_engine_node_get_volume(pEngineNode, &volume); /* Should never fail. */
  61243. if (channelsIn == channelsOut) {
  61244. /* No channel conversion required. Just copy straight to the output buffer. */
  61245. if (isVolumeSmoothingEnabled) {
  61246. /* Volume has already been applied. Just copy straight to the output buffer. */
  61247. ma_copy_pcm_frames(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut * channelsOut, ma_format_f32, channelsOut);
  61248. } else {
  61249. /* Volume has not been applied yet. Copy and apply volume in the same pass. */
  61250. ma_copy_and_apply_volume_factor_f32(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut * channelsOut, volume);
  61251. }
  61252. } else {
  61253. /* Channel conversion required. TODO: Add support for channel maps here. */
  61254. ma_channel_map_apply_f32(pRunningFramesOut, NULL, channelsOut, pWorkingBuffer, NULL, channelsIn, framesJustProcessedOut, ma_channel_mix_mode_simple, pEngineNode->monoExpansionMode);
  61255. /* If we're using smoothing, the volume will have already been applied. */
  61256. if (!isVolumeSmoothingEnabled) {
  61257. ma_apply_volume_factor_f32(pRunningFramesOut, framesJustProcessedOut * channelsOut, volume);
  61258. }
  61259. }
  61260. }
  61261. /* At this point we can guarantee that the output buffer contains valid data. We can process everything in place now. */
  61262. /* Panning. */
  61263. if (isPanningEnabled) {
  61264. ma_panner_process_pcm_frames(&pEngineNode->panner, pRunningFramesOut, pRunningFramesOut, framesJustProcessedOut); /* In-place processing. */
  61265. }
  61266. /* We're done for this chunk. */
  61267. totalFramesProcessedIn += framesJustProcessedIn;
  61268. totalFramesProcessedOut += framesJustProcessedOut;
  61269. /* 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. */
  61270. if (framesJustProcessedOut == 0) {
  61271. break;
  61272. }
  61273. }
  61274. /* At this point we're done processing. */
  61275. *pFrameCountIn = totalFramesProcessedIn;
  61276. *pFrameCountOut = totalFramesProcessedOut;
  61277. }
  61278. static void ma_engine_node_process_pcm_frames__sound(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  61279. {
  61280. /* For sounds, we need to first read from the data source. Then we need to apply the engine effects (pan, pitch, fades, etc.). */
  61281. ma_result result = MA_SUCCESS;
  61282. ma_sound* pSound = (ma_sound*)pNode;
  61283. ma_uint32 frameCount = *pFrameCountOut;
  61284. ma_uint32 totalFramesRead = 0;
  61285. ma_format dataSourceFormat;
  61286. ma_uint32 dataSourceChannels;
  61287. ma_uint8 temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  61288. ma_uint32 tempCapInFrames;
  61289. ma_uint64 seekTarget;
  61290. /* This is a data source node which means no input buses. */
  61291. (void)ppFramesIn;
  61292. (void)pFrameCountIn;
  61293. /* If we're marked at the end we need to stop the sound and do nothing. */
  61294. if (ma_sound_at_end(pSound)) {
  61295. ma_sound_stop(pSound);
  61296. *pFrameCountOut = 0;
  61297. return;
  61298. }
  61299. /* If we're seeking, do so now before reading. */
  61300. seekTarget = ma_atomic_load_64(&pSound->seekTarget);
  61301. if (seekTarget != MA_SEEK_TARGET_NONE) {
  61302. ma_data_source_seek_to_pcm_frame(pSound->pDataSource, seekTarget);
  61303. /* Any time-dependant effects need to have their times updated. */
  61304. ma_node_set_time(pSound, seekTarget);
  61305. ma_atomic_exchange_64(&pSound->seekTarget, MA_SEEK_TARGET_NONE);
  61306. }
  61307. /*
  61308. We want to update the pitch once. For sounds, this can be either at the start or at the end. If
  61309. we don't force this to only ever be updating once, we could end up in a situation where
  61310. retrieving the required input frame count ends up being different to what we actually retrieve.
  61311. What could happen is that the required input frame count is calculated, the pitch is update,
  61312. and then this processing function is called resulting in a different number of input frames
  61313. being processed. Do not call this in ma_engine_node_process_pcm_frames__general() or else
  61314. you'll hit the aforementioned bug.
  61315. */
  61316. ma_engine_node_update_pitch_if_required(&pSound->engineNode);
  61317. /*
  61318. For the convenience of the caller, we're doing to allow data sources to use non-floating-point formats and channel counts that differ
  61319. from the main engine.
  61320. */
  61321. result = ma_data_source_get_data_format(pSound->pDataSource, &dataSourceFormat, &dataSourceChannels, NULL, NULL, 0);
  61322. if (result == MA_SUCCESS) {
  61323. tempCapInFrames = sizeof(temp) / ma_get_bytes_per_frame(dataSourceFormat, dataSourceChannels);
  61324. /* Keep reading until we've read as much as was requested or we reach the end of the data source. */
  61325. while (totalFramesRead < frameCount) {
  61326. ma_uint32 framesRemaining = frameCount - totalFramesRead;
  61327. ma_uint32 framesToRead;
  61328. ma_uint64 framesJustRead;
  61329. ma_uint32 frameCountIn;
  61330. ma_uint32 frameCountOut;
  61331. const float* pRunningFramesIn;
  61332. float* pRunningFramesOut;
  61333. /*
  61334. The first thing we need to do is read into the temporary buffer. We can calculate exactly
  61335. how many input frames we'll need after resampling.
  61336. */
  61337. framesToRead = (ma_uint32)ma_engine_node_get_required_input_frame_count(&pSound->engineNode, framesRemaining);
  61338. if (framesToRead > tempCapInFrames) {
  61339. framesToRead = tempCapInFrames;
  61340. }
  61341. result = ma_data_source_read_pcm_frames(pSound->pDataSource, temp, framesToRead, &framesJustRead);
  61342. /* 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. */
  61343. if (result == MA_AT_END) {
  61344. ma_sound_set_at_end(pSound, MA_TRUE); /* This will be set to false in ma_sound_start(). */
  61345. }
  61346. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesRead, ma_engine_get_channels(ma_sound_get_engine(pSound)));
  61347. frameCountIn = (ma_uint32)framesJustRead;
  61348. frameCountOut = framesRemaining;
  61349. /* Convert if necessary. */
  61350. if (dataSourceFormat == ma_format_f32) {
  61351. /* Fast path. No data conversion necessary. */
  61352. pRunningFramesIn = (float*)temp;
  61353. ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut);
  61354. } else {
  61355. /* 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. */
  61356. 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. */
  61357. ma_convert_pcm_frames_format(tempf32, ma_format_f32, temp, dataSourceFormat, framesJustRead, dataSourceChannels, ma_dither_mode_none);
  61358. /* Now that we have our samples in f32 format we can process like normal. */
  61359. pRunningFramesIn = tempf32;
  61360. ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut);
  61361. }
  61362. /* We should have processed all of our input frames since we calculated the required number of input frames at the top. */
  61363. MA_ASSERT(frameCountIn == framesJustRead);
  61364. totalFramesRead += (ma_uint32)frameCountOut; /* Safe cast. */
  61365. if (result != MA_SUCCESS || ma_sound_at_end(pSound)) {
  61366. break; /* Might have reached the end. */
  61367. }
  61368. }
  61369. }
  61370. *pFrameCountOut = totalFramesRead;
  61371. }
  61372. static void ma_engine_node_process_pcm_frames__group(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  61373. {
  61374. /*
  61375. Make sure the pitch is updated before trying to read anything. It's important that this is done
  61376. only once and not in ma_engine_node_process_pcm_frames__general(). The reason for this is that
  61377. ma_engine_node_process_pcm_frames__general() will call ma_engine_node_get_required_input_frame_count(),
  61378. and if another thread modifies the pitch just after that call it can result in a glitch due to
  61379. the input rate changing.
  61380. */
  61381. ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode);
  61382. /* For groups, the input data has already been read and we just need to apply the effect. */
  61383. ma_engine_node_process_pcm_frames__general((ma_engine_node*)pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut);
  61384. }
  61385. static ma_result ma_engine_node_get_required_input_frame_count__group(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount)
  61386. {
  61387. ma_uint64 inputFrameCount;
  61388. MA_ASSERT(pInputFrameCount != NULL);
  61389. /* Our pitch will affect this calculation. We need to update it. */
  61390. ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode);
  61391. inputFrameCount = ma_engine_node_get_required_input_frame_count((ma_engine_node*)pNode, outputFrameCount);
  61392. if (inputFrameCount > 0xFFFFFFFF) {
  61393. inputFrameCount = 0xFFFFFFFF; /* Will never happen because miniaudio will only ever process in relatively small chunks. */
  61394. }
  61395. *pInputFrameCount = (ma_uint32)inputFrameCount;
  61396. return MA_SUCCESS;
  61397. }
  61398. static ma_node_vtable g_ma_engine_node_vtable__sound =
  61399. {
  61400. ma_engine_node_process_pcm_frames__sound,
  61401. NULL, /* onGetRequiredInputFrameCount */
  61402. 0, /* Sounds are data source nodes which means they have zero inputs (their input is drawn from the data source itself). */
  61403. 1, /* Sounds have one output bus. */
  61404. 0 /* Default flags. */
  61405. };
  61406. static ma_node_vtable g_ma_engine_node_vtable__group =
  61407. {
  61408. ma_engine_node_process_pcm_frames__group,
  61409. ma_engine_node_get_required_input_frame_count__group,
  61410. 1, /* Groups have one input bus. */
  61411. 1, /* Groups have one output bus. */
  61412. MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES /* The engine node does resampling so should let miniaudio know about it. */
  61413. };
  61414. static ma_node_config ma_engine_node_base_node_config_init(const ma_engine_node_config* pConfig)
  61415. {
  61416. ma_node_config baseNodeConfig;
  61417. if (pConfig->type == ma_engine_node_type_sound) {
  61418. /* Sound. */
  61419. baseNodeConfig = ma_node_config_init();
  61420. baseNodeConfig.vtable = &g_ma_engine_node_vtable__sound;
  61421. baseNodeConfig.initialState = ma_node_state_stopped; /* Sounds are stopped by default. */
  61422. } else {
  61423. /* Group. */
  61424. baseNodeConfig = ma_node_config_init();
  61425. baseNodeConfig.vtable = &g_ma_engine_node_vtable__group;
  61426. baseNodeConfig.initialState = ma_node_state_started; /* Groups are started by default. */
  61427. }
  61428. return baseNodeConfig;
  61429. }
  61430. static ma_spatializer_config ma_engine_node_spatializer_config_init(const ma_node_config* pBaseNodeConfig)
  61431. {
  61432. return ma_spatializer_config_init(pBaseNodeConfig->pInputChannels[0], pBaseNodeConfig->pOutputChannels[0]);
  61433. }
  61434. typedef struct
  61435. {
  61436. size_t sizeInBytes;
  61437. size_t baseNodeOffset;
  61438. size_t resamplerOffset;
  61439. size_t spatializerOffset;
  61440. size_t gainerOffset;
  61441. } ma_engine_node_heap_layout;
  61442. static ma_result ma_engine_node_get_heap_layout(const ma_engine_node_config* pConfig, ma_engine_node_heap_layout* pHeapLayout)
  61443. {
  61444. ma_result result;
  61445. size_t tempHeapSize;
  61446. ma_node_config baseNodeConfig;
  61447. ma_linear_resampler_config resamplerConfig;
  61448. ma_spatializer_config spatializerConfig;
  61449. ma_gainer_config gainerConfig;
  61450. ma_uint32 channelsIn;
  61451. ma_uint32 channelsOut;
  61452. 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. */
  61453. MA_ASSERT(pHeapLayout);
  61454. MA_ZERO_OBJECT(pHeapLayout);
  61455. if (pConfig == NULL) {
  61456. return MA_INVALID_ARGS;
  61457. }
  61458. if (pConfig->pEngine == NULL) {
  61459. return MA_INVALID_ARGS; /* An engine must be specified. */
  61460. }
  61461. pHeapLayout->sizeInBytes = 0;
  61462. channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine);
  61463. channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine);
  61464. /* Base node. */
  61465. baseNodeConfig = ma_engine_node_base_node_config_init(pConfig);
  61466. baseNodeConfig.pInputChannels = &channelsIn;
  61467. baseNodeConfig.pOutputChannels = &channelsOut;
  61468. result = ma_node_get_heap_size(ma_engine_get_node_graph(pConfig->pEngine), &baseNodeConfig, &tempHeapSize);
  61469. if (result != MA_SUCCESS) {
  61470. return result; /* Failed to retrieve the size of the heap for the base node. */
  61471. }
  61472. pHeapLayout->baseNodeOffset = pHeapLayout->sizeInBytes;
  61473. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61474. /* Resmapler. */
  61475. 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. */
  61476. resamplerConfig.lpfOrder = 0;
  61477. result = ma_linear_resampler_get_heap_size(&resamplerConfig, &tempHeapSize);
  61478. if (result != MA_SUCCESS) {
  61479. return result; /* Failed to retrieve the size of the heap for the resampler. */
  61480. }
  61481. pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes;
  61482. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61483. /* Spatializer. */
  61484. spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig);
  61485. if (spatializerConfig.channelsIn == 2) {
  61486. spatializerConfig.pChannelMapIn = defaultStereoChannelMap;
  61487. }
  61488. result = ma_spatializer_get_heap_size(&spatializerConfig, &tempHeapSize);
  61489. if (result != MA_SUCCESS) {
  61490. return result; /* Failed to retrieve the size of the heap for the spatializer. */
  61491. }
  61492. pHeapLayout->spatializerOffset = pHeapLayout->sizeInBytes;
  61493. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61494. /* Gainer. Will not be used if we are not using smoothing. */
  61495. if (pConfig->volumeSmoothTimeInPCMFrames > 0) {
  61496. gainerConfig = ma_gainer_config_init(channelsIn, pConfig->volumeSmoothTimeInPCMFrames);
  61497. result = ma_gainer_get_heap_size(&gainerConfig, &tempHeapSize);
  61498. if (result != MA_SUCCESS) {
  61499. return result;
  61500. }
  61501. pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes;
  61502. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  61503. }
  61504. return MA_SUCCESS;
  61505. }
  61506. MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes)
  61507. {
  61508. ma_result result;
  61509. ma_engine_node_heap_layout heapLayout;
  61510. if (pHeapSizeInBytes == NULL) {
  61511. return MA_INVALID_ARGS;
  61512. }
  61513. *pHeapSizeInBytes = 0;
  61514. result = ma_engine_node_get_heap_layout(pConfig, &heapLayout);
  61515. if (result != MA_SUCCESS) {
  61516. return result;
  61517. }
  61518. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  61519. return MA_SUCCESS;
  61520. }
  61521. MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode)
  61522. {
  61523. ma_result result;
  61524. ma_engine_node_heap_layout heapLayout;
  61525. ma_node_config baseNodeConfig;
  61526. ma_linear_resampler_config resamplerConfig;
  61527. ma_fader_config faderConfig;
  61528. ma_spatializer_config spatializerConfig;
  61529. ma_panner_config pannerConfig;
  61530. ma_gainer_config gainerConfig;
  61531. ma_uint32 channelsIn;
  61532. ma_uint32 channelsOut;
  61533. 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. */
  61534. if (pEngineNode == NULL) {
  61535. return MA_INVALID_ARGS;
  61536. }
  61537. MA_ZERO_OBJECT(pEngineNode);
  61538. result = ma_engine_node_get_heap_layout(pConfig, &heapLayout);
  61539. if (result != MA_SUCCESS) {
  61540. return result;
  61541. }
  61542. if (pConfig->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pConfig->pinnedListenerIndex >= ma_engine_get_listener_count(pConfig->pEngine)) {
  61543. return MA_INVALID_ARGS; /* Invalid listener. */
  61544. }
  61545. pEngineNode->_pHeap = pHeap;
  61546. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  61547. pEngineNode->pEngine = pConfig->pEngine;
  61548. pEngineNode->sampleRate = (pConfig->sampleRate > 0) ? pConfig->sampleRate : ma_engine_get_sample_rate(pEngineNode->pEngine);
  61549. pEngineNode->volumeSmoothTimeInPCMFrames = pConfig->volumeSmoothTimeInPCMFrames;
  61550. pEngineNode->monoExpansionMode = pConfig->monoExpansionMode;
  61551. ma_atomic_float_set(&pEngineNode->volume, 1);
  61552. pEngineNode->pitch = 1;
  61553. pEngineNode->oldPitch = 1;
  61554. pEngineNode->oldDopplerPitch = 1;
  61555. pEngineNode->isPitchDisabled = pConfig->isPitchDisabled;
  61556. pEngineNode->isSpatializationDisabled = pConfig->isSpatializationDisabled;
  61557. pEngineNode->pinnedListenerIndex = pConfig->pinnedListenerIndex;
  61558. ma_atomic_float_set(&pEngineNode->fadeSettings.volumeBeg, 1);
  61559. ma_atomic_float_set(&pEngineNode->fadeSettings.volumeEnd, 1);
  61560. ma_atomic_uint64_set(&pEngineNode->fadeSettings.fadeLengthInFrames, (~(ma_uint64)0));
  61561. ma_atomic_uint64_set(&pEngineNode->fadeSettings.absoluteGlobalTimeInFrames, (~(ma_uint64)0)); /* <-- Indicates that the fade should start immediately. */
  61562. channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine);
  61563. channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine);
  61564. /*
  61565. If the sample rate of the sound is different to the engine, make sure pitching is enabled so that the resampler
  61566. is activated. Not doing this will result in the sound not being resampled if MA_SOUND_FLAG_NO_PITCH is used.
  61567. */
  61568. if (pEngineNode->sampleRate != ma_engine_get_sample_rate(pEngineNode->pEngine)) {
  61569. pEngineNode->isPitchDisabled = MA_FALSE;
  61570. }
  61571. /* Base node. */
  61572. baseNodeConfig = ma_engine_node_base_node_config_init(pConfig);
  61573. baseNodeConfig.pInputChannels = &channelsIn;
  61574. baseNodeConfig.pOutputChannels = &channelsOut;
  61575. result = ma_node_init_preallocated(&pConfig->pEngine->nodeGraph, &baseNodeConfig, ma_offset_ptr(pHeap, heapLayout.baseNodeOffset), &pEngineNode->baseNode);
  61576. if (result != MA_SUCCESS) {
  61577. goto error0;
  61578. }
  61579. /*
  61580. We can now initialize the effects we need in order to implement the engine node. There's a
  61581. defined order of operations here, mainly centered around when we convert our channels from the
  61582. data source's native channel count to the engine's channel count. As a rule, we want to do as
  61583. much computation as possible before spatialization because there's a chance that will increase
  61584. the channel count, thereby increasing the amount of work needing to be done to process.
  61585. */
  61586. /* We'll always do resampling first. */
  61587. resamplerConfig = ma_linear_resampler_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], pEngineNode->sampleRate, ma_engine_get_sample_rate(pEngineNode->pEngine));
  61588. 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. */
  61589. result = ma_linear_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pEngineNode->resampler);
  61590. if (result != MA_SUCCESS) {
  61591. goto error1;
  61592. }
  61593. /* After resampling will come the fader. */
  61594. faderConfig = ma_fader_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], ma_engine_get_sample_rate(pEngineNode->pEngine));
  61595. result = ma_fader_init(&faderConfig, &pEngineNode->fader);
  61596. if (result != MA_SUCCESS) {
  61597. goto error2;
  61598. }
  61599. /*
  61600. Spatialization comes next. We spatialize based ont he node's output channel count. It's up the caller to
  61601. ensure channels counts link up correctly in the node graph.
  61602. */
  61603. spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig);
  61604. spatializerConfig.gainSmoothTimeInFrames = pEngineNode->pEngine->gainSmoothTimeInFrames;
  61605. if (spatializerConfig.channelsIn == 2) {
  61606. spatializerConfig.pChannelMapIn = defaultStereoChannelMap;
  61607. }
  61608. result = ma_spatializer_init_preallocated(&spatializerConfig, ma_offset_ptr(pHeap, heapLayout.spatializerOffset), &pEngineNode->spatializer);
  61609. if (result != MA_SUCCESS) {
  61610. goto error2;
  61611. }
  61612. /*
  61613. After spatialization comes panning. We need to do this after spatialization because otherwise we wouldn't
  61614. be able to pan mono sounds.
  61615. */
  61616. pannerConfig = ma_panner_config_init(ma_format_f32, baseNodeConfig.pOutputChannels[0]);
  61617. result = ma_panner_init(&pannerConfig, &pEngineNode->panner);
  61618. if (result != MA_SUCCESS) {
  61619. goto error3;
  61620. }
  61621. /* 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. */
  61622. if (pConfig->volumeSmoothTimeInPCMFrames > 0) {
  61623. gainerConfig = ma_gainer_config_init(channelsIn, pConfig->volumeSmoothTimeInPCMFrames);
  61624. result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pEngineNode->volumeGainer);
  61625. if (result != MA_SUCCESS) {
  61626. goto error3;
  61627. }
  61628. }
  61629. return MA_SUCCESS;
  61630. /* No need for allocation callbacks here because we use a preallocated heap. */
  61631. error3: ma_spatializer_uninit(&pEngineNode->spatializer, NULL);
  61632. error2: ma_linear_resampler_uninit(&pEngineNode->resampler, NULL);
  61633. error1: ma_node_uninit(&pEngineNode->baseNode, NULL);
  61634. error0: return result;
  61635. }
  61636. MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode)
  61637. {
  61638. ma_result result;
  61639. size_t heapSizeInBytes;
  61640. void* pHeap;
  61641. result = ma_engine_node_get_heap_size(pConfig, &heapSizeInBytes);
  61642. if (result != MA_SUCCESS) {
  61643. return result;
  61644. }
  61645. if (heapSizeInBytes > 0) {
  61646. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  61647. if (pHeap == NULL) {
  61648. return MA_OUT_OF_MEMORY;
  61649. }
  61650. } else {
  61651. pHeap = NULL;
  61652. }
  61653. result = ma_engine_node_init_preallocated(pConfig, pHeap, pEngineNode);
  61654. if (result != MA_SUCCESS) {
  61655. ma_free(pHeap, pAllocationCallbacks);
  61656. return result;
  61657. }
  61658. pEngineNode->_ownsHeap = MA_TRUE;
  61659. return MA_SUCCESS;
  61660. }
  61661. MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks)
  61662. {
  61663. /*
  61664. The base node always needs to be uninitialized first to ensure it's detached from the graph completely before we
  61665. destroy anything that might be in the middle of being used by the processing function.
  61666. */
  61667. ma_node_uninit(&pEngineNode->baseNode, pAllocationCallbacks);
  61668. /* Now that the node has been uninitialized we can safely uninitialize the rest. */
  61669. if (pEngineNode->volumeSmoothTimeInPCMFrames > 0) {
  61670. ma_gainer_uninit(&pEngineNode->volumeGainer, pAllocationCallbacks);
  61671. }
  61672. ma_spatializer_uninit(&pEngineNode->spatializer, pAllocationCallbacks);
  61673. ma_linear_resampler_uninit(&pEngineNode->resampler, pAllocationCallbacks);
  61674. /* Free the heap last. */
  61675. if (pEngineNode->_ownsHeap) {
  61676. ma_free(pEngineNode->_pHeap, pAllocationCallbacks);
  61677. }
  61678. }
  61679. MA_API ma_sound_config ma_sound_config_init(void)
  61680. {
  61681. return ma_sound_config_init_2(NULL);
  61682. }
  61683. MA_API ma_sound_config ma_sound_config_init_2(ma_engine* pEngine)
  61684. {
  61685. ma_sound_config config;
  61686. MA_ZERO_OBJECT(&config);
  61687. if (pEngine != NULL) {
  61688. config.monoExpansionMode = pEngine->monoExpansionMode;
  61689. } else {
  61690. config.monoExpansionMode = ma_mono_expansion_mode_default;
  61691. }
  61692. config.rangeEndInPCMFrames = ~((ma_uint64)0);
  61693. config.loopPointEndInPCMFrames = ~((ma_uint64)0);
  61694. return config;
  61695. }
  61696. MA_API ma_sound_group_config ma_sound_group_config_init(void)
  61697. {
  61698. return ma_sound_group_config_init_2(NULL);
  61699. }
  61700. MA_API ma_sound_group_config ma_sound_group_config_init_2(ma_engine* pEngine)
  61701. {
  61702. ma_sound_group_config config;
  61703. MA_ZERO_OBJECT(&config);
  61704. if (pEngine != NULL) {
  61705. config.monoExpansionMode = pEngine->monoExpansionMode;
  61706. } else {
  61707. config.monoExpansionMode = ma_mono_expansion_mode_default;
  61708. }
  61709. return config;
  61710. }
  61711. MA_API ma_engine_config ma_engine_config_init(void)
  61712. {
  61713. ma_engine_config config;
  61714. MA_ZERO_OBJECT(&config);
  61715. config.listenerCount = 1; /* Always want at least one listener. */
  61716. config.monoExpansionMode = ma_mono_expansion_mode_default;
  61717. return config;
  61718. }
  61719. #if !defined(MA_NO_DEVICE_IO)
  61720. static void ma_engine_data_callback_internal(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  61721. {
  61722. ma_engine* pEngine = (ma_engine*)pDevice->pUserData;
  61723. (void)pFramesIn;
  61724. /*
  61725. Experiment: Try processing a resource manager job if we're on the Emscripten build.
  61726. This serves two purposes:
  61727. 1) It ensures jobs are actually processed at some point since we cannot guarantee that the
  61728. caller is doing the right thing and calling ma_resource_manager_process_next_job(); and
  61729. 2) It's an attempt at working around an issue where processing jobs on the Emscripten main
  61730. loop doesn't work as well as it should. When trying to load sounds without the `DECODE`
  61731. flag or with the `ASYNC` flag, the sound data is just not able to be loaded in time
  61732. before the callback is processed. I think it's got something to do with the single-
  61733. threaded nature of Web, but I'm not entirely sure.
  61734. */
  61735. #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_EMSCRIPTEN)
  61736. {
  61737. if (pEngine->pResourceManager != NULL) {
  61738. if ((pEngine->pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) {
  61739. ma_resource_manager_process_next_job(pEngine->pResourceManager);
  61740. }
  61741. }
  61742. }
  61743. #endif
  61744. ma_engine_read_pcm_frames(pEngine, pFramesOut, frameCount, NULL);
  61745. }
  61746. #endif
  61747. MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine)
  61748. {
  61749. ma_result result;
  61750. ma_node_graph_config nodeGraphConfig;
  61751. ma_engine_config engineConfig;
  61752. ma_spatializer_listener_config listenerConfig;
  61753. ma_uint32 iListener;
  61754. if (pEngine == NULL) {
  61755. return MA_INVALID_ARGS;
  61756. }
  61757. MA_ZERO_OBJECT(pEngine);
  61758. /* The config is allowed to be NULL in which case we use defaults for everything. */
  61759. if (pConfig != NULL) {
  61760. engineConfig = *pConfig;
  61761. } else {
  61762. engineConfig = ma_engine_config_init();
  61763. }
  61764. pEngine->monoExpansionMode = engineConfig.monoExpansionMode;
  61765. pEngine->defaultVolumeSmoothTimeInPCMFrames = engineConfig.defaultVolumeSmoothTimeInPCMFrames;
  61766. pEngine->onProcess = engineConfig.onProcess;
  61767. pEngine->pProcessUserData = engineConfig.pProcessUserData;
  61768. ma_allocation_callbacks_init_copy(&pEngine->allocationCallbacks, &engineConfig.allocationCallbacks);
  61769. #if !defined(MA_NO_RESOURCE_MANAGER)
  61770. {
  61771. pEngine->pResourceManager = engineConfig.pResourceManager;
  61772. }
  61773. #endif
  61774. #if !defined(MA_NO_DEVICE_IO)
  61775. {
  61776. pEngine->pDevice = engineConfig.pDevice;
  61777. /* If we don't have a device, we need one. */
  61778. if (pEngine->pDevice == NULL && engineConfig.noDevice == MA_FALSE) {
  61779. ma_device_config deviceConfig;
  61780. pEngine->pDevice = (ma_device*)ma_malloc(sizeof(*pEngine->pDevice), &pEngine->allocationCallbacks);
  61781. if (pEngine->pDevice == NULL) {
  61782. return MA_OUT_OF_MEMORY;
  61783. }
  61784. deviceConfig = ma_device_config_init(ma_device_type_playback);
  61785. deviceConfig.playback.pDeviceID = engineConfig.pPlaybackDeviceID;
  61786. deviceConfig.playback.format = ma_format_f32;
  61787. deviceConfig.playback.channels = engineConfig.channels;
  61788. deviceConfig.sampleRate = engineConfig.sampleRate;
  61789. deviceConfig.dataCallback = (engineConfig.dataCallback != NULL) ? engineConfig.dataCallback : ma_engine_data_callback_internal;
  61790. deviceConfig.pUserData = pEngine;
  61791. deviceConfig.notificationCallback = engineConfig.notificationCallback;
  61792. deviceConfig.periodSizeInFrames = engineConfig.periodSizeInFrames;
  61793. deviceConfig.periodSizeInMilliseconds = engineConfig.periodSizeInMilliseconds;
  61794. 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. */
  61795. deviceConfig.noClip = MA_TRUE; /* The engine will do clipping itself. */
  61796. if (engineConfig.pContext == NULL) {
  61797. ma_context_config contextConfig = ma_context_config_init();
  61798. contextConfig.allocationCallbacks = pEngine->allocationCallbacks;
  61799. contextConfig.pLog = engineConfig.pLog;
  61800. /* If the engine config does not specify a log, use the resource manager's if we have one. */
  61801. #ifndef MA_NO_RESOURCE_MANAGER
  61802. {
  61803. if (contextConfig.pLog == NULL && engineConfig.pResourceManager != NULL) {
  61804. contextConfig.pLog = ma_resource_manager_get_log(engineConfig.pResourceManager);
  61805. }
  61806. }
  61807. #endif
  61808. result = ma_device_init_ex(NULL, 0, &contextConfig, &deviceConfig, pEngine->pDevice);
  61809. } else {
  61810. result = ma_device_init(engineConfig.pContext, &deviceConfig, pEngine->pDevice);
  61811. }
  61812. if (result != MA_SUCCESS) {
  61813. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  61814. pEngine->pDevice = NULL;
  61815. return result;
  61816. }
  61817. pEngine->ownsDevice = MA_TRUE;
  61818. }
  61819. /* Update the channel count and sample rate of the engine config so we can reference it below. */
  61820. if (pEngine->pDevice != NULL) {
  61821. engineConfig.channels = pEngine->pDevice->playback.channels;
  61822. engineConfig.sampleRate = pEngine->pDevice->sampleRate;
  61823. }
  61824. }
  61825. #endif
  61826. if (engineConfig.channels == 0 || engineConfig.sampleRate == 0) {
  61827. return MA_INVALID_ARGS;
  61828. }
  61829. pEngine->sampleRate = engineConfig.sampleRate;
  61830. /* The engine always uses either the log that was passed into the config, or the context's log is available. */
  61831. if (engineConfig.pLog != NULL) {
  61832. pEngine->pLog = engineConfig.pLog;
  61833. } else {
  61834. #if !defined(MA_NO_DEVICE_IO)
  61835. {
  61836. pEngine->pLog = ma_device_get_log(pEngine->pDevice);
  61837. }
  61838. #else
  61839. {
  61840. pEngine->pLog = NULL;
  61841. }
  61842. #endif
  61843. }
  61844. /* The engine is a node graph. This needs to be initialized after we have the device so we can can determine the channel count. */
  61845. nodeGraphConfig = ma_node_graph_config_init(engineConfig.channels);
  61846. nodeGraphConfig.nodeCacheCapInFrames = (engineConfig.periodSizeInFrames > 0xFFFF) ? 0xFFFF : (ma_uint16)engineConfig.periodSizeInFrames;
  61847. result = ma_node_graph_init(&nodeGraphConfig, &pEngine->allocationCallbacks, &pEngine->nodeGraph);
  61848. if (result != MA_SUCCESS) {
  61849. goto on_error_1;
  61850. }
  61851. /* We need at least one listener. */
  61852. if (engineConfig.listenerCount == 0) {
  61853. engineConfig.listenerCount = 1;
  61854. }
  61855. if (engineConfig.listenerCount > MA_ENGINE_MAX_LISTENERS) {
  61856. result = MA_INVALID_ARGS; /* Too many listeners. */
  61857. goto on_error_1;
  61858. }
  61859. for (iListener = 0; iListener < engineConfig.listenerCount; iListener += 1) {
  61860. listenerConfig = ma_spatializer_listener_config_init(ma_node_graph_get_channels(&pEngine->nodeGraph));
  61861. /*
  61862. If we're using a device, use the device's channel map for the listener. Otherwise just use
  61863. miniaudio's default channel map.
  61864. */
  61865. #if !defined(MA_NO_DEVICE_IO)
  61866. {
  61867. if (pEngine->pDevice != NULL) {
  61868. /*
  61869. Temporarily disabled. There is a subtle bug here where front-left and front-right
  61870. will be used by the device's channel map, but this is not what we want to use for
  61871. spatialization. Instead we want to use side-left and side-right. I need to figure
  61872. out a better solution for this. For now, disabling the use of device channel maps.
  61873. */
  61874. /*listenerConfig.pChannelMapOut = pEngine->pDevice->playback.channelMap;*/
  61875. }
  61876. }
  61877. #endif
  61878. result = ma_spatializer_listener_init(&listenerConfig, &pEngine->allocationCallbacks, &pEngine->listeners[iListener]); /* TODO: Change this to a pre-allocated heap. */
  61879. if (result != MA_SUCCESS) {
  61880. goto on_error_2;
  61881. }
  61882. pEngine->listenerCount += 1;
  61883. }
  61884. /* Gain smoothing for spatialized sounds. */
  61885. pEngine->gainSmoothTimeInFrames = engineConfig.gainSmoothTimeInFrames;
  61886. if (pEngine->gainSmoothTimeInFrames == 0) {
  61887. ma_uint32 gainSmoothTimeInMilliseconds = engineConfig.gainSmoothTimeInMilliseconds;
  61888. if (gainSmoothTimeInMilliseconds == 0) {
  61889. gainSmoothTimeInMilliseconds = 8;
  61890. }
  61891. pEngine->gainSmoothTimeInFrames = (gainSmoothTimeInMilliseconds * ma_engine_get_sample_rate(pEngine)) / 1000; /* 8ms by default. */
  61892. }
  61893. /* We need a resource manager. */
  61894. #ifndef MA_NO_RESOURCE_MANAGER
  61895. {
  61896. if (pEngine->pResourceManager == NULL) {
  61897. ma_resource_manager_config resourceManagerConfig;
  61898. pEngine->pResourceManager = (ma_resource_manager*)ma_malloc(sizeof(*pEngine->pResourceManager), &pEngine->allocationCallbacks);
  61899. if (pEngine->pResourceManager == NULL) {
  61900. result = MA_OUT_OF_MEMORY;
  61901. goto on_error_2;
  61902. }
  61903. resourceManagerConfig = ma_resource_manager_config_init();
  61904. resourceManagerConfig.pLog = pEngine->pLog; /* Always use the engine's log for internally-managed resource managers. */
  61905. resourceManagerConfig.decodedFormat = ma_format_f32;
  61906. resourceManagerConfig.decodedChannels = 0; /* Leave the decoded channel count as 0 so we can get good spatialization. */
  61907. resourceManagerConfig.decodedSampleRate = ma_engine_get_sample_rate(pEngine);
  61908. ma_allocation_callbacks_init_copy(&resourceManagerConfig.allocationCallbacks, &pEngine->allocationCallbacks);
  61909. resourceManagerConfig.pVFS = engineConfig.pResourceManagerVFS;
  61910. /* The Emscripten build cannot use threads. */
  61911. #if defined(MA_EMSCRIPTEN)
  61912. {
  61913. resourceManagerConfig.jobThreadCount = 0;
  61914. resourceManagerConfig.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  61915. }
  61916. #endif
  61917. result = ma_resource_manager_init(&resourceManagerConfig, pEngine->pResourceManager);
  61918. if (result != MA_SUCCESS) {
  61919. goto on_error_3;
  61920. }
  61921. pEngine->ownsResourceManager = MA_TRUE;
  61922. }
  61923. }
  61924. #endif
  61925. /* Setup some stuff for inlined sounds. That is sounds played with ma_engine_play_sound(). */
  61926. pEngine->inlinedSoundLock = 0;
  61927. pEngine->pInlinedSoundHead = NULL;
  61928. /* Start the engine if required. This should always be the last step. */
  61929. #if !defined(MA_NO_DEVICE_IO)
  61930. {
  61931. if (engineConfig.noAutoStart == MA_FALSE && pEngine->pDevice != NULL) {
  61932. result = ma_engine_start(pEngine);
  61933. if (result != MA_SUCCESS) {
  61934. goto on_error_4; /* Failed to start the engine. */
  61935. }
  61936. }
  61937. }
  61938. #endif
  61939. return MA_SUCCESS;
  61940. #if !defined(MA_NO_DEVICE_IO)
  61941. on_error_4:
  61942. #endif
  61943. #if !defined(MA_NO_RESOURCE_MANAGER)
  61944. on_error_3:
  61945. if (pEngine->ownsResourceManager) {
  61946. ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks);
  61947. }
  61948. #endif /* MA_NO_RESOURCE_MANAGER */
  61949. on_error_2:
  61950. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  61951. ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks);
  61952. }
  61953. ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks);
  61954. on_error_1:
  61955. #if !defined(MA_NO_DEVICE_IO)
  61956. {
  61957. if (pEngine->ownsDevice) {
  61958. ma_device_uninit(pEngine->pDevice);
  61959. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  61960. }
  61961. }
  61962. #endif
  61963. return result;
  61964. }
  61965. MA_API void ma_engine_uninit(ma_engine* pEngine)
  61966. {
  61967. ma_uint32 iListener;
  61968. if (pEngine == NULL) {
  61969. return;
  61970. }
  61971. /* The device must be uninitialized before the node graph to ensure the audio thread doesn't try accessing it. */
  61972. #if !defined(MA_NO_DEVICE_IO)
  61973. {
  61974. if (pEngine->ownsDevice) {
  61975. ma_device_uninit(pEngine->pDevice);
  61976. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  61977. } else {
  61978. if (pEngine->pDevice != NULL) {
  61979. ma_device_stop(pEngine->pDevice);
  61980. }
  61981. }
  61982. }
  61983. #endif
  61984. /*
  61985. All inlined sounds need to be deleted. I'm going to use a lock here just to future proof in case
  61986. I want to do some kind of garbage collection later on.
  61987. */
  61988. ma_spinlock_lock(&pEngine->inlinedSoundLock);
  61989. {
  61990. for (;;) {
  61991. ma_sound_inlined* pSoundToDelete = pEngine->pInlinedSoundHead;
  61992. if (pSoundToDelete == NULL) {
  61993. break; /* Done. */
  61994. }
  61995. pEngine->pInlinedSoundHead = pSoundToDelete->pNext;
  61996. ma_sound_uninit(&pSoundToDelete->sound);
  61997. ma_free(pSoundToDelete, &pEngine->allocationCallbacks);
  61998. }
  61999. }
  62000. ma_spinlock_unlock(&pEngine->inlinedSoundLock);
  62001. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  62002. ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks);
  62003. }
  62004. /* Make sure the node graph is uninitialized after the audio thread has been shutdown to prevent accessing of the node graph after being uninitialized. */
  62005. ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks);
  62006. /* Uninitialize the resource manager last to ensure we don't have a thread still trying to access it. */
  62007. #ifndef MA_NO_RESOURCE_MANAGER
  62008. if (pEngine->ownsResourceManager) {
  62009. ma_resource_manager_uninit(pEngine->pResourceManager);
  62010. ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks);
  62011. }
  62012. #endif
  62013. }
  62014. MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  62015. {
  62016. ma_result result;
  62017. ma_uint64 framesRead = 0;
  62018. if (pFramesRead != NULL) {
  62019. *pFramesRead = 0;
  62020. }
  62021. result = ma_node_graph_read_pcm_frames(&pEngine->nodeGraph, pFramesOut, frameCount, &framesRead);
  62022. if (result != MA_SUCCESS) {
  62023. return result;
  62024. }
  62025. if (pFramesRead != NULL) {
  62026. *pFramesRead = framesRead;
  62027. }
  62028. if (pEngine->onProcess) {
  62029. pEngine->onProcess(pEngine->pProcessUserData, (float*)pFramesOut, framesRead); /* Safe cast to float* because the engine always works on floating point samples. */
  62030. }
  62031. return MA_SUCCESS;
  62032. }
  62033. MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine)
  62034. {
  62035. if (pEngine == NULL) {
  62036. return NULL;
  62037. }
  62038. return &pEngine->nodeGraph;
  62039. }
  62040. #if !defined(MA_NO_RESOURCE_MANAGER)
  62041. MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine)
  62042. {
  62043. if (pEngine == NULL) {
  62044. return NULL;
  62045. }
  62046. #if !defined(MA_NO_RESOURCE_MANAGER)
  62047. {
  62048. return pEngine->pResourceManager;
  62049. }
  62050. #else
  62051. {
  62052. return NULL;
  62053. }
  62054. #endif
  62055. }
  62056. #endif
  62057. MA_API ma_device* ma_engine_get_device(ma_engine* pEngine)
  62058. {
  62059. if (pEngine == NULL) {
  62060. return NULL;
  62061. }
  62062. #if !defined(MA_NO_DEVICE_IO)
  62063. {
  62064. return pEngine->pDevice;
  62065. }
  62066. #else
  62067. {
  62068. return NULL;
  62069. }
  62070. #endif
  62071. }
  62072. MA_API ma_log* ma_engine_get_log(ma_engine* pEngine)
  62073. {
  62074. if (pEngine == NULL) {
  62075. return NULL;
  62076. }
  62077. if (pEngine->pLog != NULL) {
  62078. return pEngine->pLog;
  62079. } else {
  62080. #if !defined(MA_NO_DEVICE_IO)
  62081. {
  62082. return ma_device_get_log(ma_engine_get_device(pEngine));
  62083. }
  62084. #else
  62085. {
  62086. return NULL;
  62087. }
  62088. #endif
  62089. }
  62090. }
  62091. MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine)
  62092. {
  62093. return ma_node_graph_get_endpoint(&pEngine->nodeGraph);
  62094. }
  62095. MA_API ma_uint64 ma_engine_get_time_in_pcm_frames(const ma_engine* pEngine)
  62096. {
  62097. return ma_node_graph_get_time(&pEngine->nodeGraph);
  62098. }
  62099. MA_API ma_uint64 ma_engine_get_time_in_milliseconds(const ma_engine* pEngine)
  62100. {
  62101. return ma_engine_get_time_in_pcm_frames(pEngine) * 1000 / ma_engine_get_sample_rate(pEngine);
  62102. }
  62103. MA_API ma_result ma_engine_set_time_in_pcm_frames(ma_engine* pEngine, ma_uint64 globalTime)
  62104. {
  62105. return ma_node_graph_set_time(&pEngine->nodeGraph, globalTime);
  62106. }
  62107. MA_API ma_result ma_engine_set_time_in_milliseconds(ma_engine* pEngine, ma_uint64 globalTime)
  62108. {
  62109. return ma_engine_set_time_in_pcm_frames(pEngine, globalTime * ma_engine_get_sample_rate(pEngine) / 1000);
  62110. }
  62111. MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine)
  62112. {
  62113. return ma_engine_get_time_in_pcm_frames(pEngine);
  62114. }
  62115. MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime)
  62116. {
  62117. return ma_engine_set_time_in_pcm_frames(pEngine, globalTime);
  62118. }
  62119. MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine)
  62120. {
  62121. return ma_node_graph_get_channels(&pEngine->nodeGraph);
  62122. }
  62123. MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine)
  62124. {
  62125. if (pEngine == NULL) {
  62126. return 0;
  62127. }
  62128. return pEngine->sampleRate;
  62129. }
  62130. MA_API ma_result ma_engine_start(ma_engine* pEngine)
  62131. {
  62132. ma_result result;
  62133. if (pEngine == NULL) {
  62134. return MA_INVALID_ARGS;
  62135. }
  62136. #if !defined(MA_NO_DEVICE_IO)
  62137. {
  62138. if (pEngine->pDevice != NULL) {
  62139. result = ma_device_start(pEngine->pDevice);
  62140. } else {
  62141. result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "starting" the engine. */
  62142. }
  62143. }
  62144. #else
  62145. {
  62146. result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "starting" the engine. */
  62147. }
  62148. #endif
  62149. if (result != MA_SUCCESS) {
  62150. return result;
  62151. }
  62152. return MA_SUCCESS;
  62153. }
  62154. MA_API ma_result ma_engine_stop(ma_engine* pEngine)
  62155. {
  62156. ma_result result;
  62157. if (pEngine == NULL) {
  62158. return MA_INVALID_ARGS;
  62159. }
  62160. #if !defined(MA_NO_DEVICE_IO)
  62161. {
  62162. if (pEngine->pDevice != NULL) {
  62163. result = ma_device_stop(pEngine->pDevice);
  62164. } else {
  62165. result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "stopping" the engine. */
  62166. }
  62167. }
  62168. #else
  62169. {
  62170. result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "stopping" the engine. */
  62171. }
  62172. #endif
  62173. if (result != MA_SUCCESS) {
  62174. return result;
  62175. }
  62176. return MA_SUCCESS;
  62177. }
  62178. MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume)
  62179. {
  62180. if (pEngine == NULL) {
  62181. return MA_INVALID_ARGS;
  62182. }
  62183. return ma_node_set_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0, volume);
  62184. }
  62185. MA_API float ma_engine_get_volume(ma_engine* pEngine)
  62186. {
  62187. if (pEngine == NULL) {
  62188. return 0;
  62189. }
  62190. return ma_node_get_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0);
  62191. }
  62192. MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB)
  62193. {
  62194. return ma_engine_set_volume(pEngine, ma_volume_db_to_linear(gainDB));
  62195. }
  62196. MA_API float ma_engine_get_gain_db(ma_engine* pEngine)
  62197. {
  62198. return ma_volume_linear_to_db(ma_engine_get_volume(pEngine));
  62199. }
  62200. MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine)
  62201. {
  62202. if (pEngine == NULL) {
  62203. return 0;
  62204. }
  62205. return pEngine->listenerCount;
  62206. }
  62207. MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ)
  62208. {
  62209. ma_uint32 iListener;
  62210. ma_uint32 iListenerClosest;
  62211. float closestLen2 = MA_FLT_MAX;
  62212. if (pEngine == NULL || pEngine->listenerCount == 1) {
  62213. return 0;
  62214. }
  62215. iListenerClosest = 0;
  62216. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  62217. if (ma_engine_listener_is_enabled(pEngine, iListener)) {
  62218. float len2 = ma_vec3f_len2(ma_vec3f_sub(ma_spatializer_listener_get_position(&pEngine->listeners[iListener]), ma_vec3f_init_3f(absolutePosX, absolutePosY, absolutePosZ)));
  62219. if (closestLen2 > len2) {
  62220. closestLen2 = len2;
  62221. iListenerClosest = iListener;
  62222. }
  62223. }
  62224. }
  62225. MA_ASSERT(iListenerClosest < 255);
  62226. return iListenerClosest;
  62227. }
  62228. MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  62229. {
  62230. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62231. return;
  62232. }
  62233. ma_spatializer_listener_set_position(&pEngine->listeners[listenerIndex], x, y, z);
  62234. }
  62235. MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex)
  62236. {
  62237. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62238. return ma_vec3f_init_3f(0, 0, 0);
  62239. }
  62240. return ma_spatializer_listener_get_position(&pEngine->listeners[listenerIndex]);
  62241. }
  62242. MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  62243. {
  62244. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62245. return;
  62246. }
  62247. ma_spatializer_listener_set_direction(&pEngine->listeners[listenerIndex], x, y, z);
  62248. }
  62249. MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex)
  62250. {
  62251. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62252. return ma_vec3f_init_3f(0, 0, -1);
  62253. }
  62254. return ma_spatializer_listener_get_direction(&pEngine->listeners[listenerIndex]);
  62255. }
  62256. MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  62257. {
  62258. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62259. return;
  62260. }
  62261. ma_spatializer_listener_set_velocity(&pEngine->listeners[listenerIndex], x, y, z);
  62262. }
  62263. MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex)
  62264. {
  62265. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62266. return ma_vec3f_init_3f(0, 0, 0);
  62267. }
  62268. return ma_spatializer_listener_get_velocity(&pEngine->listeners[listenerIndex]);
  62269. }
  62270. MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  62271. {
  62272. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62273. return;
  62274. }
  62275. ma_spatializer_listener_set_cone(&pEngine->listeners[listenerIndex], innerAngleInRadians, outerAngleInRadians, outerGain);
  62276. }
  62277. MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  62278. {
  62279. if (pInnerAngleInRadians != NULL) {
  62280. *pInnerAngleInRadians = 0;
  62281. }
  62282. if (pOuterAngleInRadians != NULL) {
  62283. *pOuterAngleInRadians = 0;
  62284. }
  62285. if (pOuterGain != NULL) {
  62286. *pOuterGain = 0;
  62287. }
  62288. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62289. return;
  62290. }
  62291. ma_spatializer_listener_get_cone(&pEngine->listeners[listenerIndex], pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  62292. }
  62293. MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  62294. {
  62295. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62296. return;
  62297. }
  62298. ma_spatializer_listener_set_world_up(&pEngine->listeners[listenerIndex], x, y, z);
  62299. }
  62300. MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex)
  62301. {
  62302. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62303. return ma_vec3f_init_3f(0, 1, 0);
  62304. }
  62305. return ma_spatializer_listener_get_world_up(&pEngine->listeners[listenerIndex]);
  62306. }
  62307. MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled)
  62308. {
  62309. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62310. return;
  62311. }
  62312. ma_spatializer_listener_set_enabled(&pEngine->listeners[listenerIndex], isEnabled);
  62313. }
  62314. MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex)
  62315. {
  62316. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  62317. return MA_FALSE;
  62318. }
  62319. return ma_spatializer_listener_is_enabled(&pEngine->listeners[listenerIndex]);
  62320. }
  62321. #ifndef MA_NO_RESOURCE_MANAGER
  62322. MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex)
  62323. {
  62324. ma_result result = MA_SUCCESS;
  62325. ma_sound_inlined* pSound = NULL;
  62326. ma_sound_inlined* pNextSound = NULL;
  62327. if (pEngine == NULL || pFilePath == NULL) {
  62328. return MA_INVALID_ARGS;
  62329. }
  62330. /* Attach to the endpoint node if nothing is specicied. */
  62331. if (pNode == NULL) {
  62332. pNode = ma_node_graph_get_endpoint(&pEngine->nodeGraph);
  62333. nodeInputBusIndex = 0;
  62334. }
  62335. /*
  62336. We want to check if we can recycle an already-allocated inlined sound. Since this is just a
  62337. helper I'm not *too* concerned about performance here and I'm happy to use a lock to keep
  62338. the implementation simple. Maybe this can be optimized later if there's enough demand, but
  62339. if this function is being used it probably means the caller doesn't really care too much.
  62340. What we do is check the atEnd flag. When this is true, we can recycle the sound. Otherwise
  62341. we just keep iterating. If we reach the end without finding a sound to recycle we just
  62342. allocate a new one. This doesn't scale well for a massive number of sounds being played
  62343. simultaneously as we don't ever actually free the sound objects. Some kind of garbage
  62344. collection routine might be valuable for this which I'll think about.
  62345. */
  62346. ma_spinlock_lock(&pEngine->inlinedSoundLock);
  62347. {
  62348. ma_uint32 soundFlags = 0;
  62349. for (pNextSound = pEngine->pInlinedSoundHead; pNextSound != NULL; pNextSound = pNextSound->pNext) {
  62350. if (ma_sound_at_end(&pNextSound->sound)) {
  62351. /*
  62352. The sound is at the end which means it's available for recycling. All we need to do
  62353. is uninitialize it and reinitialize it. All we're doing is recycling memory.
  62354. */
  62355. pSound = pNextSound;
  62356. ma_atomic_fetch_sub_32(&pEngine->inlinedSoundCount, 1);
  62357. break;
  62358. }
  62359. }
  62360. if (pSound != NULL) {
  62361. /*
  62362. We actually want to detach the sound from the list here. The reason is because we want the sound
  62363. to be in a consistent state at the non-recycled case to simplify the logic below.
  62364. */
  62365. if (pEngine->pInlinedSoundHead == pSound) {
  62366. pEngine->pInlinedSoundHead = pSound->pNext;
  62367. }
  62368. if (pSound->pPrev != NULL) {
  62369. pSound->pPrev->pNext = pSound->pNext;
  62370. }
  62371. if (pSound->pNext != NULL) {
  62372. pSound->pNext->pPrev = pSound->pPrev;
  62373. }
  62374. /* Now the previous sound needs to be uninitialized. */
  62375. ma_sound_uninit(&pNextSound->sound);
  62376. } else {
  62377. /* No sound available for recycling. Allocate one now. */
  62378. pSound = (ma_sound_inlined*)ma_malloc(sizeof(*pSound), &pEngine->allocationCallbacks);
  62379. }
  62380. if (pSound != NULL) { /* Safety check for the allocation above. */
  62381. /*
  62382. At this point we should have memory allocated for the inlined sound. We just need
  62383. to initialize it like a normal sound now.
  62384. */
  62385. 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. */
  62386. 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. */
  62387. soundFlags |= MA_SOUND_FLAG_NO_PITCH; /* Pitching isn't usable with inlined sounds, so disable it to save on speed. */
  62388. 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. */
  62389. result = ma_sound_init_from_file(pEngine, pFilePath, soundFlags, NULL, NULL, &pSound->sound);
  62390. if (result == MA_SUCCESS) {
  62391. /* Now attach the sound to the graph. */
  62392. result = ma_node_attach_output_bus(pSound, 0, pNode, nodeInputBusIndex);
  62393. if (result == MA_SUCCESS) {
  62394. /* 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. */
  62395. pSound->pNext = pEngine->pInlinedSoundHead;
  62396. pSound->pPrev = NULL;
  62397. pEngine->pInlinedSoundHead = pSound; /* <-- This is what attaches the sound to the list. */
  62398. if (pSound->pNext != NULL) {
  62399. pSound->pNext->pPrev = pSound;
  62400. }
  62401. } else {
  62402. ma_free(pSound, &pEngine->allocationCallbacks);
  62403. }
  62404. } else {
  62405. ma_free(pSound, &pEngine->allocationCallbacks);
  62406. }
  62407. } else {
  62408. result = MA_OUT_OF_MEMORY;
  62409. }
  62410. }
  62411. ma_spinlock_unlock(&pEngine->inlinedSoundLock);
  62412. if (result != MA_SUCCESS) {
  62413. return result;
  62414. }
  62415. /* Finally we can start playing the sound. */
  62416. result = ma_sound_start(&pSound->sound);
  62417. if (result != MA_SUCCESS) {
  62418. /* Failed to start the sound. We need to mark it for recycling and return an error. */
  62419. ma_atomic_exchange_32(&pSound->sound.atEnd, MA_TRUE);
  62420. return result;
  62421. }
  62422. ma_atomic_fetch_add_32(&pEngine->inlinedSoundCount, 1);
  62423. return result;
  62424. }
  62425. MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup)
  62426. {
  62427. return ma_engine_play_sound_ex(pEngine, pFilePath, pGroup, 0);
  62428. }
  62429. #endif
  62430. static ma_result ma_sound_preinit(ma_engine* pEngine, ma_sound* pSound)
  62431. {
  62432. if (pSound == NULL) {
  62433. return MA_INVALID_ARGS;
  62434. }
  62435. MA_ZERO_OBJECT(pSound);
  62436. pSound->seekTarget = MA_SEEK_TARGET_NONE;
  62437. if (pEngine == NULL) {
  62438. return MA_INVALID_ARGS;
  62439. }
  62440. return MA_SUCCESS;
  62441. }
  62442. static ma_result ma_sound_init_from_data_source_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  62443. {
  62444. ma_result result;
  62445. ma_engine_node_config engineNodeConfig;
  62446. ma_engine_node_type type; /* Will be set to ma_engine_node_type_group if no data source is specified. */
  62447. /* Do not clear pSound to zero here - that's done at a higher level with ma_sound_preinit(). */
  62448. MA_ASSERT(pEngine != NULL);
  62449. MA_ASSERT(pSound != NULL);
  62450. if (pConfig == NULL) {
  62451. return MA_INVALID_ARGS;
  62452. }
  62453. pSound->pDataSource = pConfig->pDataSource;
  62454. if (pConfig->pDataSource != NULL) {
  62455. type = ma_engine_node_type_sound;
  62456. } else {
  62457. type = ma_engine_node_type_group;
  62458. }
  62459. /*
  62460. Sounds are engine nodes. Before we can initialize this we need to determine the channel count.
  62461. If we can't do this we need to abort. It's up to the caller to ensure they're using a data
  62462. source that provides this information upfront.
  62463. */
  62464. engineNodeConfig = ma_engine_node_config_init(pEngine, type, pConfig->flags);
  62465. engineNodeConfig.channelsIn = pConfig->channelsIn;
  62466. engineNodeConfig.channelsOut = pConfig->channelsOut;
  62467. engineNodeConfig.volumeSmoothTimeInPCMFrames = pConfig->volumeSmoothTimeInPCMFrames;
  62468. engineNodeConfig.monoExpansionMode = pConfig->monoExpansionMode;
  62469. if (engineNodeConfig.volumeSmoothTimeInPCMFrames == 0) {
  62470. engineNodeConfig.volumeSmoothTimeInPCMFrames = pEngine->defaultVolumeSmoothTimeInPCMFrames;
  62471. }
  62472. /* If we're loading from a data source the input channel count needs to be the data source's native channel count. */
  62473. if (pConfig->pDataSource != NULL) {
  62474. result = ma_data_source_get_data_format(pConfig->pDataSource, NULL, &engineNodeConfig.channelsIn, &engineNodeConfig.sampleRate, NULL, 0);
  62475. if (result != MA_SUCCESS) {
  62476. return result; /* Failed to retrieve the channel count. */
  62477. }
  62478. if (engineNodeConfig.channelsIn == 0) {
  62479. return MA_INVALID_OPERATION; /* Invalid channel count. */
  62480. }
  62481. if (engineNodeConfig.channelsOut == MA_SOUND_SOURCE_CHANNEL_COUNT) {
  62482. engineNodeConfig.channelsOut = engineNodeConfig.channelsIn;
  62483. }
  62484. }
  62485. /* Getting here means we should have a valid channel count and we can initialize the engine node. */
  62486. result = ma_engine_node_init(&engineNodeConfig, &pEngine->allocationCallbacks, &pSound->engineNode);
  62487. if (result != MA_SUCCESS) {
  62488. return result;
  62489. }
  62490. /* If no attachment is specified, attach the sound straight to the endpoint. */
  62491. if (pConfig->pInitialAttachment == NULL) {
  62492. /* No group. Attach straight to the endpoint by default, unless the caller has requested that it not. */
  62493. if ((pConfig->flags & MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT) == 0) {
  62494. result = ma_node_attach_output_bus(pSound, 0, ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0);
  62495. }
  62496. } else {
  62497. /* 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. */
  62498. result = ma_node_attach_output_bus(pSound, 0, pConfig->pInitialAttachment, pConfig->initialAttachmentInputBusIndex);
  62499. }
  62500. if (result != MA_SUCCESS) {
  62501. ma_engine_node_uninit(&pSound->engineNode, &pEngine->allocationCallbacks);
  62502. return result;
  62503. }
  62504. /* Apply initial range and looping state to the data source if applicable. */
  62505. if (pConfig->rangeBegInPCMFrames != 0 || pConfig->rangeEndInPCMFrames != ~((ma_uint64)0)) {
  62506. ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  62507. }
  62508. if (pConfig->loopPointBegInPCMFrames != 0 || pConfig->loopPointEndInPCMFrames != ~((ma_uint64)0)) {
  62509. ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  62510. }
  62511. ma_sound_set_looping(pSound, pConfig->isLooping);
  62512. return MA_SUCCESS;
  62513. }
  62514. #ifndef MA_NO_RESOURCE_MANAGER
  62515. MA_API ma_result ma_sound_init_from_file_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  62516. {
  62517. ma_result result = MA_SUCCESS;
  62518. ma_uint32 flags;
  62519. ma_sound_config config;
  62520. ma_resource_manager_pipeline_notifications notifications;
  62521. /*
  62522. The engine requires knowledge of the channel count of the underlying data source before it can
  62523. initialize the sound. Therefore, we need to make the resource manager wait until initialization
  62524. of the underlying data source to be initialized so we can get access to the channel count. To
  62525. do this, the MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT is forced.
  62526. Because we're initializing the data source before the sound, there's a chance the notification
  62527. will get triggered before this function returns. This is OK, so long as the caller is aware of
  62528. it and can avoid accessing the sound from within the notification.
  62529. */
  62530. flags = pConfig->flags | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT;
  62531. pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks);
  62532. if (pSound->pResourceManagerDataSource == NULL) {
  62533. return MA_OUT_OF_MEMORY;
  62534. }
  62535. /* Removed in 0.12. Set pDoneFence on the notifications. */
  62536. notifications = pConfig->initNotifications;
  62537. if (pConfig->pDoneFence != NULL && notifications.done.pFence == NULL) {
  62538. notifications.done.pFence = pConfig->pDoneFence;
  62539. }
  62540. /*
  62541. We must wrap everything around the fence if one was specified. This ensures ma_fence_wait() does
  62542. not return prematurely before the sound has finished initializing.
  62543. */
  62544. if (notifications.done.pFence) { ma_fence_acquire(notifications.done.pFence); }
  62545. {
  62546. ma_resource_manager_data_source_config resourceManagerDataSourceConfig = ma_resource_manager_data_source_config_init();
  62547. resourceManagerDataSourceConfig.pFilePath = pConfig->pFilePath;
  62548. resourceManagerDataSourceConfig.pFilePathW = pConfig->pFilePathW;
  62549. resourceManagerDataSourceConfig.flags = flags;
  62550. resourceManagerDataSourceConfig.pNotifications = &notifications;
  62551. resourceManagerDataSourceConfig.initialSeekPointInPCMFrames = pConfig->initialSeekPointInPCMFrames;
  62552. resourceManagerDataSourceConfig.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames;
  62553. resourceManagerDataSourceConfig.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames;
  62554. resourceManagerDataSourceConfig.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames;
  62555. resourceManagerDataSourceConfig.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames;
  62556. resourceManagerDataSourceConfig.isLooping = pConfig->isLooping;
  62557. result = ma_resource_manager_data_source_init_ex(pEngine->pResourceManager, &resourceManagerDataSourceConfig, pSound->pResourceManagerDataSource);
  62558. if (result != MA_SUCCESS) {
  62559. goto done;
  62560. }
  62561. pSound->ownsDataSource = MA_TRUE; /* <-- Important. Not setting this will result in the resource manager data source never getting uninitialized. */
  62562. /* We need to use a slightly customized version of the config so we'll need to make a copy. */
  62563. config = *pConfig;
  62564. config.pFilePath = NULL;
  62565. config.pFilePathW = NULL;
  62566. config.pDataSource = pSound->pResourceManagerDataSource;
  62567. result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound);
  62568. if (result != MA_SUCCESS) {
  62569. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  62570. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  62571. MA_ZERO_OBJECT(pSound);
  62572. goto done;
  62573. }
  62574. }
  62575. done:
  62576. if (notifications.done.pFence) { ma_fence_release(notifications.done.pFence); }
  62577. return result;
  62578. }
  62579. 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)
  62580. {
  62581. ma_sound_config config;
  62582. if (pFilePath == NULL) {
  62583. return MA_INVALID_ARGS;
  62584. }
  62585. config = ma_sound_config_init_2(pEngine);
  62586. config.pFilePath = pFilePath;
  62587. config.flags = flags;
  62588. config.pInitialAttachment = pGroup;
  62589. config.pDoneFence = pDoneFence;
  62590. return ma_sound_init_ex(pEngine, &config, pSound);
  62591. }
  62592. 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)
  62593. {
  62594. ma_sound_config config;
  62595. if (pFilePath == NULL) {
  62596. return MA_INVALID_ARGS;
  62597. }
  62598. config = ma_sound_config_init_2(pEngine);
  62599. config.pFilePathW = pFilePath;
  62600. config.flags = flags;
  62601. config.pInitialAttachment = pGroup;
  62602. config.pDoneFence = pDoneFence;
  62603. return ma_sound_init_ex(pEngine, &config, pSound);
  62604. }
  62605. 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)
  62606. {
  62607. ma_result result;
  62608. ma_sound_config config;
  62609. result = ma_sound_preinit(pEngine, pSound);
  62610. if (result != MA_SUCCESS) {
  62611. return result;
  62612. }
  62613. if (pExistingSound == NULL) {
  62614. return MA_INVALID_ARGS;
  62615. }
  62616. /* Cloning only works for data buffers (not streams) that are loaded from the resource manager. */
  62617. if (pExistingSound->pResourceManagerDataSource == NULL) {
  62618. return MA_INVALID_OPERATION;
  62619. }
  62620. /*
  62621. We need to make a clone of the data source. If the data source is not a data buffer (i.e. a stream)
  62622. this will fail.
  62623. */
  62624. pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks);
  62625. if (pSound->pResourceManagerDataSource == NULL) {
  62626. return MA_OUT_OF_MEMORY;
  62627. }
  62628. result = ma_resource_manager_data_source_init_copy(pEngine->pResourceManager, pExistingSound->pResourceManagerDataSource, pSound->pResourceManagerDataSource);
  62629. if (result != MA_SUCCESS) {
  62630. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  62631. return result;
  62632. }
  62633. config = ma_sound_config_init_2(pEngine);
  62634. config.pDataSource = pSound->pResourceManagerDataSource;
  62635. config.flags = flags;
  62636. config.pInitialAttachment = pGroup;
  62637. config.monoExpansionMode = pExistingSound->engineNode.monoExpansionMode;
  62638. config.volumeSmoothTimeInPCMFrames = pExistingSound->engineNode.volumeSmoothTimeInPCMFrames;
  62639. result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound);
  62640. if (result != MA_SUCCESS) {
  62641. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  62642. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  62643. MA_ZERO_OBJECT(pSound);
  62644. return result;
  62645. }
  62646. /* Make sure the sound is marked as the owner of the data source or else it will never get uninitialized. */
  62647. pSound->ownsDataSource = MA_TRUE;
  62648. return MA_SUCCESS;
  62649. }
  62650. #endif
  62651. 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)
  62652. {
  62653. ma_sound_config config = ma_sound_config_init_2(pEngine);
  62654. config.pDataSource = pDataSource;
  62655. config.flags = flags;
  62656. config.pInitialAttachment = pGroup;
  62657. return ma_sound_init_ex(pEngine, &config, pSound);
  62658. }
  62659. MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  62660. {
  62661. ma_result result;
  62662. result = ma_sound_preinit(pEngine, pSound);
  62663. if (result != MA_SUCCESS) {
  62664. return result;
  62665. }
  62666. if (pConfig == NULL) {
  62667. return MA_INVALID_ARGS;
  62668. }
  62669. pSound->endCallback = pConfig->endCallback;
  62670. pSound->pEndCallbackUserData = pConfig->pEndCallbackUserData;
  62671. /* We need to load the sound differently depending on whether or not we're loading from a file. */
  62672. #ifndef MA_NO_RESOURCE_MANAGER
  62673. if (pConfig->pFilePath != NULL || pConfig->pFilePathW != NULL) {
  62674. return ma_sound_init_from_file_internal(pEngine, pConfig, pSound);
  62675. } else
  62676. #endif
  62677. {
  62678. /*
  62679. Getting here means we're not loading from a file. We may be loading from an already-initialized
  62680. data source, or none at all. If we aren't specifying any data source, we'll be initializing the
  62681. the equivalent to a group. ma_data_source_init_from_data_source_internal() will deal with this
  62682. for us, so no special treatment required here.
  62683. */
  62684. return ma_sound_init_from_data_source_internal(pEngine, pConfig, pSound);
  62685. }
  62686. }
  62687. MA_API void ma_sound_uninit(ma_sound* pSound)
  62688. {
  62689. if (pSound == NULL) {
  62690. return;
  62691. }
  62692. /*
  62693. Always uninitialize the node first. This ensures it's detached from the graph and does not return until it has done
  62694. so which makes thread safety beyond this point trivial.
  62695. */
  62696. ma_engine_node_uninit(&pSound->engineNode, &pSound->engineNode.pEngine->allocationCallbacks);
  62697. /* 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. */
  62698. #ifndef MA_NO_RESOURCE_MANAGER
  62699. if (pSound->ownsDataSource) {
  62700. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  62701. ma_free(pSound->pResourceManagerDataSource, &pSound->engineNode.pEngine->allocationCallbacks);
  62702. pSound->pDataSource = NULL;
  62703. }
  62704. #else
  62705. MA_ASSERT(pSound->ownsDataSource == MA_FALSE);
  62706. #endif
  62707. }
  62708. MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound)
  62709. {
  62710. if (pSound == NULL) {
  62711. return NULL;
  62712. }
  62713. return pSound->engineNode.pEngine;
  62714. }
  62715. MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound)
  62716. {
  62717. if (pSound == NULL) {
  62718. return NULL;
  62719. }
  62720. return pSound->pDataSource;
  62721. }
  62722. MA_API ma_result ma_sound_start(ma_sound* pSound)
  62723. {
  62724. if (pSound == NULL) {
  62725. return MA_INVALID_ARGS;
  62726. }
  62727. /* If the sound is already playing, do nothing. */
  62728. if (ma_sound_is_playing(pSound)) {
  62729. return MA_SUCCESS;
  62730. }
  62731. /* If the sound is at the end it means we want to start from the start again. */
  62732. if (ma_sound_at_end(pSound)) {
  62733. ma_result result = ma_data_source_seek_to_pcm_frame(pSound->pDataSource, 0);
  62734. if (result != MA_SUCCESS && result != MA_NOT_IMPLEMENTED) {
  62735. return result; /* Failed to seek back to the start. */
  62736. }
  62737. /* Make sure we clear the end indicator. */
  62738. ma_atomic_exchange_32(&pSound->atEnd, MA_FALSE);
  62739. }
  62740. /* Make sure the sound is started. If there's a start delay, the sound won't actually start until the start time is reached. */
  62741. ma_node_set_state(pSound, ma_node_state_started);
  62742. return MA_SUCCESS;
  62743. }
  62744. MA_API ma_result ma_sound_stop(ma_sound* pSound)
  62745. {
  62746. if (pSound == NULL) {
  62747. return MA_INVALID_ARGS;
  62748. }
  62749. /* This will stop the sound immediately. Use ma_sound_set_stop_time() to stop the sound at a specific time. */
  62750. ma_node_set_state(pSound, ma_node_state_stopped);
  62751. return MA_SUCCESS;
  62752. }
  62753. MA_API ma_result ma_sound_stop_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 fadeLengthInFrames)
  62754. {
  62755. if (pSound == NULL) {
  62756. return MA_INVALID_ARGS;
  62757. }
  62758. /* Stopping with a fade out requires us to schedule the stop into the future by the fade length. */
  62759. ma_sound_set_stop_time_with_fade_in_pcm_frames(pSound, ma_engine_get_time_in_pcm_frames(ma_sound_get_engine(pSound)) + fadeLengthInFrames, fadeLengthInFrames);
  62760. return MA_SUCCESS;
  62761. }
  62762. MA_API ma_result ma_sound_stop_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 fadeLengthInMilliseconds)
  62763. {
  62764. ma_uint64 sampleRate;
  62765. if (pSound == NULL) {
  62766. return MA_INVALID_ARGS;
  62767. }
  62768. sampleRate = ma_engine_get_sample_rate(ma_sound_get_engine(pSound));
  62769. return ma_sound_stop_with_fade_in_pcm_frames(pSound, (fadeLengthInMilliseconds * sampleRate) / 1000);
  62770. }
  62771. MA_API void ma_sound_set_volume(ma_sound* pSound, float volume)
  62772. {
  62773. if (pSound == NULL) {
  62774. return;
  62775. }
  62776. ma_engine_node_set_volume(&pSound->engineNode, volume);
  62777. }
  62778. MA_API float ma_sound_get_volume(const ma_sound* pSound)
  62779. {
  62780. float volume = 0;
  62781. if (pSound == NULL) {
  62782. return 0;
  62783. }
  62784. ma_engine_node_get_volume(&pSound->engineNode, &volume);
  62785. return volume;
  62786. }
  62787. MA_API void ma_sound_set_pan(ma_sound* pSound, float pan)
  62788. {
  62789. if (pSound == NULL) {
  62790. return;
  62791. }
  62792. ma_panner_set_pan(&pSound->engineNode.panner, pan);
  62793. }
  62794. MA_API float ma_sound_get_pan(const ma_sound* pSound)
  62795. {
  62796. if (pSound == NULL) {
  62797. return 0;
  62798. }
  62799. return ma_panner_get_pan(&pSound->engineNode.panner);
  62800. }
  62801. MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode)
  62802. {
  62803. if (pSound == NULL) {
  62804. return;
  62805. }
  62806. ma_panner_set_mode(&pSound->engineNode.panner, panMode);
  62807. }
  62808. MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound)
  62809. {
  62810. if (pSound == NULL) {
  62811. return ma_pan_mode_balance;
  62812. }
  62813. return ma_panner_get_mode(&pSound->engineNode.panner);
  62814. }
  62815. MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch)
  62816. {
  62817. if (pSound == NULL) {
  62818. return;
  62819. }
  62820. if (pitch <= 0) {
  62821. return;
  62822. }
  62823. ma_atomic_exchange_explicit_f32(&pSound->engineNode.pitch, pitch, ma_atomic_memory_order_release);
  62824. }
  62825. MA_API float ma_sound_get_pitch(const ma_sound* pSound)
  62826. {
  62827. if (pSound == NULL) {
  62828. return 0;
  62829. }
  62830. return ma_atomic_load_f32(&pSound->engineNode.pitch); /* Naughty const-cast for this. */
  62831. }
  62832. MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled)
  62833. {
  62834. if (pSound == NULL) {
  62835. return;
  62836. }
  62837. ma_atomic_exchange_explicit_32(&pSound->engineNode.isSpatializationDisabled, !enabled, ma_atomic_memory_order_release);
  62838. }
  62839. MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound)
  62840. {
  62841. if (pSound == NULL) {
  62842. return MA_FALSE;
  62843. }
  62844. return ma_engine_node_is_spatialization_enabled(&pSound->engineNode);
  62845. }
  62846. MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex)
  62847. {
  62848. if (pSound == NULL || listenerIndex >= ma_engine_get_listener_count(ma_sound_get_engine(pSound))) {
  62849. return;
  62850. }
  62851. ma_atomic_exchange_explicit_32(&pSound->engineNode.pinnedListenerIndex, listenerIndex, ma_atomic_memory_order_release);
  62852. }
  62853. MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound)
  62854. {
  62855. if (pSound == NULL) {
  62856. return MA_LISTENER_INDEX_CLOSEST;
  62857. }
  62858. return ma_atomic_load_explicit_32(&pSound->engineNode.pinnedListenerIndex, ma_atomic_memory_order_acquire);
  62859. }
  62860. MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound)
  62861. {
  62862. ma_uint32 listenerIndex;
  62863. if (pSound == NULL) {
  62864. return 0;
  62865. }
  62866. listenerIndex = ma_sound_get_pinned_listener_index(pSound);
  62867. if (listenerIndex == MA_LISTENER_INDEX_CLOSEST) {
  62868. ma_vec3f position = ma_sound_get_position(pSound);
  62869. return ma_engine_find_closest_listener(ma_sound_get_engine(pSound), position.x, position.y, position.z);
  62870. }
  62871. return listenerIndex;
  62872. }
  62873. MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound)
  62874. {
  62875. ma_vec3f relativePos;
  62876. ma_engine* pEngine;
  62877. if (pSound == NULL) {
  62878. return ma_vec3f_init_3f(0, 0, -1);
  62879. }
  62880. pEngine = ma_sound_get_engine(pSound);
  62881. if (pEngine == NULL) {
  62882. return ma_vec3f_init_3f(0, 0, -1);
  62883. }
  62884. ma_spatializer_get_relative_position_and_direction(&pSound->engineNode.spatializer, &pEngine->listeners[ma_sound_get_listener_index(pSound)], &relativePos, NULL);
  62885. return ma_vec3f_normalize(ma_vec3f_neg(relativePos));
  62886. }
  62887. MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z)
  62888. {
  62889. if (pSound == NULL) {
  62890. return;
  62891. }
  62892. ma_spatializer_set_position(&pSound->engineNode.spatializer, x, y, z);
  62893. }
  62894. MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound)
  62895. {
  62896. if (pSound == NULL) {
  62897. return ma_vec3f_init_3f(0, 0, 0);
  62898. }
  62899. return ma_spatializer_get_position(&pSound->engineNode.spatializer);
  62900. }
  62901. MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z)
  62902. {
  62903. if (pSound == NULL) {
  62904. return;
  62905. }
  62906. ma_spatializer_set_direction(&pSound->engineNode.spatializer, x, y, z);
  62907. }
  62908. MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound)
  62909. {
  62910. if (pSound == NULL) {
  62911. return ma_vec3f_init_3f(0, 0, 0);
  62912. }
  62913. return ma_spatializer_get_direction(&pSound->engineNode.spatializer);
  62914. }
  62915. MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z)
  62916. {
  62917. if (pSound == NULL) {
  62918. return;
  62919. }
  62920. ma_spatializer_set_velocity(&pSound->engineNode.spatializer, x, y, z);
  62921. }
  62922. MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound)
  62923. {
  62924. if (pSound == NULL) {
  62925. return ma_vec3f_init_3f(0, 0, 0);
  62926. }
  62927. return ma_spatializer_get_velocity(&pSound->engineNode.spatializer);
  62928. }
  62929. MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel)
  62930. {
  62931. if (pSound == NULL) {
  62932. return;
  62933. }
  62934. ma_spatializer_set_attenuation_model(&pSound->engineNode.spatializer, attenuationModel);
  62935. }
  62936. MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound)
  62937. {
  62938. if (pSound == NULL) {
  62939. return ma_attenuation_model_none;
  62940. }
  62941. return ma_spatializer_get_attenuation_model(&pSound->engineNode.spatializer);
  62942. }
  62943. MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning)
  62944. {
  62945. if (pSound == NULL) {
  62946. return;
  62947. }
  62948. ma_spatializer_set_positioning(&pSound->engineNode.spatializer, positioning);
  62949. }
  62950. MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound)
  62951. {
  62952. if (pSound == NULL) {
  62953. return ma_positioning_absolute;
  62954. }
  62955. return ma_spatializer_get_positioning(&pSound->engineNode.spatializer);
  62956. }
  62957. MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff)
  62958. {
  62959. if (pSound == NULL) {
  62960. return;
  62961. }
  62962. ma_spatializer_set_rolloff(&pSound->engineNode.spatializer, rolloff);
  62963. }
  62964. MA_API float ma_sound_get_rolloff(const ma_sound* pSound)
  62965. {
  62966. if (pSound == NULL) {
  62967. return 0;
  62968. }
  62969. return ma_spatializer_get_rolloff(&pSound->engineNode.spatializer);
  62970. }
  62971. MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain)
  62972. {
  62973. if (pSound == NULL) {
  62974. return;
  62975. }
  62976. ma_spatializer_set_min_gain(&pSound->engineNode.spatializer, minGain);
  62977. }
  62978. MA_API float ma_sound_get_min_gain(const ma_sound* pSound)
  62979. {
  62980. if (pSound == NULL) {
  62981. return 0;
  62982. }
  62983. return ma_spatializer_get_min_gain(&pSound->engineNode.spatializer);
  62984. }
  62985. MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain)
  62986. {
  62987. if (pSound == NULL) {
  62988. return;
  62989. }
  62990. ma_spatializer_set_max_gain(&pSound->engineNode.spatializer, maxGain);
  62991. }
  62992. MA_API float ma_sound_get_max_gain(const ma_sound* pSound)
  62993. {
  62994. if (pSound == NULL) {
  62995. return 0;
  62996. }
  62997. return ma_spatializer_get_max_gain(&pSound->engineNode.spatializer);
  62998. }
  62999. MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance)
  63000. {
  63001. if (pSound == NULL) {
  63002. return;
  63003. }
  63004. ma_spatializer_set_min_distance(&pSound->engineNode.spatializer, minDistance);
  63005. }
  63006. MA_API float ma_sound_get_min_distance(const ma_sound* pSound)
  63007. {
  63008. if (pSound == NULL) {
  63009. return 0;
  63010. }
  63011. return ma_spatializer_get_min_distance(&pSound->engineNode.spatializer);
  63012. }
  63013. MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance)
  63014. {
  63015. if (pSound == NULL) {
  63016. return;
  63017. }
  63018. ma_spatializer_set_max_distance(&pSound->engineNode.spatializer, maxDistance);
  63019. }
  63020. MA_API float ma_sound_get_max_distance(const ma_sound* pSound)
  63021. {
  63022. if (pSound == NULL) {
  63023. return 0;
  63024. }
  63025. return ma_spatializer_get_max_distance(&pSound->engineNode.spatializer);
  63026. }
  63027. MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  63028. {
  63029. if (pSound == NULL) {
  63030. return;
  63031. }
  63032. ma_spatializer_set_cone(&pSound->engineNode.spatializer, innerAngleInRadians, outerAngleInRadians, outerGain);
  63033. }
  63034. MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  63035. {
  63036. if (pInnerAngleInRadians != NULL) {
  63037. *pInnerAngleInRadians = 0;
  63038. }
  63039. if (pOuterAngleInRadians != NULL) {
  63040. *pOuterAngleInRadians = 0;
  63041. }
  63042. if (pOuterGain != NULL) {
  63043. *pOuterGain = 0;
  63044. }
  63045. if (pSound == NULL) {
  63046. return;
  63047. }
  63048. ma_spatializer_get_cone(&pSound->engineNode.spatializer, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  63049. }
  63050. MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor)
  63051. {
  63052. if (pSound == NULL) {
  63053. return;
  63054. }
  63055. ma_spatializer_set_doppler_factor(&pSound->engineNode.spatializer, dopplerFactor);
  63056. }
  63057. MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound)
  63058. {
  63059. if (pSound == NULL) {
  63060. return 0;
  63061. }
  63062. return ma_spatializer_get_doppler_factor(&pSound->engineNode.spatializer);
  63063. }
  63064. MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor)
  63065. {
  63066. if (pSound == NULL) {
  63067. return;
  63068. }
  63069. ma_spatializer_set_directional_attenuation_factor(&pSound->engineNode.spatializer, directionalAttenuationFactor);
  63070. }
  63071. MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound)
  63072. {
  63073. if (pSound == NULL) {
  63074. return 1;
  63075. }
  63076. return ma_spatializer_get_directional_attenuation_factor(&pSound->engineNode.spatializer);
  63077. }
  63078. MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames)
  63079. {
  63080. if (pSound == NULL) {
  63081. return;
  63082. }
  63083. ma_sound_set_fade_start_in_pcm_frames(pSound, volumeBeg, volumeEnd, fadeLengthInFrames, (~(ma_uint64)0));
  63084. }
  63085. MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds)
  63086. {
  63087. if (pSound == NULL) {
  63088. return;
  63089. }
  63090. ma_sound_set_fade_in_pcm_frames(pSound, volumeBeg, volumeEnd, (fadeLengthInMilliseconds * pSound->engineNode.fader.config.sampleRate) / 1000);
  63091. }
  63092. MA_API void ma_sound_set_fade_start_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames, ma_uint64 absoluteGlobalTimeInFrames)
  63093. {
  63094. if (pSound == NULL) {
  63095. return;
  63096. }
  63097. /*
  63098. We don't want to update the fader at this point because we need to use the engine's current time
  63099. to derive the fader's start offset. The timer is being updated on the audio thread so in order to
  63100. do this as accurately as possible we'll need to defer this to the audio thread.
  63101. */
  63102. ma_atomic_float_set(&pSound->engineNode.fadeSettings.volumeBeg, volumeBeg);
  63103. ma_atomic_float_set(&pSound->engineNode.fadeSettings.volumeEnd, volumeEnd);
  63104. ma_atomic_uint64_set(&pSound->engineNode.fadeSettings.fadeLengthInFrames, fadeLengthInFrames);
  63105. ma_atomic_uint64_set(&pSound->engineNode.fadeSettings.absoluteGlobalTimeInFrames, absoluteGlobalTimeInFrames);
  63106. }
  63107. MA_API void ma_sound_set_fade_start_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63108. {
  63109. ma_uint32 sampleRate;
  63110. if (pSound == NULL) {
  63111. return;
  63112. }
  63113. sampleRate = ma_engine_get_sample_rate(ma_sound_get_engine(pSound));
  63114. ma_sound_set_fade_start_in_pcm_frames(pSound, volumeBeg, volumeEnd, (fadeLengthInMilliseconds * sampleRate) / 1000, (absoluteGlobalTimeInMilliseconds * sampleRate) / 1000);
  63115. }
  63116. MA_API float ma_sound_get_current_fade_volume(const ma_sound* pSound)
  63117. {
  63118. if (pSound == NULL) {
  63119. return MA_INVALID_ARGS;
  63120. }
  63121. return ma_fader_get_current_volume(&pSound->engineNode.fader);
  63122. }
  63123. MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames)
  63124. {
  63125. if (pSound == NULL) {
  63126. return;
  63127. }
  63128. ma_node_set_state_time(pSound, ma_node_state_started, absoluteGlobalTimeInFrames);
  63129. }
  63130. MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63131. {
  63132. if (pSound == NULL) {
  63133. return;
  63134. }
  63135. ma_sound_set_start_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000);
  63136. }
  63137. MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames)
  63138. {
  63139. if (pSound == NULL) {
  63140. return;
  63141. }
  63142. ma_sound_set_stop_time_with_fade_in_pcm_frames(pSound, absoluteGlobalTimeInFrames, 0);
  63143. }
  63144. MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63145. {
  63146. if (pSound == NULL) {
  63147. return;
  63148. }
  63149. ma_sound_set_stop_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000);
  63150. }
  63151. MA_API void ma_sound_set_stop_time_with_fade_in_pcm_frames(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInFrames, ma_uint64 fadeLengthInFrames)
  63152. {
  63153. if (pSound == NULL) {
  63154. return;
  63155. }
  63156. if (fadeLengthInFrames > 0) {
  63157. if (fadeLengthInFrames > stopAbsoluteGlobalTimeInFrames) {
  63158. fadeLengthInFrames = stopAbsoluteGlobalTimeInFrames;
  63159. }
  63160. ma_sound_set_fade_start_in_pcm_frames(pSound, -1, 0, fadeLengthInFrames, stopAbsoluteGlobalTimeInFrames - fadeLengthInFrames);
  63161. }
  63162. ma_node_set_state_time(pSound, ma_node_state_stopped, stopAbsoluteGlobalTimeInFrames);
  63163. }
  63164. MA_API void ma_sound_set_stop_time_with_fade_in_milliseconds(ma_sound* pSound, ma_uint64 stopAbsoluteGlobalTimeInMilliseconds, ma_uint64 fadeLengthInMilliseconds)
  63165. {
  63166. ma_uint32 sampleRate;
  63167. if (pSound == NULL) {
  63168. return;
  63169. }
  63170. sampleRate = ma_engine_get_sample_rate(ma_sound_get_engine(pSound));
  63171. ma_sound_set_stop_time_with_fade_in_pcm_frames(pSound, (stopAbsoluteGlobalTimeInMilliseconds * sampleRate) / 1000, (fadeLengthInMilliseconds * sampleRate) / 1000);
  63172. }
  63173. MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound)
  63174. {
  63175. if (pSound == NULL) {
  63176. return MA_FALSE;
  63177. }
  63178. return ma_node_get_state_by_time(pSound, ma_engine_get_time_in_pcm_frames(ma_sound_get_engine(pSound))) == ma_node_state_started;
  63179. }
  63180. MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound)
  63181. {
  63182. if (pSound == NULL) {
  63183. return 0;
  63184. }
  63185. return ma_node_get_time(pSound);
  63186. }
  63187. MA_API ma_uint64 ma_sound_get_time_in_milliseconds(const ma_sound* pSound)
  63188. {
  63189. return ma_sound_get_time_in_pcm_frames(pSound) * 1000 / ma_engine_get_sample_rate(ma_sound_get_engine(pSound));
  63190. }
  63191. MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping)
  63192. {
  63193. if (pSound == NULL) {
  63194. return;
  63195. }
  63196. /* Looping is only a valid concept if the sound is backed by a data source. */
  63197. if (pSound->pDataSource == NULL) {
  63198. return;
  63199. }
  63200. /* The looping state needs to be applied to the data source in order for any looping to actually happen. */
  63201. ma_data_source_set_looping(pSound->pDataSource, isLooping);
  63202. }
  63203. MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound)
  63204. {
  63205. if (pSound == NULL) {
  63206. return MA_FALSE;
  63207. }
  63208. /* There is no notion of looping for sounds that are not backed by a data source. */
  63209. if (pSound->pDataSource == NULL) {
  63210. return MA_FALSE;
  63211. }
  63212. return ma_data_source_is_looping(pSound->pDataSource);
  63213. }
  63214. MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound)
  63215. {
  63216. if (pSound == NULL) {
  63217. return MA_FALSE;
  63218. }
  63219. /* There is no notion of an end of a sound if it's not backed by a data source. */
  63220. if (pSound->pDataSource == NULL) {
  63221. return MA_FALSE;
  63222. }
  63223. return ma_sound_get_at_end(pSound);
  63224. }
  63225. MA_API ma_result ma_sound_seek_to_pcm_frame(ma_sound* pSound, ma_uint64 frameIndex)
  63226. {
  63227. if (pSound == NULL) {
  63228. return MA_INVALID_ARGS;
  63229. }
  63230. /* Seeking is only valid for sounds that are backed by a data source. */
  63231. if (pSound->pDataSource == NULL) {
  63232. return MA_INVALID_OPERATION;
  63233. }
  63234. /* 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. */
  63235. ma_atomic_exchange_64(&pSound->seekTarget, frameIndex);
  63236. return MA_SUCCESS;
  63237. }
  63238. 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)
  63239. {
  63240. if (pSound == NULL) {
  63241. return MA_INVALID_ARGS;
  63242. }
  63243. /* The data format is retrieved directly from the data source if the sound is backed by one. Otherwise we pull it from the node. */
  63244. if (pSound->pDataSource == NULL) {
  63245. ma_uint32 channels;
  63246. if (pFormat != NULL) {
  63247. *pFormat = ma_format_f32;
  63248. }
  63249. channels = ma_node_get_input_channels(&pSound->engineNode, 0);
  63250. if (pChannels != NULL) {
  63251. *pChannels = channels;
  63252. }
  63253. if (pSampleRate != NULL) {
  63254. *pSampleRate = pSound->engineNode.resampler.config.sampleRateIn;
  63255. }
  63256. if (pChannelMap != NULL) {
  63257. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channels);
  63258. }
  63259. return MA_SUCCESS;
  63260. } else {
  63261. return ma_data_source_get_data_format(pSound->pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  63262. }
  63263. }
  63264. MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor)
  63265. {
  63266. ma_uint64 seekTarget;
  63267. if (pSound == NULL) {
  63268. return MA_INVALID_ARGS;
  63269. }
  63270. /* The notion of a cursor is only valid for sounds that are backed by a data source. */
  63271. if (pSound->pDataSource == NULL) {
  63272. return MA_INVALID_OPERATION;
  63273. }
  63274. seekTarget = ma_atomic_load_64(&pSound->seekTarget);
  63275. if (seekTarget != MA_SEEK_TARGET_NONE) {
  63276. *pCursor = seekTarget;
  63277. return MA_SUCCESS;
  63278. } else {
  63279. return ma_data_source_get_cursor_in_pcm_frames(pSound->pDataSource, pCursor);
  63280. }
  63281. }
  63282. MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength)
  63283. {
  63284. if (pSound == NULL) {
  63285. return MA_INVALID_ARGS;
  63286. }
  63287. /* The notion of a sound length is only valid for sounds that are backed by a data source. */
  63288. if (pSound->pDataSource == NULL) {
  63289. return MA_INVALID_OPERATION;
  63290. }
  63291. return ma_data_source_get_length_in_pcm_frames(pSound->pDataSource, pLength);
  63292. }
  63293. MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor)
  63294. {
  63295. ma_result result;
  63296. ma_uint64 cursorInPCMFrames;
  63297. ma_uint32 sampleRate;
  63298. if (pCursor != NULL) {
  63299. *pCursor = 0;
  63300. }
  63301. result = ma_sound_get_cursor_in_pcm_frames(pSound, &cursorInPCMFrames);
  63302. if (result != MA_SUCCESS) {
  63303. return result;
  63304. }
  63305. result = ma_sound_get_data_format(pSound, NULL, NULL, &sampleRate, NULL, 0);
  63306. if (result != MA_SUCCESS) {
  63307. return result;
  63308. }
  63309. /* 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. */
  63310. *pCursor = (ma_int64)cursorInPCMFrames / (float)sampleRate;
  63311. return MA_SUCCESS;
  63312. }
  63313. MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength)
  63314. {
  63315. if (pSound == NULL) {
  63316. return MA_INVALID_ARGS;
  63317. }
  63318. /* The notion of a sound length is only valid for sounds that are backed by a data source. */
  63319. if (pSound->pDataSource == NULL) {
  63320. return MA_INVALID_OPERATION;
  63321. }
  63322. return ma_data_source_get_length_in_seconds(pSound->pDataSource, pLength);
  63323. }
  63324. MA_API ma_result ma_sound_set_end_callback(ma_sound* pSound, ma_sound_end_proc callback, void* pUserData)
  63325. {
  63326. if (pSound == NULL) {
  63327. return MA_INVALID_ARGS;
  63328. }
  63329. /* The notion of an end is only valid for sounds that are backed by a data source. */
  63330. if (pSound->pDataSource == NULL) {
  63331. return MA_INVALID_OPERATION;
  63332. }
  63333. pSound->endCallback = callback;
  63334. pSound->pEndCallbackUserData = pUserData;
  63335. return MA_SUCCESS;
  63336. }
  63337. MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup)
  63338. {
  63339. ma_sound_group_config config = ma_sound_group_config_init_2(pEngine);
  63340. config.flags = flags;
  63341. config.pInitialAttachment = pParentGroup;
  63342. return ma_sound_group_init_ex(pEngine, &config, pGroup);
  63343. }
  63344. MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup)
  63345. {
  63346. ma_sound_config soundConfig;
  63347. if (pGroup == NULL) {
  63348. return MA_INVALID_ARGS;
  63349. }
  63350. MA_ZERO_OBJECT(pGroup);
  63351. if (pConfig == NULL) {
  63352. return MA_INVALID_ARGS;
  63353. }
  63354. /* A sound group is just a sound without a data source. */
  63355. soundConfig = *pConfig;
  63356. soundConfig.pFilePath = NULL;
  63357. soundConfig.pFilePathW = NULL;
  63358. soundConfig.pDataSource = NULL;
  63359. /*
  63360. Groups need to have spatialization disabled by default because I think it'll be pretty rare
  63361. that programs will want to spatialize groups (but not unheard of). Certainly it feels like
  63362. disabling this by default feels like the right option. Spatialization can be enabled with a
  63363. call to ma_sound_group_set_spatialization_enabled().
  63364. */
  63365. soundConfig.flags |= MA_SOUND_FLAG_NO_SPATIALIZATION;
  63366. return ma_sound_init_ex(pEngine, &soundConfig, pGroup);
  63367. }
  63368. MA_API void ma_sound_group_uninit(ma_sound_group* pGroup)
  63369. {
  63370. ma_sound_uninit(pGroup);
  63371. }
  63372. MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup)
  63373. {
  63374. return ma_sound_get_engine(pGroup);
  63375. }
  63376. MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup)
  63377. {
  63378. return ma_sound_start(pGroup);
  63379. }
  63380. MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup)
  63381. {
  63382. return ma_sound_stop(pGroup);
  63383. }
  63384. MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume)
  63385. {
  63386. ma_sound_set_volume(pGroup, volume);
  63387. }
  63388. MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup)
  63389. {
  63390. return ma_sound_get_volume(pGroup);
  63391. }
  63392. MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan)
  63393. {
  63394. ma_sound_set_pan(pGroup, pan);
  63395. }
  63396. MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup)
  63397. {
  63398. return ma_sound_get_pan(pGroup);
  63399. }
  63400. MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode)
  63401. {
  63402. ma_sound_set_pan_mode(pGroup, panMode);
  63403. }
  63404. MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup)
  63405. {
  63406. return ma_sound_get_pan_mode(pGroup);
  63407. }
  63408. MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch)
  63409. {
  63410. ma_sound_set_pitch(pGroup, pitch);
  63411. }
  63412. MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup)
  63413. {
  63414. return ma_sound_get_pitch(pGroup);
  63415. }
  63416. MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled)
  63417. {
  63418. ma_sound_set_spatialization_enabled(pGroup, enabled);
  63419. }
  63420. MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup)
  63421. {
  63422. return ma_sound_is_spatialization_enabled(pGroup);
  63423. }
  63424. MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex)
  63425. {
  63426. ma_sound_set_pinned_listener_index(pGroup, listenerIndex);
  63427. }
  63428. MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup)
  63429. {
  63430. return ma_sound_get_pinned_listener_index(pGroup);
  63431. }
  63432. MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup)
  63433. {
  63434. return ma_sound_get_listener_index(pGroup);
  63435. }
  63436. MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup)
  63437. {
  63438. return ma_sound_get_direction_to_listener(pGroup);
  63439. }
  63440. MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z)
  63441. {
  63442. ma_sound_set_position(pGroup, x, y, z);
  63443. }
  63444. MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup)
  63445. {
  63446. return ma_sound_get_position(pGroup);
  63447. }
  63448. MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z)
  63449. {
  63450. ma_sound_set_direction(pGroup, x, y, z);
  63451. }
  63452. MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup)
  63453. {
  63454. return ma_sound_get_direction(pGroup);
  63455. }
  63456. MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z)
  63457. {
  63458. ma_sound_set_velocity(pGroup, x, y, z);
  63459. }
  63460. MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup)
  63461. {
  63462. return ma_sound_get_velocity(pGroup);
  63463. }
  63464. MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel)
  63465. {
  63466. ma_sound_set_attenuation_model(pGroup, attenuationModel);
  63467. }
  63468. MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup)
  63469. {
  63470. return ma_sound_get_attenuation_model(pGroup);
  63471. }
  63472. MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning)
  63473. {
  63474. ma_sound_set_positioning(pGroup, positioning);
  63475. }
  63476. MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup)
  63477. {
  63478. return ma_sound_get_positioning(pGroup);
  63479. }
  63480. MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff)
  63481. {
  63482. ma_sound_set_rolloff(pGroup, rolloff);
  63483. }
  63484. MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup)
  63485. {
  63486. return ma_sound_get_rolloff(pGroup);
  63487. }
  63488. MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain)
  63489. {
  63490. ma_sound_set_min_gain(pGroup, minGain);
  63491. }
  63492. MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup)
  63493. {
  63494. return ma_sound_get_min_gain(pGroup);
  63495. }
  63496. MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain)
  63497. {
  63498. ma_sound_set_max_gain(pGroup, maxGain);
  63499. }
  63500. MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup)
  63501. {
  63502. return ma_sound_get_max_gain(pGroup);
  63503. }
  63504. MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance)
  63505. {
  63506. ma_sound_set_min_distance(pGroup, minDistance);
  63507. }
  63508. MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup)
  63509. {
  63510. return ma_sound_get_min_distance(pGroup);
  63511. }
  63512. MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance)
  63513. {
  63514. ma_sound_set_max_distance(pGroup, maxDistance);
  63515. }
  63516. MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup)
  63517. {
  63518. return ma_sound_get_max_distance(pGroup);
  63519. }
  63520. MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  63521. {
  63522. ma_sound_set_cone(pGroup, innerAngleInRadians, outerAngleInRadians, outerGain);
  63523. }
  63524. MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  63525. {
  63526. ma_sound_get_cone(pGroup, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  63527. }
  63528. MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor)
  63529. {
  63530. ma_sound_set_doppler_factor(pGroup, dopplerFactor);
  63531. }
  63532. MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup)
  63533. {
  63534. return ma_sound_get_doppler_factor(pGroup);
  63535. }
  63536. MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor)
  63537. {
  63538. ma_sound_set_directional_attenuation_factor(pGroup, directionalAttenuationFactor);
  63539. }
  63540. MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup)
  63541. {
  63542. return ma_sound_get_directional_attenuation_factor(pGroup);
  63543. }
  63544. MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames)
  63545. {
  63546. ma_sound_set_fade_in_pcm_frames(pGroup, volumeBeg, volumeEnd, fadeLengthInFrames);
  63547. }
  63548. MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds)
  63549. {
  63550. ma_sound_set_fade_in_milliseconds(pGroup, volumeBeg, volumeEnd, fadeLengthInMilliseconds);
  63551. }
  63552. MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup)
  63553. {
  63554. return ma_sound_get_current_fade_volume(pGroup);
  63555. }
  63556. MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames)
  63557. {
  63558. ma_sound_set_start_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames);
  63559. }
  63560. MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63561. {
  63562. ma_sound_set_start_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds);
  63563. }
  63564. MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames)
  63565. {
  63566. ma_sound_set_stop_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames);
  63567. }
  63568. MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds)
  63569. {
  63570. ma_sound_set_stop_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds);
  63571. }
  63572. MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup)
  63573. {
  63574. return ma_sound_is_playing(pGroup);
  63575. }
  63576. MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup)
  63577. {
  63578. return ma_sound_get_time_in_pcm_frames(pGroup);
  63579. }
  63580. #endif /* MA_NO_ENGINE */
  63581. /* END SECTION: miniaudio_engine.c */
  63582. /**************************************************************************************************************************************************************
  63583. ***************************************************************************************************************************************************************
  63584. Auto Generated
  63585. ==============
  63586. All code below is auto-generated from a tool. This mostly consists of decoding backend implementations such as ma_dr_wav, ma_dr_flac, etc. If you find a bug in the
  63587. code below please report the bug to the respective repository for the relevant project (probably dr_libs).
  63588. ***************************************************************************************************************************************************************
  63589. **************************************************************************************************************************************************************/
  63590. #if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
  63591. #if !defined(MA_DR_WAV_IMPLEMENTATION) && !defined(MA_DR_WAV_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  63592. /* dr_wav_c begin */
  63593. #ifndef ma_dr_wav_c
  63594. #define ma_dr_wav_c
  63595. #ifdef __MRC__
  63596. #pragma options opt off
  63597. #endif
  63598. #include <stdlib.h>
  63599. #include <string.h>
  63600. #include <limits.h>
  63601. #ifndef MA_DR_WAV_NO_STDIO
  63602. #include <stdio.h>
  63603. #ifndef MA_DR_WAV_NO_WCHAR
  63604. #include <wchar.h>
  63605. #endif
  63606. #endif
  63607. #ifndef MA_DR_WAV_ASSERT
  63608. #include <assert.h>
  63609. #define MA_DR_WAV_ASSERT(expression) assert(expression)
  63610. #endif
  63611. #ifndef MA_DR_WAV_MALLOC
  63612. #define MA_DR_WAV_MALLOC(sz) malloc((sz))
  63613. #endif
  63614. #ifndef MA_DR_WAV_REALLOC
  63615. #define MA_DR_WAV_REALLOC(p, sz) realloc((p), (sz))
  63616. #endif
  63617. #ifndef MA_DR_WAV_FREE
  63618. #define MA_DR_WAV_FREE(p) free((p))
  63619. #endif
  63620. #ifndef MA_DR_WAV_COPY_MEMORY
  63621. #define MA_DR_WAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  63622. #endif
  63623. #ifndef MA_DR_WAV_ZERO_MEMORY
  63624. #define MA_DR_WAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  63625. #endif
  63626. #ifndef MA_DR_WAV_ZERO_OBJECT
  63627. #define MA_DR_WAV_ZERO_OBJECT(p) MA_DR_WAV_ZERO_MEMORY((p), sizeof(*p))
  63628. #endif
  63629. #define ma_dr_wav_countof(x) (sizeof(x) / sizeof(x[0]))
  63630. #define ma_dr_wav_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  63631. #define ma_dr_wav_min(a, b) (((a) < (b)) ? (a) : (b))
  63632. #define ma_dr_wav_max(a, b) (((a) > (b)) ? (a) : (b))
  63633. #define ma_dr_wav_clamp(x, lo, hi) (ma_dr_wav_max((lo), ma_dr_wav_min((hi), (x))))
  63634. #define ma_dr_wav_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset))
  63635. #define MA_DR_WAV_MAX_SIMD_VECTOR_SIZE 32
  63636. #define MA_DR_WAV_INT64_MIN ((ma_int64) ((ma_uint64)0x80000000 << 32))
  63637. #define MA_DR_WAV_INT64_MAX ((ma_int64)(((ma_uint64)0x7FFFFFFF << 32) | 0xFFFFFFFF))
  63638. #if defined(_MSC_VER) && _MSC_VER >= 1400
  63639. #define MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC
  63640. #define MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC
  63641. #define MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC
  63642. #elif defined(__clang__)
  63643. #if defined(__has_builtin)
  63644. #if __has_builtin(__builtin_bswap16)
  63645. #define MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC
  63646. #endif
  63647. #if __has_builtin(__builtin_bswap32)
  63648. #define MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC
  63649. #endif
  63650. #if __has_builtin(__builtin_bswap64)
  63651. #define MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC
  63652. #endif
  63653. #endif
  63654. #elif defined(__GNUC__)
  63655. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  63656. #define MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC
  63657. #define MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC
  63658. #endif
  63659. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  63660. #define MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC
  63661. #endif
  63662. #endif
  63663. MA_API void ma_dr_wav_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
  63664. {
  63665. if (pMajor) {
  63666. *pMajor = MA_DR_WAV_VERSION_MAJOR;
  63667. }
  63668. if (pMinor) {
  63669. *pMinor = MA_DR_WAV_VERSION_MINOR;
  63670. }
  63671. if (pRevision) {
  63672. *pRevision = MA_DR_WAV_VERSION_REVISION;
  63673. }
  63674. }
  63675. MA_API const char* ma_dr_wav_version_string(void)
  63676. {
  63677. return MA_DR_WAV_VERSION_STRING;
  63678. }
  63679. #ifndef MA_DR_WAV_MAX_SAMPLE_RATE
  63680. #define MA_DR_WAV_MAX_SAMPLE_RATE 384000
  63681. #endif
  63682. #ifndef MA_DR_WAV_MAX_CHANNELS
  63683. #define MA_DR_WAV_MAX_CHANNELS 256
  63684. #endif
  63685. #ifndef MA_DR_WAV_MAX_BITS_PER_SAMPLE
  63686. #define MA_DR_WAV_MAX_BITS_PER_SAMPLE 64
  63687. #endif
  63688. static const ma_uint8 ma_dr_wavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00};
  63689. static const ma_uint8 ma_dr_wavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63690. static const ma_uint8 ma_dr_wavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63691. static const ma_uint8 ma_dr_wavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63692. static const ma_uint8 ma_dr_wavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  63693. static MA_INLINE int ma_dr_wav__is_little_endian(void)
  63694. {
  63695. #if defined(MA_X86) || defined(MA_X64)
  63696. return MA_TRUE;
  63697. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  63698. return MA_TRUE;
  63699. #else
  63700. int n = 1;
  63701. return (*(char*)&n) == 1;
  63702. #endif
  63703. }
  63704. static MA_INLINE void ma_dr_wav_bytes_to_guid(const ma_uint8* data, ma_uint8* guid)
  63705. {
  63706. int i;
  63707. for (i = 0; i < 16; ++i) {
  63708. guid[i] = data[i];
  63709. }
  63710. }
  63711. static MA_INLINE ma_uint16 ma_dr_wav__bswap16(ma_uint16 n)
  63712. {
  63713. #ifdef MA_DR_WAV_HAS_BYTESWAP16_INTRINSIC
  63714. #if defined(_MSC_VER)
  63715. return _byteswap_ushort(n);
  63716. #elif defined(__GNUC__) || defined(__clang__)
  63717. return __builtin_bswap16(n);
  63718. #else
  63719. #error "This compiler does not support the byte swap intrinsic."
  63720. #endif
  63721. #else
  63722. return ((n & 0xFF00) >> 8) |
  63723. ((n & 0x00FF) << 8);
  63724. #endif
  63725. }
  63726. static MA_INLINE ma_uint32 ma_dr_wav__bswap32(ma_uint32 n)
  63727. {
  63728. #ifdef MA_DR_WAV_HAS_BYTESWAP32_INTRINSIC
  63729. #if defined(_MSC_VER)
  63730. return _byteswap_ulong(n);
  63731. #elif defined(__GNUC__) || defined(__clang__)
  63732. #if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(MA_64BIT)
  63733. ma_uint32 r;
  63734. __asm__ __volatile__ (
  63735. #if defined(MA_64BIT)
  63736. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)
  63737. #else
  63738. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  63739. #endif
  63740. );
  63741. return r;
  63742. #else
  63743. return __builtin_bswap32(n);
  63744. #endif
  63745. #else
  63746. #error "This compiler does not support the byte swap intrinsic."
  63747. #endif
  63748. #else
  63749. return ((n & 0xFF000000) >> 24) |
  63750. ((n & 0x00FF0000) >> 8) |
  63751. ((n & 0x0000FF00) << 8) |
  63752. ((n & 0x000000FF) << 24);
  63753. #endif
  63754. }
  63755. static MA_INLINE ma_uint64 ma_dr_wav__bswap64(ma_uint64 n)
  63756. {
  63757. #ifdef MA_DR_WAV_HAS_BYTESWAP64_INTRINSIC
  63758. #if defined(_MSC_VER)
  63759. return _byteswap_uint64(n);
  63760. #elif defined(__GNUC__) || defined(__clang__)
  63761. return __builtin_bswap64(n);
  63762. #else
  63763. #error "This compiler does not support the byte swap intrinsic."
  63764. #endif
  63765. #else
  63766. return ((n & ((ma_uint64)0xFF000000 << 32)) >> 56) |
  63767. ((n & ((ma_uint64)0x00FF0000 << 32)) >> 40) |
  63768. ((n & ((ma_uint64)0x0000FF00 << 32)) >> 24) |
  63769. ((n & ((ma_uint64)0x000000FF << 32)) >> 8) |
  63770. ((n & ((ma_uint64)0xFF000000 )) << 8) |
  63771. ((n & ((ma_uint64)0x00FF0000 )) << 24) |
  63772. ((n & ((ma_uint64)0x0000FF00 )) << 40) |
  63773. ((n & ((ma_uint64)0x000000FF )) << 56);
  63774. #endif
  63775. }
  63776. static MA_INLINE ma_int16 ma_dr_wav__bswap_s16(ma_int16 n)
  63777. {
  63778. return (ma_int16)ma_dr_wav__bswap16((ma_uint16)n);
  63779. }
  63780. static MA_INLINE void ma_dr_wav__bswap_samples_s16(ma_int16* pSamples, ma_uint64 sampleCount)
  63781. {
  63782. ma_uint64 iSample;
  63783. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63784. pSamples[iSample] = ma_dr_wav__bswap_s16(pSamples[iSample]);
  63785. }
  63786. }
  63787. static MA_INLINE void ma_dr_wav__bswap_s24(ma_uint8* p)
  63788. {
  63789. ma_uint8 t;
  63790. t = p[0];
  63791. p[0] = p[2];
  63792. p[2] = t;
  63793. }
  63794. static MA_INLINE void ma_dr_wav__bswap_samples_s24(ma_uint8* pSamples, ma_uint64 sampleCount)
  63795. {
  63796. ma_uint64 iSample;
  63797. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63798. ma_uint8* pSample = pSamples + (iSample*3);
  63799. ma_dr_wav__bswap_s24(pSample);
  63800. }
  63801. }
  63802. static MA_INLINE ma_int32 ma_dr_wav__bswap_s32(ma_int32 n)
  63803. {
  63804. return (ma_int32)ma_dr_wav__bswap32((ma_uint32)n);
  63805. }
  63806. static MA_INLINE void ma_dr_wav__bswap_samples_s32(ma_int32* pSamples, ma_uint64 sampleCount)
  63807. {
  63808. ma_uint64 iSample;
  63809. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63810. pSamples[iSample] = ma_dr_wav__bswap_s32(pSamples[iSample]);
  63811. }
  63812. }
  63813. static MA_INLINE ma_int64 ma_dr_wav__bswap_s64(ma_int64 n)
  63814. {
  63815. return (ma_int64)ma_dr_wav__bswap64((ma_uint64)n);
  63816. }
  63817. static MA_INLINE void ma_dr_wav__bswap_samples_s64(ma_int64* pSamples, ma_uint64 sampleCount)
  63818. {
  63819. ma_uint64 iSample;
  63820. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63821. pSamples[iSample] = ma_dr_wav__bswap_s64(pSamples[iSample]);
  63822. }
  63823. }
  63824. static MA_INLINE float ma_dr_wav__bswap_f32(float n)
  63825. {
  63826. union {
  63827. ma_uint32 i;
  63828. float f;
  63829. } x;
  63830. x.f = n;
  63831. x.i = ma_dr_wav__bswap32(x.i);
  63832. return x.f;
  63833. }
  63834. static MA_INLINE void ma_dr_wav__bswap_samples_f32(float* pSamples, ma_uint64 sampleCount)
  63835. {
  63836. ma_uint64 iSample;
  63837. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  63838. pSamples[iSample] = ma_dr_wav__bswap_f32(pSamples[iSample]);
  63839. }
  63840. }
  63841. static MA_INLINE void ma_dr_wav__bswap_samples(void* pSamples, ma_uint64 sampleCount, ma_uint32 bytesPerSample)
  63842. {
  63843. switch (bytesPerSample)
  63844. {
  63845. case 1:
  63846. {
  63847. } break;
  63848. case 2:
  63849. {
  63850. ma_dr_wav__bswap_samples_s16((ma_int16*)pSamples, sampleCount);
  63851. } break;
  63852. case 3:
  63853. {
  63854. ma_dr_wav__bswap_samples_s24((ma_uint8*)pSamples, sampleCount);
  63855. } break;
  63856. case 4:
  63857. {
  63858. ma_dr_wav__bswap_samples_s32((ma_int32*)pSamples, sampleCount);
  63859. } break;
  63860. case 8:
  63861. {
  63862. ma_dr_wav__bswap_samples_s64((ma_int64*)pSamples, sampleCount);
  63863. } break;
  63864. default:
  63865. {
  63866. MA_DR_WAV_ASSERT(MA_FALSE);
  63867. } break;
  63868. }
  63869. }
  63870. MA_PRIVATE MA_INLINE ma_bool32 ma_dr_wav_is_container_be(ma_dr_wav_container container)
  63871. {
  63872. if (container == ma_dr_wav_container_rifx || container == ma_dr_wav_container_aiff) {
  63873. return MA_TRUE;
  63874. } else {
  63875. return MA_FALSE;
  63876. }
  63877. }
  63878. MA_PRIVATE MA_INLINE ma_uint16 ma_dr_wav_bytes_to_u16_le(const ma_uint8* data)
  63879. {
  63880. return ((ma_uint16)data[0] << 0) | ((ma_uint16)data[1] << 8);
  63881. }
  63882. MA_PRIVATE MA_INLINE ma_uint16 ma_dr_wav_bytes_to_u16_be(const ma_uint8* data)
  63883. {
  63884. return ((ma_uint16)data[1] << 0) | ((ma_uint16)data[0] << 8);
  63885. }
  63886. MA_PRIVATE MA_INLINE ma_uint16 ma_dr_wav_bytes_to_u16_ex(const ma_uint8* data, ma_dr_wav_container container)
  63887. {
  63888. if (ma_dr_wav_is_container_be(container)) {
  63889. return ma_dr_wav_bytes_to_u16_be(data);
  63890. } else {
  63891. return ma_dr_wav_bytes_to_u16_le(data);
  63892. }
  63893. }
  63894. MA_PRIVATE MA_INLINE ma_uint32 ma_dr_wav_bytes_to_u32_le(const ma_uint8* data)
  63895. {
  63896. return ((ma_uint32)data[0] << 0) | ((ma_uint32)data[1] << 8) | ((ma_uint32)data[2] << 16) | ((ma_uint32)data[3] << 24);
  63897. }
  63898. MA_PRIVATE MA_INLINE ma_uint32 ma_dr_wav_bytes_to_u32_be(const ma_uint8* data)
  63899. {
  63900. return ((ma_uint32)data[3] << 0) | ((ma_uint32)data[2] << 8) | ((ma_uint32)data[1] << 16) | ((ma_uint32)data[0] << 24);
  63901. }
  63902. MA_PRIVATE MA_INLINE ma_uint32 ma_dr_wav_bytes_to_u32_ex(const ma_uint8* data, ma_dr_wav_container container)
  63903. {
  63904. if (ma_dr_wav_is_container_be(container)) {
  63905. return ma_dr_wav_bytes_to_u32_be(data);
  63906. } else {
  63907. return ma_dr_wav_bytes_to_u32_le(data);
  63908. }
  63909. }
  63910. MA_PRIVATE ma_int64 ma_dr_wav_aiff_extented_to_s64(const ma_uint8* data)
  63911. {
  63912. ma_uint32 exponent = ((ma_uint32)data[0] << 8) | data[1];
  63913. ma_uint64 hi = ((ma_uint64)data[2] << 24) | ((ma_uint64)data[3] << 16) | ((ma_uint64)data[4] << 8) | ((ma_uint64)data[5] << 0);
  63914. ma_uint64 lo = ((ma_uint64)data[6] << 24) | ((ma_uint64)data[7] << 16) | ((ma_uint64)data[8] << 8) | ((ma_uint64)data[9] << 0);
  63915. ma_uint64 significand = (hi << 32) | lo;
  63916. int sign = exponent >> 15;
  63917. exponent &= 0x7FFF;
  63918. if (exponent == 0 && significand == 0) {
  63919. return 0;
  63920. } else if (exponent == 0x7FFF) {
  63921. return sign ? MA_DR_WAV_INT64_MIN : MA_DR_WAV_INT64_MAX;
  63922. }
  63923. exponent -= 16383;
  63924. if (exponent > 63) {
  63925. return sign ? MA_DR_WAV_INT64_MIN : MA_DR_WAV_INT64_MAX;
  63926. } else if (exponent < 1) {
  63927. return 0;
  63928. }
  63929. significand >>= (63 - exponent);
  63930. if (sign) {
  63931. return -(ma_int64)significand;
  63932. } else {
  63933. return (ma_int64)significand;
  63934. }
  63935. }
  63936. MA_PRIVATE void* ma_dr_wav__malloc_default(size_t sz, void* pUserData)
  63937. {
  63938. (void)pUserData;
  63939. return MA_DR_WAV_MALLOC(sz);
  63940. }
  63941. MA_PRIVATE void* ma_dr_wav__realloc_default(void* p, size_t sz, void* pUserData)
  63942. {
  63943. (void)pUserData;
  63944. return MA_DR_WAV_REALLOC(p, sz);
  63945. }
  63946. MA_PRIVATE void ma_dr_wav__free_default(void* p, void* pUserData)
  63947. {
  63948. (void)pUserData;
  63949. MA_DR_WAV_FREE(p);
  63950. }
  63951. MA_PRIVATE void* ma_dr_wav__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  63952. {
  63953. if (pAllocationCallbacks == NULL) {
  63954. return NULL;
  63955. }
  63956. if (pAllocationCallbacks->onMalloc != NULL) {
  63957. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  63958. }
  63959. if (pAllocationCallbacks->onRealloc != NULL) {
  63960. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  63961. }
  63962. return NULL;
  63963. }
  63964. MA_PRIVATE void* ma_dr_wav__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks)
  63965. {
  63966. if (pAllocationCallbacks == NULL) {
  63967. return NULL;
  63968. }
  63969. if (pAllocationCallbacks->onRealloc != NULL) {
  63970. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  63971. }
  63972. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  63973. void* p2;
  63974. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  63975. if (p2 == NULL) {
  63976. return NULL;
  63977. }
  63978. if (p != NULL) {
  63979. MA_DR_WAV_COPY_MEMORY(p2, p, szOld);
  63980. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  63981. }
  63982. return p2;
  63983. }
  63984. return NULL;
  63985. }
  63986. MA_PRIVATE void ma_dr_wav__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  63987. {
  63988. if (p == NULL || pAllocationCallbacks == NULL) {
  63989. return;
  63990. }
  63991. if (pAllocationCallbacks->onFree != NULL) {
  63992. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  63993. }
  63994. }
  63995. MA_PRIVATE ma_allocation_callbacks ma_dr_wav_copy_allocation_callbacks_or_defaults(const ma_allocation_callbacks* pAllocationCallbacks)
  63996. {
  63997. if (pAllocationCallbacks != NULL) {
  63998. return *pAllocationCallbacks;
  63999. } else {
  64000. ma_allocation_callbacks allocationCallbacks;
  64001. allocationCallbacks.pUserData = NULL;
  64002. allocationCallbacks.onMalloc = ma_dr_wav__malloc_default;
  64003. allocationCallbacks.onRealloc = ma_dr_wav__realloc_default;
  64004. allocationCallbacks.onFree = ma_dr_wav__free_default;
  64005. return allocationCallbacks;
  64006. }
  64007. }
  64008. static MA_INLINE ma_bool32 ma_dr_wav__is_compressed_format_tag(ma_uint16 formatTag)
  64009. {
  64010. return
  64011. formatTag == MA_DR_WAVE_FORMAT_ADPCM ||
  64012. formatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM;
  64013. }
  64014. MA_PRIVATE unsigned int ma_dr_wav__chunk_padding_size_riff(ma_uint64 chunkSize)
  64015. {
  64016. return (unsigned int)(chunkSize % 2);
  64017. }
  64018. MA_PRIVATE unsigned int ma_dr_wav__chunk_padding_size_w64(ma_uint64 chunkSize)
  64019. {
  64020. return (unsigned int)(chunkSize % 8);
  64021. }
  64022. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__msadpcm(ma_dr_wav* pWav, ma_uint64 samplesToRead, ma_int16* pBufferOut);
  64023. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__ima(ma_dr_wav* pWav, ma_uint64 samplesToRead, ma_int16* pBufferOut);
  64024. MA_PRIVATE ma_bool32 ma_dr_wav_init_write__internal(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount);
  64025. MA_PRIVATE ma_result ma_dr_wav__read_chunk_header(ma_dr_wav_read_proc onRead, void* pUserData, ma_dr_wav_container container, ma_uint64* pRunningBytesReadOut, ma_dr_wav_chunk_header* pHeaderOut)
  64026. {
  64027. if (container == ma_dr_wav_container_riff || container == ma_dr_wav_container_rifx || container == ma_dr_wav_container_rf64 || container == ma_dr_wav_container_aiff) {
  64028. ma_uint8 sizeInBytes[4];
  64029. if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) {
  64030. return MA_AT_END;
  64031. }
  64032. if (onRead(pUserData, sizeInBytes, 4) != 4) {
  64033. return MA_INVALID_FILE;
  64034. }
  64035. pHeaderOut->sizeInBytes = ma_dr_wav_bytes_to_u32_ex(sizeInBytes, container);
  64036. pHeaderOut->paddingSize = ma_dr_wav__chunk_padding_size_riff(pHeaderOut->sizeInBytes);
  64037. *pRunningBytesReadOut += 8;
  64038. } else if (container == ma_dr_wav_container_w64) {
  64039. ma_uint8 sizeInBytes[8];
  64040. if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) {
  64041. return MA_AT_END;
  64042. }
  64043. if (onRead(pUserData, sizeInBytes, 8) != 8) {
  64044. return MA_INVALID_FILE;
  64045. }
  64046. pHeaderOut->sizeInBytes = ma_dr_wav_bytes_to_u64(sizeInBytes) - 24;
  64047. pHeaderOut->paddingSize = ma_dr_wav__chunk_padding_size_w64(pHeaderOut->sizeInBytes);
  64048. *pRunningBytesReadOut += 24;
  64049. } else {
  64050. return MA_INVALID_FILE;
  64051. }
  64052. return MA_SUCCESS;
  64053. }
  64054. MA_PRIVATE ma_bool32 ma_dr_wav__seek_forward(ma_dr_wav_seek_proc onSeek, ma_uint64 offset, void* pUserData)
  64055. {
  64056. ma_uint64 bytesRemainingToSeek = offset;
  64057. while (bytesRemainingToSeek > 0) {
  64058. if (bytesRemainingToSeek > 0x7FFFFFFF) {
  64059. if (!onSeek(pUserData, 0x7FFFFFFF, ma_dr_wav_seek_origin_current)) {
  64060. return MA_FALSE;
  64061. }
  64062. bytesRemainingToSeek -= 0x7FFFFFFF;
  64063. } else {
  64064. if (!onSeek(pUserData, (int)bytesRemainingToSeek, ma_dr_wav_seek_origin_current)) {
  64065. return MA_FALSE;
  64066. }
  64067. bytesRemainingToSeek = 0;
  64068. }
  64069. }
  64070. return MA_TRUE;
  64071. }
  64072. MA_PRIVATE ma_bool32 ma_dr_wav__seek_from_start(ma_dr_wav_seek_proc onSeek, ma_uint64 offset, void* pUserData)
  64073. {
  64074. if (offset <= 0x7FFFFFFF) {
  64075. return onSeek(pUserData, (int)offset, ma_dr_wav_seek_origin_start);
  64076. }
  64077. if (!onSeek(pUserData, 0x7FFFFFFF, ma_dr_wav_seek_origin_start)) {
  64078. return MA_FALSE;
  64079. }
  64080. offset -= 0x7FFFFFFF;
  64081. for (;;) {
  64082. if (offset <= 0x7FFFFFFF) {
  64083. return onSeek(pUserData, (int)offset, ma_dr_wav_seek_origin_current);
  64084. }
  64085. if (!onSeek(pUserData, 0x7FFFFFFF, ma_dr_wav_seek_origin_current)) {
  64086. return MA_FALSE;
  64087. }
  64088. offset -= 0x7FFFFFFF;
  64089. }
  64090. }
  64091. MA_PRIVATE size_t ma_dr_wav__on_read(ma_dr_wav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, ma_uint64* pCursor)
  64092. {
  64093. size_t bytesRead;
  64094. MA_DR_WAV_ASSERT(onRead != NULL);
  64095. MA_DR_WAV_ASSERT(pCursor != NULL);
  64096. bytesRead = onRead(pUserData, pBufferOut, bytesToRead);
  64097. *pCursor += bytesRead;
  64098. return bytesRead;
  64099. }
  64100. #if 0
  64101. MA_PRIVATE ma_bool32 ma_dr_wav__on_seek(ma_dr_wav_seek_proc onSeek, void* pUserData, int offset, ma_dr_wav_seek_origin origin, ma_uint64* pCursor)
  64102. {
  64103. MA_DR_WAV_ASSERT(onSeek != NULL);
  64104. MA_DR_WAV_ASSERT(pCursor != NULL);
  64105. if (!onSeek(pUserData, offset, origin)) {
  64106. return MA_FALSE;
  64107. }
  64108. if (origin == ma_dr_wav_seek_origin_start) {
  64109. *pCursor = offset;
  64110. } else {
  64111. *pCursor += offset;
  64112. }
  64113. return MA_TRUE;
  64114. }
  64115. #endif
  64116. #define MA_DR_WAV_SMPL_BYTES 36
  64117. #define MA_DR_WAV_SMPL_LOOP_BYTES 24
  64118. #define MA_DR_WAV_INST_BYTES 7
  64119. #define MA_DR_WAV_ACID_BYTES 24
  64120. #define MA_DR_WAV_CUE_BYTES 4
  64121. #define MA_DR_WAV_BEXT_BYTES 602
  64122. #define MA_DR_WAV_BEXT_DESCRIPTION_BYTES 256
  64123. #define MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES 32
  64124. #define MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES 32
  64125. #define MA_DR_WAV_BEXT_RESERVED_BYTES 180
  64126. #define MA_DR_WAV_BEXT_UMID_BYTES 64
  64127. #define MA_DR_WAV_CUE_POINT_BYTES 24
  64128. #define MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES 4
  64129. #define MA_DR_WAV_LIST_LABELLED_TEXT_BYTES 20
  64130. #define MA_DR_WAV_METADATA_ALIGNMENT 8
  64131. typedef enum
  64132. {
  64133. ma_dr_wav__metadata_parser_stage_count,
  64134. ma_dr_wav__metadata_parser_stage_read
  64135. } ma_dr_wav__metadata_parser_stage;
  64136. typedef struct
  64137. {
  64138. ma_dr_wav_read_proc onRead;
  64139. ma_dr_wav_seek_proc onSeek;
  64140. void *pReadSeekUserData;
  64141. ma_dr_wav__metadata_parser_stage stage;
  64142. ma_dr_wav_metadata *pMetadata;
  64143. ma_uint32 metadataCount;
  64144. ma_uint8 *pData;
  64145. ma_uint8 *pDataCursor;
  64146. ma_uint64 metadataCursor;
  64147. ma_uint64 extraCapacity;
  64148. } ma_dr_wav__metadata_parser;
  64149. MA_PRIVATE size_t ma_dr_wav__metadata_memory_capacity(ma_dr_wav__metadata_parser* pParser)
  64150. {
  64151. ma_uint64 cap = sizeof(ma_dr_wav_metadata) * (ma_uint64)pParser->metadataCount + pParser->extraCapacity;
  64152. if (cap > MA_SIZE_MAX) {
  64153. return 0;
  64154. }
  64155. return (size_t)cap;
  64156. }
  64157. MA_PRIVATE ma_uint8* ma_dr_wav__metadata_get_memory(ma_dr_wav__metadata_parser* pParser, size_t size, size_t align)
  64158. {
  64159. ma_uint8* pResult;
  64160. if (align) {
  64161. ma_uintptr modulo = (ma_uintptr)pParser->pDataCursor % align;
  64162. if (modulo != 0) {
  64163. pParser->pDataCursor += align - modulo;
  64164. }
  64165. }
  64166. pResult = pParser->pDataCursor;
  64167. MA_DR_WAV_ASSERT((pResult + size) <= (pParser->pData + ma_dr_wav__metadata_memory_capacity(pParser)));
  64168. pParser->pDataCursor += size;
  64169. return pResult;
  64170. }
  64171. MA_PRIVATE void ma_dr_wav__metadata_request_extra_memory_for_stage_2(ma_dr_wav__metadata_parser* pParser, size_t bytes, size_t align)
  64172. {
  64173. size_t extra = bytes + (align ? (align - 1) : 0);
  64174. pParser->extraCapacity += extra;
  64175. }
  64176. MA_PRIVATE ma_result ma_dr_wav__metadata_alloc(ma_dr_wav__metadata_parser* pParser, ma_allocation_callbacks* pAllocationCallbacks)
  64177. {
  64178. if (pParser->extraCapacity != 0 || pParser->metadataCount != 0) {
  64179. pAllocationCallbacks->onFree(pParser->pData, pAllocationCallbacks->pUserData);
  64180. pParser->pData = (ma_uint8*)pAllocationCallbacks->onMalloc(ma_dr_wav__metadata_memory_capacity(pParser), pAllocationCallbacks->pUserData);
  64181. pParser->pDataCursor = pParser->pData;
  64182. if (pParser->pData == NULL) {
  64183. return MA_OUT_OF_MEMORY;
  64184. }
  64185. pParser->pMetadata = (ma_dr_wav_metadata*)ma_dr_wav__metadata_get_memory(pParser, sizeof(ma_dr_wav_metadata) * pParser->metadataCount, 1);
  64186. pParser->metadataCursor = 0;
  64187. }
  64188. return MA_SUCCESS;
  64189. }
  64190. MA_PRIVATE size_t ma_dr_wav__metadata_parser_read(ma_dr_wav__metadata_parser* pParser, void* pBufferOut, size_t bytesToRead, ma_uint64* pCursor)
  64191. {
  64192. if (pCursor != NULL) {
  64193. return ma_dr_wav__on_read(pParser->onRead, pParser->pReadSeekUserData, pBufferOut, bytesToRead, pCursor);
  64194. } else {
  64195. return pParser->onRead(pParser->pReadSeekUserData, pBufferOut, bytesToRead);
  64196. }
  64197. }
  64198. MA_PRIVATE ma_uint64 ma_dr_wav__read_smpl_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_metadata* pMetadata)
  64199. {
  64200. ma_uint8 smplHeaderData[MA_DR_WAV_SMPL_BYTES];
  64201. ma_uint64 totalBytesRead = 0;
  64202. size_t bytesJustRead;
  64203. if (pMetadata == NULL) {
  64204. return 0;
  64205. }
  64206. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead);
  64207. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64208. MA_DR_WAV_ASSERT(pChunkHeader != NULL);
  64209. if (pMetadata != NULL && bytesJustRead == sizeof(smplHeaderData)) {
  64210. ma_uint32 iSampleLoop;
  64211. pMetadata->type = ma_dr_wav_metadata_type_smpl;
  64212. pMetadata->data.smpl.manufacturerId = ma_dr_wav_bytes_to_u32(smplHeaderData + 0);
  64213. pMetadata->data.smpl.productId = ma_dr_wav_bytes_to_u32(smplHeaderData + 4);
  64214. pMetadata->data.smpl.samplePeriodNanoseconds = ma_dr_wav_bytes_to_u32(smplHeaderData + 8);
  64215. pMetadata->data.smpl.midiUnityNote = ma_dr_wav_bytes_to_u32(smplHeaderData + 12);
  64216. pMetadata->data.smpl.midiPitchFraction = ma_dr_wav_bytes_to_u32(smplHeaderData + 16);
  64217. pMetadata->data.smpl.smpteFormat = ma_dr_wav_bytes_to_u32(smplHeaderData + 20);
  64218. pMetadata->data.smpl.smpteOffset = ma_dr_wav_bytes_to_u32(smplHeaderData + 24);
  64219. pMetadata->data.smpl.sampleLoopCount = ma_dr_wav_bytes_to_u32(smplHeaderData + 28);
  64220. pMetadata->data.smpl.samplerSpecificDataSizeInBytes = ma_dr_wav_bytes_to_u32(smplHeaderData + 32);
  64221. if (pMetadata->data.smpl.sampleLoopCount == (pChunkHeader->sizeInBytes - MA_DR_WAV_SMPL_BYTES) / MA_DR_WAV_SMPL_LOOP_BYTES) {
  64222. pMetadata->data.smpl.pLoops = (ma_dr_wav_smpl_loop*)ma_dr_wav__metadata_get_memory(pParser, sizeof(ma_dr_wav_smpl_loop) * pMetadata->data.smpl.sampleLoopCount, MA_DR_WAV_METADATA_ALIGNMENT);
  64223. for (iSampleLoop = 0; iSampleLoop < pMetadata->data.smpl.sampleLoopCount; ++iSampleLoop) {
  64224. ma_uint8 smplLoopData[MA_DR_WAV_SMPL_LOOP_BYTES];
  64225. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, smplLoopData, sizeof(smplLoopData), &totalBytesRead);
  64226. if (bytesJustRead == sizeof(smplLoopData)) {
  64227. pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = ma_dr_wav_bytes_to_u32(smplLoopData + 0);
  64228. pMetadata->data.smpl.pLoops[iSampleLoop].type = ma_dr_wav_bytes_to_u32(smplLoopData + 4);
  64229. pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleByteOffset = ma_dr_wav_bytes_to_u32(smplLoopData + 8);
  64230. pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleByteOffset = ma_dr_wav_bytes_to_u32(smplLoopData + 12);
  64231. pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = ma_dr_wav_bytes_to_u32(smplLoopData + 16);
  64232. pMetadata->data.smpl.pLoops[iSampleLoop].playCount = ma_dr_wav_bytes_to_u32(smplLoopData + 20);
  64233. } else {
  64234. break;
  64235. }
  64236. }
  64237. if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
  64238. pMetadata->data.smpl.pSamplerSpecificData = ma_dr_wav__metadata_get_memory(pParser, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, 1);
  64239. MA_DR_WAV_ASSERT(pMetadata->data.smpl.pSamplerSpecificData != NULL);
  64240. ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, &totalBytesRead);
  64241. }
  64242. }
  64243. }
  64244. return totalBytesRead;
  64245. }
  64246. MA_PRIVATE ma_uint64 ma_dr_wav__read_cue_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_metadata* pMetadata)
  64247. {
  64248. ma_uint8 cueHeaderSectionData[MA_DR_WAV_CUE_BYTES];
  64249. ma_uint64 totalBytesRead = 0;
  64250. size_t bytesJustRead;
  64251. if (pMetadata == NULL) {
  64252. return 0;
  64253. }
  64254. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead);
  64255. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64256. if (bytesJustRead == sizeof(cueHeaderSectionData)) {
  64257. pMetadata->type = ma_dr_wav_metadata_type_cue;
  64258. pMetadata->data.cue.cuePointCount = ma_dr_wav_bytes_to_u32(cueHeaderSectionData);
  64259. if (pMetadata->data.cue.cuePointCount == (pChunkHeader->sizeInBytes - MA_DR_WAV_CUE_BYTES) / MA_DR_WAV_CUE_POINT_BYTES) {
  64260. pMetadata->data.cue.pCuePoints = (ma_dr_wav_cue_point*)ma_dr_wav__metadata_get_memory(pParser, sizeof(ma_dr_wav_cue_point) * pMetadata->data.cue.cuePointCount, MA_DR_WAV_METADATA_ALIGNMENT);
  64261. MA_DR_WAV_ASSERT(pMetadata->data.cue.pCuePoints != NULL);
  64262. if (pMetadata->data.cue.cuePointCount > 0) {
  64263. ma_uint32 iCuePoint;
  64264. for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
  64265. ma_uint8 cuePointData[MA_DR_WAV_CUE_POINT_BYTES];
  64266. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, cuePointData, sizeof(cuePointData), &totalBytesRead);
  64267. if (bytesJustRead == sizeof(cuePointData)) {
  64268. pMetadata->data.cue.pCuePoints[iCuePoint].id = ma_dr_wav_bytes_to_u32(cuePointData + 0);
  64269. pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition = ma_dr_wav_bytes_to_u32(cuePointData + 4);
  64270. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[0] = cuePointData[8];
  64271. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[1] = cuePointData[9];
  64272. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[2] = cuePointData[10];
  64273. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[3] = cuePointData[11];
  64274. pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart = ma_dr_wav_bytes_to_u32(cuePointData + 12);
  64275. pMetadata->data.cue.pCuePoints[iCuePoint].blockStart = ma_dr_wav_bytes_to_u32(cuePointData + 16);
  64276. pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset = ma_dr_wav_bytes_to_u32(cuePointData + 20);
  64277. } else {
  64278. break;
  64279. }
  64280. }
  64281. }
  64282. }
  64283. }
  64284. return totalBytesRead;
  64285. }
  64286. MA_PRIVATE ma_uint64 ma_dr_wav__read_inst_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata)
  64287. {
  64288. ma_uint8 instData[MA_DR_WAV_INST_BYTES];
  64289. ma_uint64 bytesRead;
  64290. if (pMetadata == NULL) {
  64291. return 0;
  64292. }
  64293. bytesRead = ma_dr_wav__metadata_parser_read(pParser, instData, sizeof(instData), NULL);
  64294. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64295. if (bytesRead == sizeof(instData)) {
  64296. pMetadata->type = ma_dr_wav_metadata_type_inst;
  64297. pMetadata->data.inst.midiUnityNote = (ma_int8)instData[0];
  64298. pMetadata->data.inst.fineTuneCents = (ma_int8)instData[1];
  64299. pMetadata->data.inst.gainDecibels = (ma_int8)instData[2];
  64300. pMetadata->data.inst.lowNote = (ma_int8)instData[3];
  64301. pMetadata->data.inst.highNote = (ma_int8)instData[4];
  64302. pMetadata->data.inst.lowVelocity = (ma_int8)instData[5];
  64303. pMetadata->data.inst.highVelocity = (ma_int8)instData[6];
  64304. }
  64305. return bytesRead;
  64306. }
  64307. MA_PRIVATE ma_uint64 ma_dr_wav__read_acid_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata)
  64308. {
  64309. ma_uint8 acidData[MA_DR_WAV_ACID_BYTES];
  64310. ma_uint64 bytesRead;
  64311. if (pMetadata == NULL) {
  64312. return 0;
  64313. }
  64314. bytesRead = ma_dr_wav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL);
  64315. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64316. if (bytesRead == sizeof(acidData)) {
  64317. pMetadata->type = ma_dr_wav_metadata_type_acid;
  64318. pMetadata->data.acid.flags = ma_dr_wav_bytes_to_u32(acidData + 0);
  64319. pMetadata->data.acid.midiUnityNote = ma_dr_wav_bytes_to_u16(acidData + 4);
  64320. pMetadata->data.acid.reserved1 = ma_dr_wav_bytes_to_u16(acidData + 6);
  64321. pMetadata->data.acid.reserved2 = ma_dr_wav_bytes_to_f32(acidData + 8);
  64322. pMetadata->data.acid.numBeats = ma_dr_wav_bytes_to_u32(acidData + 12);
  64323. pMetadata->data.acid.meterDenominator = ma_dr_wav_bytes_to_u16(acidData + 16);
  64324. pMetadata->data.acid.meterNumerator = ma_dr_wav_bytes_to_u16(acidData + 18);
  64325. pMetadata->data.acid.tempo = ma_dr_wav_bytes_to_f32(acidData + 20);
  64326. }
  64327. return bytesRead;
  64328. }
  64329. MA_PRIVATE size_t ma_dr_wav__strlen(const char* str)
  64330. {
  64331. size_t result = 0;
  64332. while (*str++) {
  64333. result += 1;
  64334. }
  64335. return result;
  64336. }
  64337. MA_PRIVATE size_t ma_dr_wav__strlen_clamped(const char* str, size_t maxToRead)
  64338. {
  64339. size_t result = 0;
  64340. while (*str++ && result < maxToRead) {
  64341. result += 1;
  64342. }
  64343. return result;
  64344. }
  64345. MA_PRIVATE char* ma_dr_wav__metadata_copy_string(ma_dr_wav__metadata_parser* pParser, const char* str, size_t maxToRead)
  64346. {
  64347. size_t len = ma_dr_wav__strlen_clamped(str, maxToRead);
  64348. if (len) {
  64349. char* result = (char*)ma_dr_wav__metadata_get_memory(pParser, len + 1, 1);
  64350. MA_DR_WAV_ASSERT(result != NULL);
  64351. MA_DR_WAV_COPY_MEMORY(result, str, len);
  64352. result[len] = '\0';
  64353. return result;
  64354. } else {
  64355. return NULL;
  64356. }
  64357. }
  64358. typedef struct
  64359. {
  64360. const void* pBuffer;
  64361. size_t sizeInBytes;
  64362. size_t cursor;
  64363. } ma_dr_wav_buffer_reader;
  64364. MA_PRIVATE ma_result ma_dr_wav_buffer_reader_init(const void* pBuffer, size_t sizeInBytes, ma_dr_wav_buffer_reader* pReader)
  64365. {
  64366. MA_DR_WAV_ASSERT(pBuffer != NULL);
  64367. MA_DR_WAV_ASSERT(pReader != NULL);
  64368. MA_DR_WAV_ZERO_OBJECT(pReader);
  64369. pReader->pBuffer = pBuffer;
  64370. pReader->sizeInBytes = sizeInBytes;
  64371. pReader->cursor = 0;
  64372. return MA_SUCCESS;
  64373. }
  64374. MA_PRIVATE const void* ma_dr_wav_buffer_reader_ptr(const ma_dr_wav_buffer_reader* pReader)
  64375. {
  64376. MA_DR_WAV_ASSERT(pReader != NULL);
  64377. return ma_dr_wav_offset_ptr(pReader->pBuffer, pReader->cursor);
  64378. }
  64379. MA_PRIVATE ma_result ma_dr_wav_buffer_reader_seek(ma_dr_wav_buffer_reader* pReader, size_t bytesToSeek)
  64380. {
  64381. MA_DR_WAV_ASSERT(pReader != NULL);
  64382. if (pReader->cursor + bytesToSeek > pReader->sizeInBytes) {
  64383. return MA_BAD_SEEK;
  64384. }
  64385. pReader->cursor += bytesToSeek;
  64386. return MA_SUCCESS;
  64387. }
  64388. MA_PRIVATE ma_result ma_dr_wav_buffer_reader_read(ma_dr_wav_buffer_reader* pReader, void* pDst, size_t bytesToRead, size_t* pBytesRead)
  64389. {
  64390. ma_result result = MA_SUCCESS;
  64391. size_t bytesRemaining;
  64392. MA_DR_WAV_ASSERT(pReader != NULL);
  64393. if (pBytesRead != NULL) {
  64394. *pBytesRead = 0;
  64395. }
  64396. bytesRemaining = (pReader->sizeInBytes - pReader->cursor);
  64397. if (bytesToRead > bytesRemaining) {
  64398. bytesToRead = bytesRemaining;
  64399. }
  64400. if (pDst == NULL) {
  64401. result = ma_dr_wav_buffer_reader_seek(pReader, bytesToRead);
  64402. } else {
  64403. MA_DR_WAV_COPY_MEMORY(pDst, ma_dr_wav_buffer_reader_ptr(pReader), bytesToRead);
  64404. pReader->cursor += bytesToRead;
  64405. }
  64406. MA_DR_WAV_ASSERT(pReader->cursor <= pReader->sizeInBytes);
  64407. if (result == MA_SUCCESS) {
  64408. if (pBytesRead != NULL) {
  64409. *pBytesRead = bytesToRead;
  64410. }
  64411. }
  64412. return MA_SUCCESS;
  64413. }
  64414. MA_PRIVATE ma_result ma_dr_wav_buffer_reader_read_u16(ma_dr_wav_buffer_reader* pReader, ma_uint16* pDst)
  64415. {
  64416. ma_result result;
  64417. size_t bytesRead;
  64418. ma_uint8 data[2];
  64419. MA_DR_WAV_ASSERT(pReader != NULL);
  64420. MA_DR_WAV_ASSERT(pDst != NULL);
  64421. *pDst = 0;
  64422. result = ma_dr_wav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
  64423. if (result != MA_SUCCESS || bytesRead != sizeof(*pDst)) {
  64424. return result;
  64425. }
  64426. *pDst = ma_dr_wav_bytes_to_u16(data);
  64427. return MA_SUCCESS;
  64428. }
  64429. MA_PRIVATE ma_result ma_dr_wav_buffer_reader_read_u32(ma_dr_wav_buffer_reader* pReader, ma_uint32* pDst)
  64430. {
  64431. ma_result result;
  64432. size_t bytesRead;
  64433. ma_uint8 data[4];
  64434. MA_DR_WAV_ASSERT(pReader != NULL);
  64435. MA_DR_WAV_ASSERT(pDst != NULL);
  64436. *pDst = 0;
  64437. result = ma_dr_wav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
  64438. if (result != MA_SUCCESS || bytesRead != sizeof(*pDst)) {
  64439. return result;
  64440. }
  64441. *pDst = ma_dr_wav_bytes_to_u32(data);
  64442. return MA_SUCCESS;
  64443. }
  64444. MA_PRIVATE ma_uint64 ma_dr_wav__read_bext_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata, ma_uint64 chunkSize)
  64445. {
  64446. ma_uint8 bextData[MA_DR_WAV_BEXT_BYTES];
  64447. size_t bytesRead = ma_dr_wav__metadata_parser_read(pParser, bextData, sizeof(bextData), NULL);
  64448. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64449. if (bytesRead == sizeof(bextData)) {
  64450. ma_dr_wav_buffer_reader reader;
  64451. ma_uint32 timeReferenceLow;
  64452. ma_uint32 timeReferenceHigh;
  64453. size_t extraBytes;
  64454. pMetadata->type = ma_dr_wav_metadata_type_bext;
  64455. if (ma_dr_wav_buffer_reader_init(bextData, bytesRead, &reader) == MA_SUCCESS) {
  64456. pMetadata->data.bext.pDescription = ma_dr_wav__metadata_copy_string(pParser, (const char*)ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_DESCRIPTION_BYTES);
  64457. ma_dr_wav_buffer_reader_seek(&reader, MA_DR_WAV_BEXT_DESCRIPTION_BYTES);
  64458. pMetadata->data.bext.pOriginatorName = ma_dr_wav__metadata_copy_string(pParser, (const char*)ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES);
  64459. ma_dr_wav_buffer_reader_seek(&reader, MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES);
  64460. pMetadata->data.bext.pOriginatorReference = ma_dr_wav__metadata_copy_string(pParser, (const char*)ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES);
  64461. ma_dr_wav_buffer_reader_seek(&reader, MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES);
  64462. ma_dr_wav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate), NULL);
  64463. ma_dr_wav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime), NULL);
  64464. ma_dr_wav_buffer_reader_read_u32(&reader, &timeReferenceLow);
  64465. ma_dr_wav_buffer_reader_read_u32(&reader, &timeReferenceHigh);
  64466. pMetadata->data.bext.timeReference = ((ma_uint64)timeReferenceHigh << 32) + timeReferenceLow;
  64467. ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.version);
  64468. pMetadata->data.bext.pUMID = ma_dr_wav__metadata_get_memory(pParser, MA_DR_WAV_BEXT_UMID_BYTES, 1);
  64469. ma_dr_wav_buffer_reader_read(&reader, pMetadata->data.bext.pUMID, MA_DR_WAV_BEXT_UMID_BYTES, NULL);
  64470. ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessValue);
  64471. ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessRange);
  64472. ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxTruePeakLevel);
  64473. ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxMomentaryLoudness);
  64474. ma_dr_wav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxShortTermLoudness);
  64475. MA_DR_WAV_ASSERT((ma_dr_wav_offset_ptr(ma_dr_wav_buffer_reader_ptr(&reader), MA_DR_WAV_BEXT_RESERVED_BYTES)) == (bextData + MA_DR_WAV_BEXT_BYTES));
  64476. extraBytes = (size_t)(chunkSize - MA_DR_WAV_BEXT_BYTES);
  64477. if (extraBytes > 0) {
  64478. pMetadata->data.bext.pCodingHistory = (char*)ma_dr_wav__metadata_get_memory(pParser, extraBytes + 1, 1);
  64479. MA_DR_WAV_ASSERT(pMetadata->data.bext.pCodingHistory != NULL);
  64480. bytesRead += ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.bext.pCodingHistory, extraBytes, NULL);
  64481. pMetadata->data.bext.codingHistorySize = (ma_uint32)ma_dr_wav__strlen(pMetadata->data.bext.pCodingHistory);
  64482. } else {
  64483. pMetadata->data.bext.pCodingHistory = NULL;
  64484. pMetadata->data.bext.codingHistorySize = 0;
  64485. }
  64486. }
  64487. }
  64488. return bytesRead;
  64489. }
  64490. MA_PRIVATE ma_uint64 ma_dr_wav__read_list_label_or_note_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata, ma_uint64 chunkSize, ma_dr_wav_metadata_type type)
  64491. {
  64492. ma_uint8 cueIDBuffer[MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES];
  64493. ma_uint64 totalBytesRead = 0;
  64494. size_t bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, cueIDBuffer, sizeof(cueIDBuffer), &totalBytesRead);
  64495. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64496. if (bytesJustRead == sizeof(cueIDBuffer)) {
  64497. ma_uint32 sizeIncludingNullTerminator;
  64498. pMetadata->type = type;
  64499. pMetadata->data.labelOrNote.cuePointId = ma_dr_wav_bytes_to_u32(cueIDBuffer);
  64500. sizeIncludingNullTerminator = (ma_uint32)chunkSize - MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES;
  64501. if (sizeIncludingNullTerminator > 0) {
  64502. pMetadata->data.labelOrNote.stringLength = sizeIncludingNullTerminator - 1;
  64503. pMetadata->data.labelOrNote.pString = (char*)ma_dr_wav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
  64504. MA_DR_WAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
  64505. ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.labelOrNote.pString, sizeIncludingNullTerminator, &totalBytesRead);
  64506. } else {
  64507. pMetadata->data.labelOrNote.stringLength = 0;
  64508. pMetadata->data.labelOrNote.pString = NULL;
  64509. }
  64510. }
  64511. return totalBytesRead;
  64512. }
  64513. MA_PRIVATE ma_uint64 ma_dr_wav__read_list_labelled_cue_region_to_metadata_obj(ma_dr_wav__metadata_parser* pParser, ma_dr_wav_metadata* pMetadata, ma_uint64 chunkSize)
  64514. {
  64515. ma_uint8 buffer[MA_DR_WAV_LIST_LABELLED_TEXT_BYTES];
  64516. ma_uint64 totalBytesRead = 0;
  64517. size_t bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, sizeof(buffer), &totalBytesRead);
  64518. MA_DR_WAV_ASSERT(pParser->stage == ma_dr_wav__metadata_parser_stage_read);
  64519. if (bytesJustRead == sizeof(buffer)) {
  64520. ma_uint32 sizeIncludingNullTerminator;
  64521. pMetadata->type = ma_dr_wav_metadata_type_list_labelled_cue_region;
  64522. pMetadata->data.labelledCueRegion.cuePointId = ma_dr_wav_bytes_to_u32(buffer + 0);
  64523. pMetadata->data.labelledCueRegion.sampleLength = ma_dr_wav_bytes_to_u32(buffer + 4);
  64524. pMetadata->data.labelledCueRegion.purposeId[0] = buffer[8];
  64525. pMetadata->data.labelledCueRegion.purposeId[1] = buffer[9];
  64526. pMetadata->data.labelledCueRegion.purposeId[2] = buffer[10];
  64527. pMetadata->data.labelledCueRegion.purposeId[3] = buffer[11];
  64528. pMetadata->data.labelledCueRegion.country = ma_dr_wav_bytes_to_u16(buffer + 12);
  64529. pMetadata->data.labelledCueRegion.language = ma_dr_wav_bytes_to_u16(buffer + 14);
  64530. pMetadata->data.labelledCueRegion.dialect = ma_dr_wav_bytes_to_u16(buffer + 16);
  64531. pMetadata->data.labelledCueRegion.codePage = ma_dr_wav_bytes_to_u16(buffer + 18);
  64532. sizeIncludingNullTerminator = (ma_uint32)chunkSize - MA_DR_WAV_LIST_LABELLED_TEXT_BYTES;
  64533. if (sizeIncludingNullTerminator > 0) {
  64534. pMetadata->data.labelledCueRegion.stringLength = sizeIncludingNullTerminator - 1;
  64535. pMetadata->data.labelledCueRegion.pString = (char*)ma_dr_wav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
  64536. MA_DR_WAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
  64537. ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.labelledCueRegion.pString, sizeIncludingNullTerminator, &totalBytesRead);
  64538. } else {
  64539. pMetadata->data.labelledCueRegion.stringLength = 0;
  64540. pMetadata->data.labelledCueRegion.pString = NULL;
  64541. }
  64542. }
  64543. return totalBytesRead;
  64544. }
  64545. MA_PRIVATE ma_uint64 ma_dr_wav__metadata_process_info_text_chunk(ma_dr_wav__metadata_parser* pParser, ma_uint64 chunkSize, ma_dr_wav_metadata_type type)
  64546. {
  64547. ma_uint64 bytesRead = 0;
  64548. ma_uint32 stringSizeWithNullTerminator = (ma_uint32)chunkSize;
  64549. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64550. pParser->metadataCount += 1;
  64551. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, stringSizeWithNullTerminator, 1);
  64552. } else {
  64553. ma_dr_wav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
  64554. pMetadata->type = type;
  64555. if (stringSizeWithNullTerminator > 0) {
  64556. pMetadata->data.infoText.stringLength = stringSizeWithNullTerminator - 1;
  64557. pMetadata->data.infoText.pString = (char*)ma_dr_wav__metadata_get_memory(pParser, stringSizeWithNullTerminator, 1);
  64558. MA_DR_WAV_ASSERT(pMetadata->data.infoText.pString != NULL);
  64559. bytesRead = ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.infoText.pString, (size_t)stringSizeWithNullTerminator, NULL);
  64560. if (bytesRead == chunkSize) {
  64561. pParser->metadataCursor += 1;
  64562. } else {
  64563. }
  64564. } else {
  64565. pMetadata->data.infoText.stringLength = 0;
  64566. pMetadata->data.infoText.pString = NULL;
  64567. pParser->metadataCursor += 1;
  64568. }
  64569. }
  64570. return bytesRead;
  64571. }
  64572. MA_PRIVATE ma_uint64 ma_dr_wav__metadata_process_unknown_chunk(ma_dr_wav__metadata_parser* pParser, const ma_uint8* pChunkId, ma_uint64 chunkSize, ma_dr_wav_metadata_location location)
  64573. {
  64574. ma_uint64 bytesRead = 0;
  64575. if (location == ma_dr_wav_metadata_location_invalid) {
  64576. return 0;
  64577. }
  64578. if (ma_dr_wav_fourcc_equal(pChunkId, "data") || ma_dr_wav_fourcc_equal(pChunkId, "fmt ") || ma_dr_wav_fourcc_equal(pChunkId, "fact")) {
  64579. return 0;
  64580. }
  64581. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64582. pParser->metadataCount += 1;
  64583. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)chunkSize, 1);
  64584. } else {
  64585. ma_dr_wav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
  64586. pMetadata->type = ma_dr_wav_metadata_type_unknown;
  64587. pMetadata->data.unknown.chunkLocation = location;
  64588. pMetadata->data.unknown.id[0] = pChunkId[0];
  64589. pMetadata->data.unknown.id[1] = pChunkId[1];
  64590. pMetadata->data.unknown.id[2] = pChunkId[2];
  64591. pMetadata->data.unknown.id[3] = pChunkId[3];
  64592. pMetadata->data.unknown.dataSizeInBytes = (ma_uint32)chunkSize;
  64593. pMetadata->data.unknown.pData = (ma_uint8 *)ma_dr_wav__metadata_get_memory(pParser, (size_t)chunkSize, 1);
  64594. MA_DR_WAV_ASSERT(pMetadata->data.unknown.pData != NULL);
  64595. bytesRead = ma_dr_wav__metadata_parser_read(pParser, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes, NULL);
  64596. if (bytesRead == pMetadata->data.unknown.dataSizeInBytes) {
  64597. pParser->metadataCursor += 1;
  64598. } else {
  64599. }
  64600. }
  64601. return bytesRead;
  64602. }
  64603. MA_PRIVATE ma_bool32 ma_dr_wav__chunk_matches(ma_dr_wav_metadata_type allowedMetadataTypes, const ma_uint8* pChunkID, ma_dr_wav_metadata_type type, const char* pID)
  64604. {
  64605. return (allowedMetadataTypes & type) && ma_dr_wav_fourcc_equal(pChunkID, pID);
  64606. }
  64607. MA_PRIVATE ma_uint64 ma_dr_wav__metadata_process_chunk(ma_dr_wav__metadata_parser* pParser, const ma_dr_wav_chunk_header* pChunkHeader, ma_dr_wav_metadata_type allowedMetadataTypes)
  64608. {
  64609. const ma_uint8 *pChunkID = pChunkHeader->id.fourcc;
  64610. ma_uint64 bytesRead = 0;
  64611. if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_smpl, "smpl")) {
  64612. if (pChunkHeader->sizeInBytes >= MA_DR_WAV_SMPL_BYTES) {
  64613. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64614. ma_uint8 buffer[4];
  64615. size_t bytesJustRead;
  64616. if (!pParser->onSeek(pParser->pReadSeekUserData, 28, ma_dr_wav_seek_origin_current)) {
  64617. return bytesRead;
  64618. }
  64619. bytesRead += 28;
  64620. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
  64621. if (bytesJustRead == sizeof(buffer)) {
  64622. ma_uint32 loopCount = ma_dr_wav_bytes_to_u32(buffer);
  64623. ma_uint64 calculatedLoopCount;
  64624. calculatedLoopCount = (pChunkHeader->sizeInBytes - MA_DR_WAV_SMPL_BYTES) / MA_DR_WAV_SMPL_LOOP_BYTES;
  64625. if (calculatedLoopCount == loopCount) {
  64626. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
  64627. if (bytesJustRead == sizeof(buffer)) {
  64628. ma_uint32 samplerSpecificDataSizeInBytes = ma_dr_wav_bytes_to_u32(buffer);
  64629. pParser->metadataCount += 1;
  64630. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(ma_dr_wav_smpl_loop) * loopCount, MA_DR_WAV_METADATA_ALIGNMENT);
  64631. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, samplerSpecificDataSizeInBytes, 1);
  64632. }
  64633. } else {
  64634. }
  64635. }
  64636. } else {
  64637. bytesRead = ma_dr_wav__read_smpl_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
  64638. if (bytesRead == pChunkHeader->sizeInBytes) {
  64639. pParser->metadataCursor += 1;
  64640. } else {
  64641. }
  64642. }
  64643. } else {
  64644. }
  64645. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_inst, "inst")) {
  64646. if (pChunkHeader->sizeInBytes == MA_DR_WAV_INST_BYTES) {
  64647. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64648. pParser->metadataCount += 1;
  64649. } else {
  64650. bytesRead = ma_dr_wav__read_inst_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
  64651. if (bytesRead == pChunkHeader->sizeInBytes) {
  64652. pParser->metadataCursor += 1;
  64653. } else {
  64654. }
  64655. }
  64656. } else {
  64657. }
  64658. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_acid, "acid")) {
  64659. if (pChunkHeader->sizeInBytes == MA_DR_WAV_ACID_BYTES) {
  64660. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64661. pParser->metadataCount += 1;
  64662. } else {
  64663. bytesRead = ma_dr_wav__read_acid_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
  64664. if (bytesRead == pChunkHeader->sizeInBytes) {
  64665. pParser->metadataCursor += 1;
  64666. } else {
  64667. }
  64668. }
  64669. } else {
  64670. }
  64671. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_cue, "cue ")) {
  64672. if (pChunkHeader->sizeInBytes >= MA_DR_WAV_CUE_BYTES) {
  64673. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64674. size_t cueCount;
  64675. pParser->metadataCount += 1;
  64676. cueCount = (size_t)(pChunkHeader->sizeInBytes - MA_DR_WAV_CUE_BYTES) / MA_DR_WAV_CUE_POINT_BYTES;
  64677. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(ma_dr_wav_cue_point) * cueCount, MA_DR_WAV_METADATA_ALIGNMENT);
  64678. } else {
  64679. bytesRead = ma_dr_wav__read_cue_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
  64680. if (bytesRead == pChunkHeader->sizeInBytes) {
  64681. pParser->metadataCursor += 1;
  64682. } else {
  64683. }
  64684. }
  64685. } else {
  64686. }
  64687. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, pChunkID, ma_dr_wav_metadata_type_bext, "bext")) {
  64688. if (pChunkHeader->sizeInBytes >= MA_DR_WAV_BEXT_BYTES) {
  64689. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64690. char buffer[MA_DR_WAV_BEXT_DESCRIPTION_BYTES + 1];
  64691. size_t allocSizeNeeded = MA_DR_WAV_BEXT_UMID_BYTES;
  64692. size_t bytesJustRead;
  64693. buffer[MA_DR_WAV_BEXT_DESCRIPTION_BYTES] = '\0';
  64694. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, MA_DR_WAV_BEXT_DESCRIPTION_BYTES, &bytesRead);
  64695. if (bytesJustRead != MA_DR_WAV_BEXT_DESCRIPTION_BYTES) {
  64696. return bytesRead;
  64697. }
  64698. allocSizeNeeded += ma_dr_wav__strlen(buffer) + 1;
  64699. buffer[MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES] = '\0';
  64700. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES, &bytesRead);
  64701. if (bytesJustRead != MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES) {
  64702. return bytesRead;
  64703. }
  64704. allocSizeNeeded += ma_dr_wav__strlen(buffer) + 1;
  64705. buffer[MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES] = '\0';
  64706. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, buffer, MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES, &bytesRead);
  64707. if (bytesJustRead != MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES) {
  64708. return bytesRead;
  64709. }
  64710. allocSizeNeeded += ma_dr_wav__strlen(buffer) + 1;
  64711. allocSizeNeeded += (size_t)pChunkHeader->sizeInBytes - MA_DR_WAV_BEXT_BYTES;
  64712. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, allocSizeNeeded, 1);
  64713. pParser->metadataCount += 1;
  64714. } else {
  64715. bytesRead = ma_dr_wav__read_bext_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], pChunkHeader->sizeInBytes);
  64716. if (bytesRead == pChunkHeader->sizeInBytes) {
  64717. pParser->metadataCursor += 1;
  64718. } else {
  64719. }
  64720. }
  64721. } else {
  64722. }
  64723. } else if (ma_dr_wav_fourcc_equal(pChunkID, "LIST") || ma_dr_wav_fourcc_equal(pChunkID, "list")) {
  64724. ma_dr_wav_metadata_location listType = ma_dr_wav_metadata_location_invalid;
  64725. while (bytesRead < pChunkHeader->sizeInBytes) {
  64726. ma_uint8 subchunkId[4];
  64727. ma_uint8 subchunkSizeBuffer[4];
  64728. ma_uint64 subchunkDataSize;
  64729. ma_uint64 subchunkBytesRead = 0;
  64730. ma_uint64 bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, subchunkId, sizeof(subchunkId), &bytesRead);
  64731. if (bytesJustRead != sizeof(subchunkId)) {
  64732. break;
  64733. }
  64734. if (ma_dr_wav_fourcc_equal(subchunkId, "adtl")) {
  64735. listType = ma_dr_wav_metadata_location_inside_adtl_list;
  64736. continue;
  64737. } else if (ma_dr_wav_fourcc_equal(subchunkId, "INFO")) {
  64738. listType = ma_dr_wav_metadata_location_inside_info_list;
  64739. continue;
  64740. }
  64741. bytesJustRead = ma_dr_wav__metadata_parser_read(pParser, subchunkSizeBuffer, sizeof(subchunkSizeBuffer), &bytesRead);
  64742. if (bytesJustRead != sizeof(subchunkSizeBuffer)) {
  64743. break;
  64744. }
  64745. subchunkDataSize = ma_dr_wav_bytes_to_u32(subchunkSizeBuffer);
  64746. if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_label, "labl") || ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_note, "note")) {
  64747. if (subchunkDataSize >= MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES) {
  64748. ma_uint64 stringSizeWithNullTerm = subchunkDataSize - MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES;
  64749. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64750. pParser->metadataCount += 1;
  64751. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerm, 1);
  64752. } else {
  64753. subchunkBytesRead = ma_dr_wav__read_list_label_or_note_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize, ma_dr_wav_fourcc_equal(subchunkId, "labl") ? ma_dr_wav_metadata_type_list_label : ma_dr_wav_metadata_type_list_note);
  64754. if (subchunkBytesRead == subchunkDataSize) {
  64755. pParser->metadataCursor += 1;
  64756. } else {
  64757. }
  64758. }
  64759. } else {
  64760. }
  64761. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_labelled_cue_region, "ltxt")) {
  64762. if (subchunkDataSize >= MA_DR_WAV_LIST_LABELLED_TEXT_BYTES) {
  64763. ma_uint64 stringSizeWithNullTerminator = subchunkDataSize - MA_DR_WAV_LIST_LABELLED_TEXT_BYTES;
  64764. if (pParser->stage == ma_dr_wav__metadata_parser_stage_count) {
  64765. pParser->metadataCount += 1;
  64766. ma_dr_wav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerminator, 1);
  64767. } else {
  64768. subchunkBytesRead = ma_dr_wav__read_list_labelled_cue_region_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize);
  64769. if (subchunkBytesRead == subchunkDataSize) {
  64770. pParser->metadataCursor += 1;
  64771. } else {
  64772. }
  64773. }
  64774. } else {
  64775. }
  64776. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_software, "ISFT")) {
  64777. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_software);
  64778. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_copyright, "ICOP")) {
  64779. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_copyright);
  64780. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_title, "INAM")) {
  64781. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_title);
  64782. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_artist, "IART")) {
  64783. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_artist);
  64784. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_comment, "ICMT")) {
  64785. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_comment);
  64786. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_date, "ICRD")) {
  64787. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_date);
  64788. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_genre, "IGNR")) {
  64789. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_genre);
  64790. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_album, "IPRD")) {
  64791. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_album);
  64792. } else if (ma_dr_wav__chunk_matches(allowedMetadataTypes, subchunkId, ma_dr_wav_metadata_type_list_info_tracknumber, "ITRK")) {
  64793. subchunkBytesRead = ma_dr_wav__metadata_process_info_text_chunk(pParser, subchunkDataSize, ma_dr_wav_metadata_type_list_info_tracknumber);
  64794. } else if ((allowedMetadataTypes & ma_dr_wav_metadata_type_unknown) != 0) {
  64795. subchunkBytesRead = ma_dr_wav__metadata_process_unknown_chunk(pParser, subchunkId, subchunkDataSize, listType);
  64796. }
  64797. bytesRead += subchunkBytesRead;
  64798. MA_DR_WAV_ASSERT(subchunkBytesRead <= subchunkDataSize);
  64799. if (subchunkBytesRead < subchunkDataSize) {
  64800. ma_uint64 bytesToSeek = subchunkDataSize - subchunkBytesRead;
  64801. if (!pParser->onSeek(pParser->pReadSeekUserData, (int)bytesToSeek, ma_dr_wav_seek_origin_current)) {
  64802. break;
  64803. }
  64804. bytesRead += bytesToSeek;
  64805. }
  64806. if ((subchunkDataSize % 2) == 1) {
  64807. if (!pParser->onSeek(pParser->pReadSeekUserData, 1, ma_dr_wav_seek_origin_current)) {
  64808. break;
  64809. }
  64810. bytesRead += 1;
  64811. }
  64812. }
  64813. } else if ((allowedMetadataTypes & ma_dr_wav_metadata_type_unknown) != 0) {
  64814. bytesRead = ma_dr_wav__metadata_process_unknown_chunk(pParser, pChunkID, pChunkHeader->sizeInBytes, ma_dr_wav_metadata_location_top_level);
  64815. }
  64816. return bytesRead;
  64817. }
  64818. MA_PRIVATE ma_uint32 ma_dr_wav_get_bytes_per_pcm_frame(ma_dr_wav* pWav)
  64819. {
  64820. ma_uint32 bytesPerFrame;
  64821. if ((pWav->bitsPerSample & 0x7) == 0) {
  64822. bytesPerFrame = (pWav->bitsPerSample * pWav->fmt.channels) >> 3;
  64823. } else {
  64824. bytesPerFrame = pWav->fmt.blockAlign;
  64825. }
  64826. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) {
  64827. if (bytesPerFrame != pWav->fmt.channels) {
  64828. return 0;
  64829. }
  64830. }
  64831. return bytesPerFrame;
  64832. }
  64833. MA_API ma_uint16 ma_dr_wav_fmt_get_format(const ma_dr_wav_fmt* pFMT)
  64834. {
  64835. if (pFMT == NULL) {
  64836. return 0;
  64837. }
  64838. if (pFMT->formatTag != MA_DR_WAVE_FORMAT_EXTENSIBLE) {
  64839. return pFMT->formatTag;
  64840. } else {
  64841. return ma_dr_wav_bytes_to_u16(pFMT->subFormat);
  64842. }
  64843. }
  64844. MA_PRIVATE ma_bool32 ma_dr_wav_preinit(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pReadSeekUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  64845. {
  64846. if (pWav == NULL || onRead == NULL || onSeek == NULL) {
  64847. return MA_FALSE;
  64848. }
  64849. MA_DR_WAV_ZERO_MEMORY(pWav, sizeof(*pWav));
  64850. pWav->onRead = onRead;
  64851. pWav->onSeek = onSeek;
  64852. pWav->pUserData = pReadSeekUserData;
  64853. pWav->allocationCallbacks = ma_dr_wav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  64854. if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
  64855. return MA_FALSE;
  64856. }
  64857. return MA_TRUE;
  64858. }
  64859. MA_PRIVATE ma_bool32 ma_dr_wav_init__internal(ma_dr_wav* pWav, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags)
  64860. {
  64861. ma_result result;
  64862. ma_uint64 cursor;
  64863. ma_bool32 sequential;
  64864. ma_uint8 riff[4];
  64865. ma_dr_wav_fmt fmt;
  64866. unsigned short translatedFormatTag;
  64867. ma_uint64 dataChunkSize = 0;
  64868. ma_uint64 sampleCountFromFactChunk = 0;
  64869. ma_uint64 metadataStartPos;
  64870. ma_dr_wav__metadata_parser metadataParser;
  64871. ma_bool8 isProcessingMetadata = MA_FALSE;
  64872. ma_bool8 foundChunk_fmt = MA_FALSE;
  64873. ma_bool8 foundChunk_data = MA_FALSE;
  64874. ma_bool8 isAIFCFormType = MA_FALSE;
  64875. ma_uint64 aiffFrameCount = 0;
  64876. cursor = 0;
  64877. sequential = (flags & MA_DR_WAV_SEQUENTIAL) != 0;
  64878. MA_DR_WAV_ZERO_OBJECT(&fmt);
  64879. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) {
  64880. return MA_FALSE;
  64881. }
  64882. if (ma_dr_wav_fourcc_equal(riff, "RIFF")) {
  64883. pWav->container = ma_dr_wav_container_riff;
  64884. } else if (ma_dr_wav_fourcc_equal(riff, "RIFX")) {
  64885. pWav->container = ma_dr_wav_container_rifx;
  64886. } else if (ma_dr_wav_fourcc_equal(riff, "riff")) {
  64887. int i;
  64888. ma_uint8 riff2[12];
  64889. pWav->container = ma_dr_wav_container_w64;
  64890. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) {
  64891. return MA_FALSE;
  64892. }
  64893. for (i = 0; i < 12; ++i) {
  64894. if (riff2[i] != ma_dr_wavGUID_W64_RIFF[i+4]) {
  64895. return MA_FALSE;
  64896. }
  64897. }
  64898. } else if (ma_dr_wav_fourcc_equal(riff, "RF64")) {
  64899. pWav->container = ma_dr_wav_container_rf64;
  64900. } else if (ma_dr_wav_fourcc_equal(riff, "FORM")) {
  64901. pWav->container = ma_dr_wav_container_aiff;
  64902. } else {
  64903. return MA_FALSE;
  64904. }
  64905. if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) {
  64906. ma_uint8 chunkSizeBytes[4];
  64907. ma_uint8 wave[4];
  64908. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  64909. return MA_FALSE;
  64910. }
  64911. if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx) {
  64912. if (ma_dr_wav_bytes_to_u32_ex(chunkSizeBytes, pWav->container) < 36) {
  64913. return MA_FALSE;
  64914. }
  64915. } else if (pWav->container == ma_dr_wav_container_rf64) {
  64916. if (ma_dr_wav_bytes_to_u32_le(chunkSizeBytes) != 0xFFFFFFFF) {
  64917. return MA_FALSE;
  64918. }
  64919. } else {
  64920. return MA_FALSE;
  64921. }
  64922. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  64923. return MA_FALSE;
  64924. }
  64925. if (!ma_dr_wav_fourcc_equal(wave, "WAVE")) {
  64926. return MA_FALSE;
  64927. }
  64928. } else if (pWav->container == ma_dr_wav_container_w64) {
  64929. ma_uint8 chunkSizeBytes[8];
  64930. ma_uint8 wave[16];
  64931. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  64932. return MA_FALSE;
  64933. }
  64934. if (ma_dr_wav_bytes_to_u64(chunkSizeBytes) < 80) {
  64935. return MA_FALSE;
  64936. }
  64937. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  64938. return MA_FALSE;
  64939. }
  64940. if (!ma_dr_wav_guid_equal(wave, ma_dr_wavGUID_W64_WAVE)) {
  64941. return MA_FALSE;
  64942. }
  64943. } else if (pWav->container == ma_dr_wav_container_aiff) {
  64944. ma_uint8 chunkSizeBytes[4];
  64945. ma_uint8 aiff[4];
  64946. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  64947. return MA_FALSE;
  64948. }
  64949. if (ma_dr_wav_bytes_to_u32_be(chunkSizeBytes) < 18) {
  64950. return MA_FALSE;
  64951. }
  64952. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, aiff, sizeof(aiff), &cursor) != sizeof(aiff)) {
  64953. return MA_FALSE;
  64954. }
  64955. if (ma_dr_wav_fourcc_equal(aiff, "AIFF")) {
  64956. isAIFCFormType = MA_FALSE;
  64957. } else if (ma_dr_wav_fourcc_equal(aiff, "AIFC")) {
  64958. isAIFCFormType = MA_TRUE;
  64959. } else {
  64960. return MA_FALSE;
  64961. }
  64962. } else {
  64963. return MA_FALSE;
  64964. }
  64965. if (pWav->container == ma_dr_wav_container_rf64) {
  64966. ma_uint8 sizeBytes[8];
  64967. ma_uint64 bytesRemainingInChunk;
  64968. ma_dr_wav_chunk_header header;
  64969. result = ma_dr_wav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  64970. if (result != MA_SUCCESS) {
  64971. return MA_FALSE;
  64972. }
  64973. if (!ma_dr_wav_fourcc_equal(header.id.fourcc, "ds64")) {
  64974. return MA_FALSE;
  64975. }
  64976. bytesRemainingInChunk = header.sizeInBytes + header.paddingSize;
  64977. if (!ma_dr_wav__seek_forward(pWav->onSeek, 8, pWav->pUserData)) {
  64978. return MA_FALSE;
  64979. }
  64980. bytesRemainingInChunk -= 8;
  64981. cursor += 8;
  64982. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
  64983. return MA_FALSE;
  64984. }
  64985. bytesRemainingInChunk -= 8;
  64986. dataChunkSize = ma_dr_wav_bytes_to_u64(sizeBytes);
  64987. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
  64988. return MA_FALSE;
  64989. }
  64990. bytesRemainingInChunk -= 8;
  64991. sampleCountFromFactChunk = ma_dr_wav_bytes_to_u64(sizeBytes);
  64992. if (!ma_dr_wav__seek_forward(pWav->onSeek, bytesRemainingInChunk, pWav->pUserData)) {
  64993. return MA_FALSE;
  64994. }
  64995. cursor += bytesRemainingInChunk;
  64996. }
  64997. metadataStartPos = cursor;
  64998. isProcessingMetadata = !sequential && ((flags & MA_DR_WAV_WITH_METADATA) != 0);
  64999. if (pWav->container != ma_dr_wav_container_riff && pWav->container != ma_dr_wav_container_rf64) {
  65000. isProcessingMetadata = MA_FALSE;
  65001. }
  65002. MA_DR_WAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser));
  65003. if (isProcessingMetadata) {
  65004. metadataParser.onRead = pWav->onRead;
  65005. metadataParser.onSeek = pWav->onSeek;
  65006. metadataParser.pReadSeekUserData = pWav->pUserData;
  65007. metadataParser.stage = ma_dr_wav__metadata_parser_stage_count;
  65008. }
  65009. for (;;) {
  65010. ma_dr_wav_chunk_header header;
  65011. ma_uint64 chunkSize;
  65012. result = ma_dr_wav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  65013. if (result != MA_SUCCESS) {
  65014. break;
  65015. }
  65016. chunkSize = header.sizeInBytes;
  65017. if (!sequential && onChunk != NULL) {
  65018. ma_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt);
  65019. if (callbackBytesRead > 0) {
  65020. if (ma_dr_wav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == MA_FALSE) {
  65021. return MA_FALSE;
  65022. }
  65023. }
  65024. }
  65025. if (((pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) && ma_dr_wav_fourcc_equal(header.id.fourcc, "fmt ")) ||
  65026. ((pWav->container == ma_dr_wav_container_w64) && ma_dr_wav_guid_equal(header.id.guid, ma_dr_wavGUID_W64_FMT))) {
  65027. ma_uint8 fmtData[16];
  65028. foundChunk_fmt = MA_TRUE;
  65029. if (pWav->onRead(pWav->pUserData, fmtData, sizeof(fmtData)) != sizeof(fmtData)) {
  65030. return MA_FALSE;
  65031. }
  65032. cursor += sizeof(fmtData);
  65033. fmt.formatTag = ma_dr_wav_bytes_to_u16_ex(fmtData + 0, pWav->container);
  65034. fmt.channels = ma_dr_wav_bytes_to_u16_ex(fmtData + 2, pWav->container);
  65035. fmt.sampleRate = ma_dr_wav_bytes_to_u32_ex(fmtData + 4, pWav->container);
  65036. fmt.avgBytesPerSec = ma_dr_wav_bytes_to_u32_ex(fmtData + 8, pWav->container);
  65037. fmt.blockAlign = ma_dr_wav_bytes_to_u16_ex(fmtData + 12, pWav->container);
  65038. fmt.bitsPerSample = ma_dr_wav_bytes_to_u16_ex(fmtData + 14, pWav->container);
  65039. fmt.extendedSize = 0;
  65040. fmt.validBitsPerSample = 0;
  65041. fmt.channelMask = 0;
  65042. MA_DR_WAV_ZERO_MEMORY(fmt.subFormat, sizeof(fmt.subFormat));
  65043. if (header.sizeInBytes > 16) {
  65044. ma_uint8 fmt_cbSize[2];
  65045. int bytesReadSoFar = 0;
  65046. if (pWav->onRead(pWav->pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) {
  65047. return MA_FALSE;
  65048. }
  65049. cursor += sizeof(fmt_cbSize);
  65050. bytesReadSoFar = 18;
  65051. fmt.extendedSize = ma_dr_wav_bytes_to_u16_ex(fmt_cbSize, pWav->container);
  65052. if (fmt.extendedSize > 0) {
  65053. if (fmt.formatTag == MA_DR_WAVE_FORMAT_EXTENSIBLE) {
  65054. if (fmt.extendedSize != 22) {
  65055. return MA_FALSE;
  65056. }
  65057. }
  65058. if (fmt.formatTag == MA_DR_WAVE_FORMAT_EXTENSIBLE) {
  65059. ma_uint8 fmtext[22];
  65060. if (pWav->onRead(pWav->pUserData, fmtext, fmt.extendedSize) != fmt.extendedSize) {
  65061. return MA_FALSE;
  65062. }
  65063. fmt.validBitsPerSample = ma_dr_wav_bytes_to_u16_ex(fmtext + 0, pWav->container);
  65064. fmt.channelMask = ma_dr_wav_bytes_to_u32_ex(fmtext + 2, pWav->container);
  65065. ma_dr_wav_bytes_to_guid(fmtext + 6, fmt.subFormat);
  65066. } else {
  65067. if (pWav->onSeek(pWav->pUserData, fmt.extendedSize, ma_dr_wav_seek_origin_current) == MA_FALSE) {
  65068. return MA_FALSE;
  65069. }
  65070. }
  65071. cursor += fmt.extendedSize;
  65072. bytesReadSoFar += fmt.extendedSize;
  65073. }
  65074. if (pWav->onSeek(pWav->pUserData, (int)(header.sizeInBytes - bytesReadSoFar), ma_dr_wav_seek_origin_current) == MA_FALSE) {
  65075. return MA_FALSE;
  65076. }
  65077. cursor += (header.sizeInBytes - bytesReadSoFar);
  65078. }
  65079. if (header.paddingSize > 0) {
  65080. if (ma_dr_wav__seek_forward(pWav->onSeek, header.paddingSize, pWav->pUserData) == MA_FALSE) {
  65081. break;
  65082. }
  65083. cursor += header.paddingSize;
  65084. }
  65085. continue;
  65086. }
  65087. if (((pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) && ma_dr_wav_fourcc_equal(header.id.fourcc, "data")) ||
  65088. ((pWav->container == ma_dr_wav_container_w64) && ma_dr_wav_guid_equal(header.id.guid, ma_dr_wavGUID_W64_DATA))) {
  65089. foundChunk_data = MA_TRUE;
  65090. pWav->dataChunkDataPos = cursor;
  65091. if (pWav->container != ma_dr_wav_container_rf64) {
  65092. dataChunkSize = chunkSize;
  65093. }
  65094. if (sequential || !isProcessingMetadata) {
  65095. break;
  65096. } else {
  65097. chunkSize += header.paddingSize;
  65098. if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) {
  65099. break;
  65100. }
  65101. cursor += chunkSize;
  65102. continue;
  65103. }
  65104. }
  65105. if (((pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx || pWav->container == ma_dr_wav_container_rf64) && ma_dr_wav_fourcc_equal(header.id.fourcc, "fact")) ||
  65106. ((pWav->container == ma_dr_wav_container_w64) && ma_dr_wav_guid_equal(header.id.guid, ma_dr_wavGUID_W64_FACT))) {
  65107. if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx) {
  65108. ma_uint8 sampleCount[4];
  65109. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) {
  65110. return MA_FALSE;
  65111. }
  65112. chunkSize -= 4;
  65113. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) {
  65114. sampleCountFromFactChunk = ma_dr_wav_bytes_to_u32_ex(sampleCount, pWav->container);
  65115. } else {
  65116. sampleCountFromFactChunk = 0;
  65117. }
  65118. } else if (pWav->container == ma_dr_wav_container_w64) {
  65119. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) {
  65120. return MA_FALSE;
  65121. }
  65122. chunkSize -= 8;
  65123. } else if (pWav->container == ma_dr_wav_container_rf64) {
  65124. }
  65125. chunkSize += header.paddingSize;
  65126. if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) {
  65127. break;
  65128. }
  65129. cursor += chunkSize;
  65130. continue;
  65131. }
  65132. if (pWav->container == ma_dr_wav_container_aiff && ma_dr_wav_fourcc_equal(header.id.fourcc, "COMM")) {
  65133. ma_uint8 commData[24];
  65134. ma_uint32 commDataBytesToRead;
  65135. ma_uint16 channels;
  65136. ma_uint32 frameCount;
  65137. ma_uint16 sampleSizeInBits;
  65138. ma_int64 sampleRate;
  65139. ma_uint16 compressionFormat;
  65140. foundChunk_fmt = MA_TRUE;
  65141. if (isAIFCFormType) {
  65142. commDataBytesToRead = 24;
  65143. if (header.sizeInBytes < commDataBytesToRead) {
  65144. return MA_FALSE;
  65145. }
  65146. } else {
  65147. commDataBytesToRead = 18;
  65148. if (header.sizeInBytes != commDataBytesToRead) {
  65149. return MA_FALSE;
  65150. }
  65151. }
  65152. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, commData, commDataBytesToRead, &cursor) != commDataBytesToRead) {
  65153. return MA_FALSE;
  65154. }
  65155. channels = ma_dr_wav_bytes_to_u16_ex (commData + 0, pWav->container);
  65156. frameCount = ma_dr_wav_bytes_to_u32_ex (commData + 2, pWav->container);
  65157. sampleSizeInBits = ma_dr_wav_bytes_to_u16_ex (commData + 6, pWav->container);
  65158. sampleRate = ma_dr_wav_aiff_extented_to_s64(commData + 8);
  65159. if (sampleRate < 0 || sampleRate > 0xFFFFFFFF) {
  65160. return MA_FALSE;
  65161. }
  65162. if (isAIFCFormType) {
  65163. const ma_uint8* type = commData + 18;
  65164. if (ma_dr_wav_fourcc_equal(type, "NONE")) {
  65165. compressionFormat = MA_DR_WAVE_FORMAT_PCM;
  65166. } else if (ma_dr_wav_fourcc_equal(type, "raw ")) {
  65167. compressionFormat = MA_DR_WAVE_FORMAT_PCM;
  65168. if (sampleSizeInBits == 8) {
  65169. pWav->aiff.isUnsigned = MA_TRUE;
  65170. }
  65171. } else if (ma_dr_wav_fourcc_equal(type, "sowt")) {
  65172. compressionFormat = MA_DR_WAVE_FORMAT_PCM;
  65173. pWav->aiff.isLE = MA_TRUE;
  65174. } else if (ma_dr_wav_fourcc_equal(type, "fl32") || ma_dr_wav_fourcc_equal(type, "fl64") || ma_dr_wav_fourcc_equal(type, "FL32") || ma_dr_wav_fourcc_equal(type, "FL64")) {
  65175. compressionFormat = MA_DR_WAVE_FORMAT_IEEE_FLOAT;
  65176. } else if (ma_dr_wav_fourcc_equal(type, "alaw") || ma_dr_wav_fourcc_equal(type, "ALAW")) {
  65177. compressionFormat = MA_DR_WAVE_FORMAT_ALAW;
  65178. } else if (ma_dr_wav_fourcc_equal(type, "ulaw") || ma_dr_wav_fourcc_equal(type, "ULAW")) {
  65179. compressionFormat = MA_DR_WAVE_FORMAT_MULAW;
  65180. } else if (ma_dr_wav_fourcc_equal(type, "ima4")) {
  65181. compressionFormat = MA_DR_WAVE_FORMAT_DVI_ADPCM;
  65182. sampleSizeInBits = 4;
  65183. return MA_FALSE;
  65184. } else {
  65185. return MA_FALSE;
  65186. }
  65187. } else {
  65188. compressionFormat = MA_DR_WAVE_FORMAT_PCM;
  65189. }
  65190. aiffFrameCount = frameCount;
  65191. fmt.formatTag = compressionFormat;
  65192. fmt.channels = channels;
  65193. fmt.sampleRate = (ma_uint32)sampleRate;
  65194. fmt.bitsPerSample = sampleSizeInBits;
  65195. fmt.blockAlign = (ma_uint16)(fmt.channels * fmt.bitsPerSample / 8);
  65196. fmt.avgBytesPerSec = fmt.blockAlign * fmt.sampleRate;
  65197. if (fmt.blockAlign == 0 && compressionFormat == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  65198. fmt.blockAlign = 34 * fmt.channels;
  65199. }
  65200. if (compressionFormat == MA_DR_WAVE_FORMAT_ALAW || compressionFormat == MA_DR_WAVE_FORMAT_MULAW) {
  65201. if (fmt.bitsPerSample > 8) {
  65202. fmt.bitsPerSample = 8;
  65203. fmt.blockAlign = fmt.channels;
  65204. }
  65205. }
  65206. fmt.bitsPerSample += (fmt.bitsPerSample & 7);
  65207. if (isAIFCFormType) {
  65208. if (ma_dr_wav__seek_forward(pWav->onSeek, (chunkSize - commDataBytesToRead), pWav->pUserData) == MA_FALSE) {
  65209. return MA_FALSE;
  65210. }
  65211. cursor += (chunkSize - commDataBytesToRead);
  65212. }
  65213. continue;
  65214. }
  65215. if (pWav->container == ma_dr_wav_container_aiff && ma_dr_wav_fourcc_equal(header.id.fourcc, "SSND")) {
  65216. ma_uint8 offsetAndBlockSizeData[8];
  65217. ma_uint32 offset;
  65218. foundChunk_data = MA_TRUE;
  65219. if (ma_dr_wav__on_read(pWav->onRead, pWav->pUserData, offsetAndBlockSizeData, sizeof(offsetAndBlockSizeData), &cursor) != sizeof(offsetAndBlockSizeData)) {
  65220. return MA_FALSE;
  65221. }
  65222. offset = ma_dr_wav_bytes_to_u32_ex(offsetAndBlockSizeData + 0, pWav->container);
  65223. if (ma_dr_wav__seek_forward(pWav->onSeek, offset, pWav->pUserData) == MA_FALSE) {
  65224. return MA_FALSE;
  65225. }
  65226. cursor += offset;
  65227. pWav->dataChunkDataPos = cursor;
  65228. dataChunkSize = chunkSize;
  65229. if (sequential || !isProcessingMetadata) {
  65230. break;
  65231. } else {
  65232. if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) {
  65233. break;
  65234. }
  65235. cursor += chunkSize;
  65236. continue;
  65237. }
  65238. }
  65239. if (isProcessingMetadata) {
  65240. ma_uint64 metadataBytesRead;
  65241. metadataBytesRead = ma_dr_wav__metadata_process_chunk(&metadataParser, &header, ma_dr_wav_metadata_type_all_including_unknown);
  65242. MA_DR_WAV_ASSERT(metadataBytesRead <= header.sizeInBytes);
  65243. if (ma_dr_wav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == MA_FALSE) {
  65244. break;
  65245. }
  65246. }
  65247. chunkSize += header.paddingSize;
  65248. if (ma_dr_wav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == MA_FALSE) {
  65249. break;
  65250. }
  65251. cursor += chunkSize;
  65252. }
  65253. if (!foundChunk_fmt || !foundChunk_data) {
  65254. return MA_FALSE;
  65255. }
  65256. if ((fmt.sampleRate == 0 || fmt.sampleRate > MA_DR_WAV_MAX_SAMPLE_RATE ) ||
  65257. (fmt.channels == 0 || fmt.channels > MA_DR_WAV_MAX_CHANNELS ) ||
  65258. (fmt.bitsPerSample == 0 || fmt.bitsPerSample > MA_DR_WAV_MAX_BITS_PER_SAMPLE) ||
  65259. fmt.blockAlign == 0) {
  65260. return MA_FALSE;
  65261. }
  65262. translatedFormatTag = fmt.formatTag;
  65263. if (translatedFormatTag == MA_DR_WAVE_FORMAT_EXTENSIBLE) {
  65264. translatedFormatTag = ma_dr_wav_bytes_to_u16_ex(fmt.subFormat + 0, pWav->container);
  65265. }
  65266. if (!sequential) {
  65267. if (!ma_dr_wav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData)) {
  65268. return MA_FALSE;
  65269. }
  65270. cursor = pWav->dataChunkDataPos;
  65271. }
  65272. if (isProcessingMetadata && metadataParser.metadataCount > 0) {
  65273. if (ma_dr_wav__seek_from_start(pWav->onSeek, metadataStartPos, pWav->pUserData) == MA_FALSE) {
  65274. return MA_FALSE;
  65275. }
  65276. result = ma_dr_wav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks);
  65277. if (result != MA_SUCCESS) {
  65278. return MA_FALSE;
  65279. }
  65280. metadataParser.stage = ma_dr_wav__metadata_parser_stage_read;
  65281. for (;;) {
  65282. ma_dr_wav_chunk_header header;
  65283. ma_uint64 metadataBytesRead;
  65284. result = ma_dr_wav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  65285. if (result != MA_SUCCESS) {
  65286. break;
  65287. }
  65288. metadataBytesRead = ma_dr_wav__metadata_process_chunk(&metadataParser, &header, ma_dr_wav_metadata_type_all_including_unknown);
  65289. if (ma_dr_wav__seek_forward(pWav->onSeek, (header.sizeInBytes + header.paddingSize) - metadataBytesRead, pWav->pUserData) == MA_FALSE) {
  65290. ma_dr_wav_free(metadataParser.pMetadata, &pWav->allocationCallbacks);
  65291. return MA_FALSE;
  65292. }
  65293. }
  65294. pWav->pMetadata = metadataParser.pMetadata;
  65295. pWav->metadataCount = metadataParser.metadataCount;
  65296. }
  65297. if (dataChunkSize == 0xFFFFFFFF && (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rifx) && pWav->isSequentialWrite == MA_FALSE) {
  65298. dataChunkSize = 0;
  65299. for (;;) {
  65300. ma_uint8 temp[4096];
  65301. size_t bytesRead = pWav->onRead(pWav->pUserData, temp, sizeof(temp));
  65302. dataChunkSize += bytesRead;
  65303. if (bytesRead < sizeof(temp)) {
  65304. break;
  65305. }
  65306. }
  65307. }
  65308. if (ma_dr_wav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData) == MA_FALSE) {
  65309. ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks);
  65310. return MA_FALSE;
  65311. }
  65312. pWav->fmt = fmt;
  65313. pWav->sampleRate = fmt.sampleRate;
  65314. pWav->channels = fmt.channels;
  65315. pWav->bitsPerSample = fmt.bitsPerSample;
  65316. pWav->bytesRemaining = dataChunkSize;
  65317. pWav->translatedFormatTag = translatedFormatTag;
  65318. pWav->dataChunkDataSize = dataChunkSize;
  65319. if (sampleCountFromFactChunk != 0) {
  65320. pWav->totalPCMFrameCount = sampleCountFromFactChunk;
  65321. } else if (aiffFrameCount != 0) {
  65322. pWav->totalPCMFrameCount = aiffFrameCount;
  65323. } else {
  65324. ma_uint32 bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  65325. if (bytesPerFrame == 0) {
  65326. ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks);
  65327. return MA_FALSE;
  65328. }
  65329. pWav->totalPCMFrameCount = dataChunkSize / bytesPerFrame;
  65330. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) {
  65331. ma_uint64 totalBlockHeaderSizeInBytes;
  65332. ma_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  65333. if ((blockCount * fmt.blockAlign) < dataChunkSize) {
  65334. blockCount += 1;
  65335. }
  65336. totalBlockHeaderSizeInBytes = blockCount * (6*fmt.channels);
  65337. pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
  65338. }
  65339. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  65340. ma_uint64 totalBlockHeaderSizeInBytes;
  65341. ma_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  65342. if ((blockCount * fmt.blockAlign) < dataChunkSize) {
  65343. blockCount += 1;
  65344. }
  65345. totalBlockHeaderSizeInBytes = blockCount * (4*fmt.channels);
  65346. pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
  65347. pWav->totalPCMFrameCount += blockCount;
  65348. }
  65349. }
  65350. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  65351. if (pWav->channels > 2) {
  65352. ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks);
  65353. return MA_FALSE;
  65354. }
  65355. }
  65356. if (ma_dr_wav_get_bytes_per_pcm_frame(pWav) == 0) {
  65357. ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks);
  65358. return MA_FALSE;
  65359. }
  65360. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  65361. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) {
  65362. ma_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  65363. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels;
  65364. }
  65365. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  65366. ma_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  65367. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
  65368. }
  65369. #endif
  65370. return MA_TRUE;
  65371. }
  65372. MA_API ma_bool32 ma_dr_wav_init(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  65373. {
  65374. return ma_dr_wav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0, pAllocationCallbacks);
  65375. }
  65376. MA_API ma_bool32 ma_dr_wav_init_ex(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, ma_dr_wav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  65377. {
  65378. if (!ma_dr_wav_preinit(pWav, onRead, onSeek, pReadSeekUserData, pAllocationCallbacks)) {
  65379. return MA_FALSE;
  65380. }
  65381. return ma_dr_wav_init__internal(pWav, onChunk, pChunkUserData, flags);
  65382. }
  65383. MA_API ma_bool32 ma_dr_wav_init_with_metadata(ma_dr_wav* pWav, ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  65384. {
  65385. if (!ma_dr_wav_preinit(pWav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  65386. return MA_FALSE;
  65387. }
  65388. return ma_dr_wav_init__internal(pWav, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA);
  65389. }
  65390. MA_API ma_dr_wav_metadata* ma_dr_wav_take_ownership_of_metadata(ma_dr_wav* pWav)
  65391. {
  65392. ma_dr_wav_metadata *result = pWav->pMetadata;
  65393. pWav->pMetadata = NULL;
  65394. pWav->metadataCount = 0;
  65395. return result;
  65396. }
  65397. MA_PRIVATE size_t ma_dr_wav__write(ma_dr_wav* pWav, const void* pData, size_t dataSize)
  65398. {
  65399. MA_DR_WAV_ASSERT(pWav != NULL);
  65400. MA_DR_WAV_ASSERT(pWav->onWrite != NULL);
  65401. return pWav->onWrite(pWav->pUserData, pData, dataSize);
  65402. }
  65403. MA_PRIVATE size_t ma_dr_wav__write_byte(ma_dr_wav* pWav, ma_uint8 byte)
  65404. {
  65405. MA_DR_WAV_ASSERT(pWav != NULL);
  65406. MA_DR_WAV_ASSERT(pWav->onWrite != NULL);
  65407. return pWav->onWrite(pWav->pUserData, &byte, 1);
  65408. }
  65409. MA_PRIVATE size_t ma_dr_wav__write_u16ne_to_le(ma_dr_wav* pWav, ma_uint16 value)
  65410. {
  65411. MA_DR_WAV_ASSERT(pWav != NULL);
  65412. MA_DR_WAV_ASSERT(pWav->onWrite != NULL);
  65413. if (!ma_dr_wav__is_little_endian()) {
  65414. value = ma_dr_wav__bswap16(value);
  65415. }
  65416. return ma_dr_wav__write(pWav, &value, 2);
  65417. }
  65418. MA_PRIVATE size_t ma_dr_wav__write_u32ne_to_le(ma_dr_wav* pWav, ma_uint32 value)
  65419. {
  65420. MA_DR_WAV_ASSERT(pWav != NULL);
  65421. MA_DR_WAV_ASSERT(pWav->onWrite != NULL);
  65422. if (!ma_dr_wav__is_little_endian()) {
  65423. value = ma_dr_wav__bswap32(value);
  65424. }
  65425. return ma_dr_wav__write(pWav, &value, 4);
  65426. }
  65427. MA_PRIVATE size_t ma_dr_wav__write_u64ne_to_le(ma_dr_wav* pWav, ma_uint64 value)
  65428. {
  65429. MA_DR_WAV_ASSERT(pWav != NULL);
  65430. MA_DR_WAV_ASSERT(pWav->onWrite != NULL);
  65431. if (!ma_dr_wav__is_little_endian()) {
  65432. value = ma_dr_wav__bswap64(value);
  65433. }
  65434. return ma_dr_wav__write(pWav, &value, 8);
  65435. }
  65436. MA_PRIVATE size_t ma_dr_wav__write_f32ne_to_le(ma_dr_wav* pWav, float value)
  65437. {
  65438. union {
  65439. ma_uint32 u32;
  65440. float f32;
  65441. } u;
  65442. MA_DR_WAV_ASSERT(pWav != NULL);
  65443. MA_DR_WAV_ASSERT(pWav->onWrite != NULL);
  65444. u.f32 = value;
  65445. if (!ma_dr_wav__is_little_endian()) {
  65446. u.u32 = ma_dr_wav__bswap32(u.u32);
  65447. }
  65448. return ma_dr_wav__write(pWav, &u.u32, 4);
  65449. }
  65450. MA_PRIVATE size_t ma_dr_wav__write_or_count(ma_dr_wav* pWav, const void* pData, size_t dataSize)
  65451. {
  65452. if (pWav == NULL) {
  65453. return dataSize;
  65454. }
  65455. return ma_dr_wav__write(pWav, pData, dataSize);
  65456. }
  65457. MA_PRIVATE size_t ma_dr_wav__write_or_count_byte(ma_dr_wav* pWav, ma_uint8 byte)
  65458. {
  65459. if (pWav == NULL) {
  65460. return 1;
  65461. }
  65462. return ma_dr_wav__write_byte(pWav, byte);
  65463. }
  65464. MA_PRIVATE size_t ma_dr_wav__write_or_count_u16ne_to_le(ma_dr_wav* pWav, ma_uint16 value)
  65465. {
  65466. if (pWav == NULL) {
  65467. return 2;
  65468. }
  65469. return ma_dr_wav__write_u16ne_to_le(pWav, value);
  65470. }
  65471. MA_PRIVATE size_t ma_dr_wav__write_or_count_u32ne_to_le(ma_dr_wav* pWav, ma_uint32 value)
  65472. {
  65473. if (pWav == NULL) {
  65474. return 4;
  65475. }
  65476. return ma_dr_wav__write_u32ne_to_le(pWav, value);
  65477. }
  65478. #if 0
  65479. MA_PRIVATE size_t ma_dr_wav__write_or_count_u64ne_to_le(ma_dr_wav* pWav, ma_uint64 value)
  65480. {
  65481. if (pWav == NULL) {
  65482. return 8;
  65483. }
  65484. return ma_dr_wav__write_u64ne_to_le(pWav, value);
  65485. }
  65486. #endif
  65487. MA_PRIVATE size_t ma_dr_wav__write_or_count_f32ne_to_le(ma_dr_wav* pWav, float value)
  65488. {
  65489. if (pWav == NULL) {
  65490. return 4;
  65491. }
  65492. return ma_dr_wav__write_f32ne_to_le(pWav, value);
  65493. }
  65494. MA_PRIVATE size_t ma_dr_wav__write_or_count_string_to_fixed_size_buf(ma_dr_wav* pWav, char* str, size_t bufFixedSize)
  65495. {
  65496. size_t len;
  65497. if (pWav == NULL) {
  65498. return bufFixedSize;
  65499. }
  65500. len = ma_dr_wav__strlen_clamped(str, bufFixedSize);
  65501. ma_dr_wav__write_or_count(pWav, str, len);
  65502. if (len < bufFixedSize) {
  65503. size_t i;
  65504. for (i = 0; i < bufFixedSize - len; ++i) {
  65505. ma_dr_wav__write_byte(pWav, 0);
  65506. }
  65507. }
  65508. return bufFixedSize;
  65509. }
  65510. MA_PRIVATE size_t ma_dr_wav__write_or_count_metadata(ma_dr_wav* pWav, ma_dr_wav_metadata* pMetadatas, ma_uint32 metadataCount)
  65511. {
  65512. size_t bytesWritten = 0;
  65513. ma_bool32 hasListAdtl = MA_FALSE;
  65514. ma_bool32 hasListInfo = MA_FALSE;
  65515. ma_uint32 iMetadata;
  65516. if (pMetadatas == NULL || metadataCount == 0) {
  65517. return 0;
  65518. }
  65519. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65520. ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata];
  65521. ma_uint32 chunkSize = 0;
  65522. if ((pMetadata->type & ma_dr_wav_metadata_type_list_all_info_strings) || (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_info_list)) {
  65523. hasListInfo = MA_TRUE;
  65524. }
  65525. if ((pMetadata->type & ma_dr_wav_metadata_type_list_all_adtl) || (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_adtl_list)) {
  65526. hasListAdtl = MA_TRUE;
  65527. }
  65528. switch (pMetadata->type) {
  65529. case ma_dr_wav_metadata_type_smpl:
  65530. {
  65531. ma_uint32 iLoop;
  65532. chunkSize = MA_DR_WAV_SMPL_BYTES + MA_DR_WAV_SMPL_LOOP_BYTES * pMetadata->data.smpl.sampleLoopCount + pMetadata->data.smpl.samplerSpecificDataSizeInBytes;
  65533. bytesWritten += ma_dr_wav__write_or_count(pWav, "smpl", 4);
  65534. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65535. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.manufacturerId);
  65536. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.productId);
  65537. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplePeriodNanoseconds);
  65538. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiUnityNote);
  65539. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiPitchFraction);
  65540. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteFormat);
  65541. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteOffset);
  65542. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.sampleLoopCount);
  65543. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
  65544. for (iLoop = 0; iLoop < pMetadata->data.smpl.sampleLoopCount; ++iLoop) {
  65545. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].cuePointId);
  65546. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].type);
  65547. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleByteOffset);
  65548. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleByteOffset);
  65549. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].sampleFraction);
  65550. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].playCount);
  65551. }
  65552. if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
  65553. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
  65554. }
  65555. } break;
  65556. case ma_dr_wav_metadata_type_inst:
  65557. {
  65558. chunkSize = MA_DR_WAV_INST_BYTES;
  65559. bytesWritten += ma_dr_wav__write_or_count(pWav, "inst", 4);
  65560. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65561. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.midiUnityNote, 1);
  65562. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.fineTuneCents, 1);
  65563. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.gainDecibels, 1);
  65564. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.lowNote, 1);
  65565. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.highNote, 1);
  65566. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.lowVelocity, 1);
  65567. bytesWritten += ma_dr_wav__write_or_count(pWav, &pMetadata->data.inst.highVelocity, 1);
  65568. } break;
  65569. case ma_dr_wav_metadata_type_cue:
  65570. {
  65571. ma_uint32 iCuePoint;
  65572. chunkSize = MA_DR_WAV_CUE_BYTES + MA_DR_WAV_CUE_POINT_BYTES * pMetadata->data.cue.cuePointCount;
  65573. bytesWritten += ma_dr_wav__write_or_count(pWav, "cue ", 4);
  65574. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65575. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.cuePointCount);
  65576. for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
  65577. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].id);
  65578. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition);
  65579. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId, 4);
  65580. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart);
  65581. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].blockStart);
  65582. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset);
  65583. }
  65584. } break;
  65585. case ma_dr_wav_metadata_type_acid:
  65586. {
  65587. chunkSize = MA_DR_WAV_ACID_BYTES;
  65588. bytesWritten += ma_dr_wav__write_or_count(pWav, "acid", 4);
  65589. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65590. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.flags);
  65591. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.midiUnityNote);
  65592. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.reserved1);
  65593. bytesWritten += ma_dr_wav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.reserved2);
  65594. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.numBeats);
  65595. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterDenominator);
  65596. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterNumerator);
  65597. bytesWritten += ma_dr_wav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.tempo);
  65598. } break;
  65599. case ma_dr_wav_metadata_type_bext:
  65600. {
  65601. char reservedBuf[MA_DR_WAV_BEXT_RESERVED_BYTES];
  65602. ma_uint32 timeReferenceLow;
  65603. ma_uint32 timeReferenceHigh;
  65604. chunkSize = MA_DR_WAV_BEXT_BYTES + pMetadata->data.bext.codingHistorySize;
  65605. bytesWritten += ma_dr_wav__write_or_count(pWav, "bext", 4);
  65606. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65607. bytesWritten += ma_dr_wav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pDescription, MA_DR_WAV_BEXT_DESCRIPTION_BYTES);
  65608. bytesWritten += ma_dr_wav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorName, MA_DR_WAV_BEXT_ORIGINATOR_NAME_BYTES);
  65609. bytesWritten += ma_dr_wav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorReference, MA_DR_WAV_BEXT_ORIGINATOR_REF_BYTES);
  65610. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate));
  65611. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime));
  65612. timeReferenceLow = (ma_uint32)(pMetadata->data.bext.timeReference & 0xFFFFFFFF);
  65613. timeReferenceHigh = (ma_uint32)(pMetadata->data.bext.timeReference >> 32);
  65614. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, timeReferenceLow);
  65615. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, timeReferenceHigh);
  65616. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.version);
  65617. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pUMID, MA_DR_WAV_BEXT_UMID_BYTES);
  65618. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessValue);
  65619. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessRange);
  65620. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxTruePeakLevel);
  65621. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxMomentaryLoudness);
  65622. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxShortTermLoudness);
  65623. MA_DR_WAV_ZERO_MEMORY(reservedBuf, sizeof(reservedBuf));
  65624. bytesWritten += ma_dr_wav__write_or_count(pWav, reservedBuf, sizeof(reservedBuf));
  65625. if (pMetadata->data.bext.codingHistorySize > 0) {
  65626. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.bext.pCodingHistory, pMetadata->data.bext.codingHistorySize);
  65627. }
  65628. } break;
  65629. case ma_dr_wav_metadata_type_unknown:
  65630. {
  65631. if (pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_top_level) {
  65632. chunkSize = pMetadata->data.unknown.dataSizeInBytes;
  65633. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  65634. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65635. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes);
  65636. }
  65637. } break;
  65638. default: break;
  65639. }
  65640. if ((chunkSize % 2) != 0) {
  65641. bytesWritten += ma_dr_wav__write_or_count_byte(pWav, 0);
  65642. }
  65643. }
  65644. if (hasListInfo) {
  65645. ma_uint32 chunkSize = 4;
  65646. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65647. ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata];
  65648. if ((pMetadata->type & ma_dr_wav_metadata_type_list_all_info_strings)) {
  65649. chunkSize += 8;
  65650. chunkSize += pMetadata->data.infoText.stringLength + 1;
  65651. } else if (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_info_list) {
  65652. chunkSize += 8;
  65653. chunkSize += pMetadata->data.unknown.dataSizeInBytes;
  65654. }
  65655. if ((chunkSize % 2) != 0) {
  65656. chunkSize += 1;
  65657. }
  65658. }
  65659. bytesWritten += ma_dr_wav__write_or_count(pWav, "LIST", 4);
  65660. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65661. bytesWritten += ma_dr_wav__write_or_count(pWav, "INFO", 4);
  65662. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65663. ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata];
  65664. ma_uint32 subchunkSize = 0;
  65665. if (pMetadata->type & ma_dr_wav_metadata_type_list_all_info_strings) {
  65666. const char* pID = NULL;
  65667. switch (pMetadata->type) {
  65668. case ma_dr_wav_metadata_type_list_info_software: pID = "ISFT"; break;
  65669. case ma_dr_wav_metadata_type_list_info_copyright: pID = "ICOP"; break;
  65670. case ma_dr_wav_metadata_type_list_info_title: pID = "INAM"; break;
  65671. case ma_dr_wav_metadata_type_list_info_artist: pID = "IART"; break;
  65672. case ma_dr_wav_metadata_type_list_info_comment: pID = "ICMT"; break;
  65673. case ma_dr_wav_metadata_type_list_info_date: pID = "ICRD"; break;
  65674. case ma_dr_wav_metadata_type_list_info_genre: pID = "IGNR"; break;
  65675. case ma_dr_wav_metadata_type_list_info_album: pID = "IPRD"; break;
  65676. case ma_dr_wav_metadata_type_list_info_tracknumber: pID = "ITRK"; break;
  65677. default: break;
  65678. }
  65679. MA_DR_WAV_ASSERT(pID != NULL);
  65680. if (pMetadata->data.infoText.stringLength) {
  65681. subchunkSize = pMetadata->data.infoText.stringLength + 1;
  65682. bytesWritten += ma_dr_wav__write_or_count(pWav, pID, 4);
  65683. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65684. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.infoText.pString, pMetadata->data.infoText.stringLength);
  65685. bytesWritten += ma_dr_wav__write_or_count_byte(pWav, '\0');
  65686. }
  65687. } else if (pMetadata->type == ma_dr_wav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_info_list) {
  65688. if (pMetadata->data.unknown.dataSizeInBytes) {
  65689. subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
  65690. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  65691. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.unknown.dataSizeInBytes);
  65692. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
  65693. }
  65694. }
  65695. if ((subchunkSize % 2) != 0) {
  65696. bytesWritten += ma_dr_wav__write_or_count_byte(pWav, 0);
  65697. }
  65698. }
  65699. }
  65700. if (hasListAdtl) {
  65701. ma_uint32 chunkSize = 4;
  65702. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65703. ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata];
  65704. switch (pMetadata->type)
  65705. {
  65706. case ma_dr_wav_metadata_type_list_label:
  65707. case ma_dr_wav_metadata_type_list_note:
  65708. {
  65709. chunkSize += 8;
  65710. chunkSize += MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES;
  65711. if (pMetadata->data.labelOrNote.stringLength > 0) {
  65712. chunkSize += pMetadata->data.labelOrNote.stringLength + 1;
  65713. }
  65714. } break;
  65715. case ma_dr_wav_metadata_type_list_labelled_cue_region:
  65716. {
  65717. chunkSize += 8;
  65718. chunkSize += MA_DR_WAV_LIST_LABELLED_TEXT_BYTES;
  65719. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  65720. chunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
  65721. }
  65722. } break;
  65723. case ma_dr_wav_metadata_type_unknown:
  65724. {
  65725. if (pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_adtl_list) {
  65726. chunkSize += 8;
  65727. chunkSize += pMetadata->data.unknown.dataSizeInBytes;
  65728. }
  65729. } break;
  65730. default: break;
  65731. }
  65732. if ((chunkSize % 2) != 0) {
  65733. chunkSize += 1;
  65734. }
  65735. }
  65736. bytesWritten += ma_dr_wav__write_or_count(pWav, "LIST", 4);
  65737. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, chunkSize);
  65738. bytesWritten += ma_dr_wav__write_or_count(pWav, "adtl", 4);
  65739. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  65740. ma_dr_wav_metadata* pMetadata = &pMetadatas[iMetadata];
  65741. ma_uint32 subchunkSize = 0;
  65742. switch (pMetadata->type)
  65743. {
  65744. case ma_dr_wav_metadata_type_list_label:
  65745. case ma_dr_wav_metadata_type_list_note:
  65746. {
  65747. if (pMetadata->data.labelOrNote.stringLength > 0) {
  65748. const char *pID = NULL;
  65749. if (pMetadata->type == ma_dr_wav_metadata_type_list_label) {
  65750. pID = "labl";
  65751. }
  65752. else if (pMetadata->type == ma_dr_wav_metadata_type_list_note) {
  65753. pID = "note";
  65754. }
  65755. MA_DR_WAV_ASSERT(pID != NULL);
  65756. MA_DR_WAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
  65757. subchunkSize = MA_DR_WAV_LIST_LABEL_OR_NOTE_BYTES;
  65758. bytesWritten += ma_dr_wav__write_or_count(pWav, pID, 4);
  65759. subchunkSize += pMetadata->data.labelOrNote.stringLength + 1;
  65760. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65761. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelOrNote.cuePointId);
  65762. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.labelOrNote.pString, pMetadata->data.labelOrNote.stringLength);
  65763. bytesWritten += ma_dr_wav__write_or_count_byte(pWav, '\0');
  65764. }
  65765. } break;
  65766. case ma_dr_wav_metadata_type_list_labelled_cue_region:
  65767. {
  65768. subchunkSize = MA_DR_WAV_LIST_LABELLED_TEXT_BYTES;
  65769. bytesWritten += ma_dr_wav__write_or_count(pWav, "ltxt", 4);
  65770. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  65771. subchunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
  65772. }
  65773. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65774. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.cuePointId);
  65775. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.sampleLength);
  65776. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.labelledCueRegion.purposeId, 4);
  65777. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.country);
  65778. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.language);
  65779. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.dialect);
  65780. bytesWritten += ma_dr_wav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.codePage);
  65781. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  65782. MA_DR_WAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
  65783. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.labelledCueRegion.pString, pMetadata->data.labelledCueRegion.stringLength);
  65784. bytesWritten += ma_dr_wav__write_or_count_byte(pWav, '\0');
  65785. }
  65786. } break;
  65787. case ma_dr_wav_metadata_type_unknown:
  65788. {
  65789. if (pMetadata->data.unknown.chunkLocation == ma_dr_wav_metadata_location_inside_adtl_list) {
  65790. subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
  65791. MA_DR_WAV_ASSERT(pMetadata->data.unknown.pData != NULL);
  65792. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  65793. bytesWritten += ma_dr_wav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  65794. bytesWritten += ma_dr_wav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
  65795. }
  65796. } break;
  65797. default: break;
  65798. }
  65799. if ((subchunkSize % 2) != 0) {
  65800. bytesWritten += ma_dr_wav__write_or_count_byte(pWav, 0);
  65801. }
  65802. }
  65803. }
  65804. MA_DR_WAV_ASSERT((bytesWritten % 2) == 0);
  65805. return bytesWritten;
  65806. }
  65807. MA_PRIVATE ma_uint32 ma_dr_wav__riff_chunk_size_riff(ma_uint64 dataChunkSize, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount)
  65808. {
  65809. ma_uint64 chunkSize = 4 + 24 + (ma_uint64)ma_dr_wav__write_or_count_metadata(NULL, pMetadata, metadataCount) + 8 + dataChunkSize + ma_dr_wav__chunk_padding_size_riff(dataChunkSize);
  65810. if (chunkSize > 0xFFFFFFFFUL) {
  65811. chunkSize = 0xFFFFFFFFUL;
  65812. }
  65813. return (ma_uint32)chunkSize;
  65814. }
  65815. MA_PRIVATE ma_uint32 ma_dr_wav__data_chunk_size_riff(ma_uint64 dataChunkSize)
  65816. {
  65817. if (dataChunkSize <= 0xFFFFFFFFUL) {
  65818. return (ma_uint32)dataChunkSize;
  65819. } else {
  65820. return 0xFFFFFFFFUL;
  65821. }
  65822. }
  65823. MA_PRIVATE ma_uint64 ma_dr_wav__riff_chunk_size_w64(ma_uint64 dataChunkSize)
  65824. {
  65825. ma_uint64 dataSubchunkPaddingSize = ma_dr_wav__chunk_padding_size_w64(dataChunkSize);
  65826. return 80 + 24 + dataChunkSize + dataSubchunkPaddingSize;
  65827. }
  65828. MA_PRIVATE ma_uint64 ma_dr_wav__data_chunk_size_w64(ma_uint64 dataChunkSize)
  65829. {
  65830. return 24 + dataChunkSize;
  65831. }
  65832. MA_PRIVATE ma_uint64 ma_dr_wav__riff_chunk_size_rf64(ma_uint64 dataChunkSize, ma_dr_wav_metadata *metadata, ma_uint32 numMetadata)
  65833. {
  65834. ma_uint64 chunkSize = 4 + 36 + 24 + (ma_uint64)ma_dr_wav__write_or_count_metadata(NULL, metadata, numMetadata) + 8 + dataChunkSize + ma_dr_wav__chunk_padding_size_riff(dataChunkSize);
  65835. if (chunkSize > 0xFFFFFFFFUL) {
  65836. chunkSize = 0xFFFFFFFFUL;
  65837. }
  65838. return chunkSize;
  65839. }
  65840. MA_PRIVATE ma_uint64 ma_dr_wav__data_chunk_size_rf64(ma_uint64 dataChunkSize)
  65841. {
  65842. return dataChunkSize;
  65843. }
  65844. MA_PRIVATE ma_bool32 ma_dr_wav_preinit_write(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_bool32 isSequential, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  65845. {
  65846. if (pWav == NULL || onWrite == NULL) {
  65847. return MA_FALSE;
  65848. }
  65849. if (!isSequential && onSeek == NULL) {
  65850. return MA_FALSE;
  65851. }
  65852. if (pFormat->format == MA_DR_WAVE_FORMAT_EXTENSIBLE) {
  65853. return MA_FALSE;
  65854. }
  65855. if (pFormat->format == MA_DR_WAVE_FORMAT_ADPCM || pFormat->format == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  65856. return MA_FALSE;
  65857. }
  65858. MA_DR_WAV_ZERO_MEMORY(pWav, sizeof(*pWav));
  65859. pWav->onWrite = onWrite;
  65860. pWav->onSeek = onSeek;
  65861. pWav->pUserData = pUserData;
  65862. pWav->allocationCallbacks = ma_dr_wav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  65863. if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
  65864. return MA_FALSE;
  65865. }
  65866. pWav->fmt.formatTag = (ma_uint16)pFormat->format;
  65867. pWav->fmt.channels = (ma_uint16)pFormat->channels;
  65868. pWav->fmt.sampleRate = pFormat->sampleRate;
  65869. pWav->fmt.avgBytesPerSec = (ma_uint32)((pFormat->bitsPerSample * pFormat->sampleRate * pFormat->channels) / 8);
  65870. pWav->fmt.blockAlign = (ma_uint16)((pFormat->channels * pFormat->bitsPerSample) / 8);
  65871. pWav->fmt.bitsPerSample = (ma_uint16)pFormat->bitsPerSample;
  65872. pWav->fmt.extendedSize = 0;
  65873. pWav->isSequentialWrite = isSequential;
  65874. return MA_TRUE;
  65875. }
  65876. MA_PRIVATE ma_bool32 ma_dr_wav_init_write__internal(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount)
  65877. {
  65878. size_t runningPos = 0;
  65879. ma_uint64 initialDataChunkSize = 0;
  65880. ma_uint64 chunkSizeFMT;
  65881. if (pWav->isSequentialWrite) {
  65882. initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8;
  65883. if (pFormat->container == ma_dr_wav_container_riff) {
  65884. if (initialDataChunkSize > (0xFFFFFFFFUL - 36)) {
  65885. return MA_FALSE;
  65886. }
  65887. }
  65888. }
  65889. pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize;
  65890. if (pFormat->container == ma_dr_wav_container_riff) {
  65891. ma_uint32 chunkSizeRIFF = 28 + (ma_uint32)initialDataChunkSize;
  65892. runningPos += ma_dr_wav__write(pWav, "RIFF", 4);
  65893. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, chunkSizeRIFF);
  65894. runningPos += ma_dr_wav__write(pWav, "WAVE", 4);
  65895. } else if (pFormat->container == ma_dr_wav_container_w64) {
  65896. ma_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize;
  65897. runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_RIFF, 16);
  65898. runningPos += ma_dr_wav__write_u64ne_to_le(pWav, chunkSizeRIFF);
  65899. runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_WAVE, 16);
  65900. } else if (pFormat->container == ma_dr_wav_container_rf64) {
  65901. runningPos += ma_dr_wav__write(pWav, "RF64", 4);
  65902. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
  65903. runningPos += ma_dr_wav__write(pWav, "WAVE", 4);
  65904. } else {
  65905. return MA_FALSE;
  65906. }
  65907. if (pFormat->container == ma_dr_wav_container_rf64) {
  65908. ma_uint32 initialds64ChunkSize = 28;
  65909. ma_uint64 initialRiffChunkSize = 8 + initialds64ChunkSize + initialDataChunkSize;
  65910. runningPos += ma_dr_wav__write(pWav, "ds64", 4);
  65911. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, initialds64ChunkSize);
  65912. runningPos += ma_dr_wav__write_u64ne_to_le(pWav, initialRiffChunkSize);
  65913. runningPos += ma_dr_wav__write_u64ne_to_le(pWav, initialDataChunkSize);
  65914. runningPos += ma_dr_wav__write_u64ne_to_le(pWav, totalSampleCount);
  65915. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, 0);
  65916. }
  65917. if (pFormat->container == ma_dr_wav_container_riff || pFormat->container == ma_dr_wav_container_rf64) {
  65918. chunkSizeFMT = 16;
  65919. runningPos += ma_dr_wav__write(pWav, "fmt ", 4);
  65920. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, (ma_uint32)chunkSizeFMT);
  65921. } else if (pFormat->container == ma_dr_wav_container_w64) {
  65922. chunkSizeFMT = 40;
  65923. runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_FMT, 16);
  65924. runningPos += ma_dr_wav__write_u64ne_to_le(pWav, chunkSizeFMT);
  65925. }
  65926. runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.formatTag);
  65927. runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.channels);
  65928. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, pWav->fmt.sampleRate);
  65929. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, pWav->fmt.avgBytesPerSec);
  65930. runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.blockAlign);
  65931. runningPos += ma_dr_wav__write_u16ne_to_le(pWav, pWav->fmt.bitsPerSample);
  65932. if (!pWav->isSequentialWrite && pWav->pMetadata != NULL && pWav->metadataCount > 0 && (pFormat->container == ma_dr_wav_container_riff || pFormat->container == ma_dr_wav_container_rf64)) {
  65933. runningPos += ma_dr_wav__write_or_count_metadata(pWav, pWav->pMetadata, pWav->metadataCount);
  65934. }
  65935. pWav->dataChunkDataPos = runningPos;
  65936. if (pFormat->container == ma_dr_wav_container_riff) {
  65937. ma_uint32 chunkSizeDATA = (ma_uint32)initialDataChunkSize;
  65938. runningPos += ma_dr_wav__write(pWav, "data", 4);
  65939. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, chunkSizeDATA);
  65940. } else if (pFormat->container == ma_dr_wav_container_w64) {
  65941. ma_uint64 chunkSizeDATA = 24 + initialDataChunkSize;
  65942. runningPos += ma_dr_wav__write(pWav, ma_dr_wavGUID_W64_DATA, 16);
  65943. runningPos += ma_dr_wav__write_u64ne_to_le(pWav, chunkSizeDATA);
  65944. } else if (pFormat->container == ma_dr_wav_container_rf64) {
  65945. runningPos += ma_dr_wav__write(pWav, "data", 4);
  65946. runningPos += ma_dr_wav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
  65947. }
  65948. pWav->container = pFormat->container;
  65949. pWav->channels = (ma_uint16)pFormat->channels;
  65950. pWav->sampleRate = pFormat->sampleRate;
  65951. pWav->bitsPerSample = (ma_uint16)pFormat->bitsPerSample;
  65952. pWav->translatedFormatTag = (ma_uint16)pFormat->format;
  65953. pWav->dataChunkDataPos = runningPos;
  65954. return MA_TRUE;
  65955. }
  65956. MA_API ma_bool32 ma_dr_wav_init_write(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  65957. {
  65958. if (!ma_dr_wav_preinit_write(pWav, pFormat, MA_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
  65959. return MA_FALSE;
  65960. }
  65961. return ma_dr_wav_init_write__internal(pWav, pFormat, 0);
  65962. }
  65963. MA_API ma_bool32 ma_dr_wav_init_write_sequential(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  65964. {
  65965. if (!ma_dr_wav_preinit_write(pWav, pFormat, MA_TRUE, onWrite, NULL, pUserData, pAllocationCallbacks)) {
  65966. return MA_FALSE;
  65967. }
  65968. return ma_dr_wav_init_write__internal(pWav, pFormat, totalSampleCount);
  65969. }
  65970. MA_API ma_bool32 ma_dr_wav_init_write_sequential_pcm_frames(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, ma_dr_wav_write_proc onWrite, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  65971. {
  65972. if (pFormat == NULL) {
  65973. return MA_FALSE;
  65974. }
  65975. return ma_dr_wav_init_write_sequential(pWav, pFormat, totalPCMFrameCount*pFormat->channels, onWrite, pUserData, pAllocationCallbacks);
  65976. }
  65977. MA_API ma_bool32 ma_dr_wav_init_write_with_metadata(ma_dr_wav* pWav, const ma_dr_wav_data_format* pFormat, ma_dr_wav_write_proc onWrite, ma_dr_wav_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount)
  65978. {
  65979. if (!ma_dr_wav_preinit_write(pWav, pFormat, MA_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
  65980. return MA_FALSE;
  65981. }
  65982. pWav->pMetadata = pMetadata;
  65983. pWav->metadataCount = metadataCount;
  65984. return ma_dr_wav_init_write__internal(pWav, pFormat, 0);
  65985. }
  65986. MA_API ma_uint64 ma_dr_wav_target_write_size_bytes(const ma_dr_wav_data_format* pFormat, ma_uint64 totalFrameCount, ma_dr_wav_metadata* pMetadata, ma_uint32 metadataCount)
  65987. {
  65988. ma_uint64 targetDataSizeBytes = (ma_uint64)((ma_int64)totalFrameCount * pFormat->channels * pFormat->bitsPerSample/8.0);
  65989. ma_uint64 riffChunkSizeBytes;
  65990. ma_uint64 fileSizeBytes = 0;
  65991. if (pFormat->container == ma_dr_wav_container_riff) {
  65992. riffChunkSizeBytes = ma_dr_wav__riff_chunk_size_riff(targetDataSizeBytes, pMetadata, metadataCount);
  65993. fileSizeBytes = (8 + riffChunkSizeBytes);
  65994. } else if (pFormat->container == ma_dr_wav_container_w64) {
  65995. riffChunkSizeBytes = ma_dr_wav__riff_chunk_size_w64(targetDataSizeBytes);
  65996. fileSizeBytes = riffChunkSizeBytes;
  65997. } else if (pFormat->container == ma_dr_wav_container_rf64) {
  65998. riffChunkSizeBytes = ma_dr_wav__riff_chunk_size_rf64(targetDataSizeBytes, pMetadata, metadataCount);
  65999. fileSizeBytes = (8 + riffChunkSizeBytes);
  66000. }
  66001. return fileSizeBytes;
  66002. }
  66003. #ifndef MA_DR_WAV_NO_STDIO
  66004. MA_PRIVATE size_t ma_dr_wav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  66005. {
  66006. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  66007. }
  66008. MA_PRIVATE size_t ma_dr_wav__on_write_stdio(void* pUserData, const void* pData, size_t bytesToWrite)
  66009. {
  66010. return fwrite(pData, 1, bytesToWrite, (FILE*)pUserData);
  66011. }
  66012. MA_PRIVATE ma_bool32 ma_dr_wav__on_seek_stdio(void* pUserData, int offset, ma_dr_wav_seek_origin origin)
  66013. {
  66014. return fseek((FILE*)pUserData, offset, (origin == ma_dr_wav_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  66015. }
  66016. MA_API ma_bool32 ma_dr_wav_init_file(ma_dr_wav* pWav, const char* filename, const ma_allocation_callbacks* pAllocationCallbacks)
  66017. {
  66018. return ma_dr_wav_init_file_ex(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
  66019. }
  66020. MA_PRIVATE ma_bool32 ma_dr_wav_init_file__internal_FILE(ma_dr_wav* pWav, FILE* pFile, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66021. {
  66022. ma_bool32 result;
  66023. result = ma_dr_wav_preinit(pWav, ma_dr_wav__on_read_stdio, ma_dr_wav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  66024. if (result != MA_TRUE) {
  66025. fclose(pFile);
  66026. return result;
  66027. }
  66028. result = ma_dr_wav_init__internal(pWav, onChunk, pChunkUserData, flags);
  66029. if (result != MA_TRUE) {
  66030. fclose(pFile);
  66031. return result;
  66032. }
  66033. return MA_TRUE;
  66034. }
  66035. MA_API ma_bool32 ma_dr_wav_init_file_ex(ma_dr_wav* pWav, const char* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66036. {
  66037. FILE* pFile;
  66038. if (ma_fopen(&pFile, filename, "rb") != MA_SUCCESS) {
  66039. return MA_FALSE;
  66040. }
  66041. return ma_dr_wav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks);
  66042. }
  66043. #ifndef MA_DR_WAV_NO_WCHAR
  66044. MA_API ma_bool32 ma_dr_wav_init_file_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_allocation_callbacks* pAllocationCallbacks)
  66045. {
  66046. return ma_dr_wav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
  66047. }
  66048. MA_API ma_bool32 ma_dr_wav_init_file_ex_w(ma_dr_wav* pWav, const wchar_t* filename, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66049. {
  66050. FILE* pFile;
  66051. if (ma_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != MA_SUCCESS) {
  66052. return MA_FALSE;
  66053. }
  66054. return ma_dr_wav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks);
  66055. }
  66056. #endif
  66057. MA_API ma_bool32 ma_dr_wav_init_file_with_metadata(ma_dr_wav* pWav, const char* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66058. {
  66059. FILE* pFile;
  66060. if (ma_fopen(&pFile, filename, "rb") != MA_SUCCESS) {
  66061. return MA_FALSE;
  66062. }
  66063. return ma_dr_wav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA, pAllocationCallbacks);
  66064. }
  66065. #ifndef MA_DR_WAV_NO_WCHAR
  66066. MA_API ma_bool32 ma_dr_wav_init_file_with_metadata_w(ma_dr_wav* pWav, const wchar_t* filename, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66067. {
  66068. FILE* pFile;
  66069. if (ma_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != MA_SUCCESS) {
  66070. return MA_FALSE;
  66071. }
  66072. return ma_dr_wav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA, pAllocationCallbacks);
  66073. }
  66074. #endif
  66075. MA_PRIVATE ma_bool32 ma_dr_wav_init_file_write__internal_FILE(ma_dr_wav* pWav, FILE* pFile, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks)
  66076. {
  66077. ma_bool32 result;
  66078. result = ma_dr_wav_preinit_write(pWav, pFormat, isSequential, ma_dr_wav__on_write_stdio, ma_dr_wav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  66079. if (result != MA_TRUE) {
  66080. fclose(pFile);
  66081. return result;
  66082. }
  66083. result = ma_dr_wav_init_write__internal(pWav, pFormat, totalSampleCount);
  66084. if (result != MA_TRUE) {
  66085. fclose(pFile);
  66086. return result;
  66087. }
  66088. return MA_TRUE;
  66089. }
  66090. MA_PRIVATE ma_bool32 ma_dr_wav_init_file_write__internal(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks)
  66091. {
  66092. FILE* pFile;
  66093. if (ma_fopen(&pFile, filename, "wb") != MA_SUCCESS) {
  66094. return MA_FALSE;
  66095. }
  66096. return ma_dr_wav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
  66097. }
  66098. #ifndef MA_DR_WAV_NO_WCHAR
  66099. MA_PRIVATE ma_bool32 ma_dr_wav_init_file_write_w__internal(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks)
  66100. {
  66101. FILE* pFile;
  66102. if (ma_wfopen(&pFile, filename, L"wb", pAllocationCallbacks) != MA_SUCCESS) {
  66103. return MA_FALSE;
  66104. }
  66105. return ma_dr_wav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
  66106. }
  66107. #endif
  66108. MA_API ma_bool32 ma_dr_wav_init_file_write(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks)
  66109. {
  66110. return ma_dr_wav_init_file_write__internal(pWav, filename, pFormat, 0, MA_FALSE, pAllocationCallbacks);
  66111. }
  66112. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks)
  66113. {
  66114. return ma_dr_wav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, MA_TRUE, pAllocationCallbacks);
  66115. }
  66116. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames(ma_dr_wav* pWav, const char* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  66117. {
  66118. if (pFormat == NULL) {
  66119. return MA_FALSE;
  66120. }
  66121. return ma_dr_wav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  66122. }
  66123. #ifndef MA_DR_WAV_NO_WCHAR
  66124. MA_API ma_bool32 ma_dr_wav_init_file_write_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks)
  66125. {
  66126. return ma_dr_wav_init_file_write_w__internal(pWav, filename, pFormat, 0, MA_FALSE, pAllocationCallbacks);
  66127. }
  66128. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks)
  66129. {
  66130. return ma_dr_wav_init_file_write_w__internal(pWav, filename, pFormat, totalSampleCount, MA_TRUE, pAllocationCallbacks);
  66131. }
  66132. MA_API ma_bool32 ma_dr_wav_init_file_write_sequential_pcm_frames_w(ma_dr_wav* pWav, const wchar_t* filename, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  66133. {
  66134. if (pFormat == NULL) {
  66135. return MA_FALSE;
  66136. }
  66137. return ma_dr_wav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  66138. }
  66139. #endif
  66140. #endif
  66141. MA_PRIVATE size_t ma_dr_wav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  66142. {
  66143. ma_dr_wav* pWav = (ma_dr_wav*)pUserData;
  66144. size_t bytesRemaining;
  66145. MA_DR_WAV_ASSERT(pWav != NULL);
  66146. MA_DR_WAV_ASSERT(pWav->memoryStream.dataSize >= pWav->memoryStream.currentReadPos);
  66147. bytesRemaining = pWav->memoryStream.dataSize - pWav->memoryStream.currentReadPos;
  66148. if (bytesToRead > bytesRemaining) {
  66149. bytesToRead = bytesRemaining;
  66150. }
  66151. if (bytesToRead > 0) {
  66152. MA_DR_WAV_COPY_MEMORY(pBufferOut, pWav->memoryStream.data + pWav->memoryStream.currentReadPos, bytesToRead);
  66153. pWav->memoryStream.currentReadPos += bytesToRead;
  66154. }
  66155. return bytesToRead;
  66156. }
  66157. MA_PRIVATE ma_bool32 ma_dr_wav__on_seek_memory(void* pUserData, int offset, ma_dr_wav_seek_origin origin)
  66158. {
  66159. ma_dr_wav* pWav = (ma_dr_wav*)pUserData;
  66160. MA_DR_WAV_ASSERT(pWav != NULL);
  66161. if (origin == ma_dr_wav_seek_origin_current) {
  66162. if (offset > 0) {
  66163. if (pWav->memoryStream.currentReadPos + offset > pWav->memoryStream.dataSize) {
  66164. return MA_FALSE;
  66165. }
  66166. } else {
  66167. if (pWav->memoryStream.currentReadPos < (size_t)-offset) {
  66168. return MA_FALSE;
  66169. }
  66170. }
  66171. pWav->memoryStream.currentReadPos += offset;
  66172. } else {
  66173. if ((ma_uint32)offset <= pWav->memoryStream.dataSize) {
  66174. pWav->memoryStream.currentReadPos = offset;
  66175. } else {
  66176. return MA_FALSE;
  66177. }
  66178. }
  66179. return MA_TRUE;
  66180. }
  66181. MA_PRIVATE size_t ma_dr_wav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite)
  66182. {
  66183. ma_dr_wav* pWav = (ma_dr_wav*)pUserData;
  66184. size_t bytesRemaining;
  66185. MA_DR_WAV_ASSERT(pWav != NULL);
  66186. MA_DR_WAV_ASSERT(pWav->memoryStreamWrite.dataCapacity >= pWav->memoryStreamWrite.currentWritePos);
  66187. bytesRemaining = pWav->memoryStreamWrite.dataCapacity - pWav->memoryStreamWrite.currentWritePos;
  66188. if (bytesRemaining < bytesToWrite) {
  66189. void* pNewData;
  66190. size_t newDataCapacity = (pWav->memoryStreamWrite.dataCapacity == 0) ? 256 : pWav->memoryStreamWrite.dataCapacity * 2;
  66191. if ((newDataCapacity - pWav->memoryStreamWrite.currentWritePos) < bytesToWrite) {
  66192. newDataCapacity = pWav->memoryStreamWrite.currentWritePos + bytesToWrite;
  66193. }
  66194. pNewData = ma_dr_wav__realloc_from_callbacks(*pWav->memoryStreamWrite.ppData, newDataCapacity, pWav->memoryStreamWrite.dataCapacity, &pWav->allocationCallbacks);
  66195. if (pNewData == NULL) {
  66196. return 0;
  66197. }
  66198. *pWav->memoryStreamWrite.ppData = pNewData;
  66199. pWav->memoryStreamWrite.dataCapacity = newDataCapacity;
  66200. }
  66201. MA_DR_WAV_COPY_MEMORY(((ma_uint8*)(*pWav->memoryStreamWrite.ppData)) + pWav->memoryStreamWrite.currentWritePos, pDataIn, bytesToWrite);
  66202. pWav->memoryStreamWrite.currentWritePos += bytesToWrite;
  66203. if (pWav->memoryStreamWrite.dataSize < pWav->memoryStreamWrite.currentWritePos) {
  66204. pWav->memoryStreamWrite.dataSize = pWav->memoryStreamWrite.currentWritePos;
  66205. }
  66206. *pWav->memoryStreamWrite.pDataSize = pWav->memoryStreamWrite.dataSize;
  66207. return bytesToWrite;
  66208. }
  66209. MA_PRIVATE ma_bool32 ma_dr_wav__on_seek_memory_write(void* pUserData, int offset, ma_dr_wav_seek_origin origin)
  66210. {
  66211. ma_dr_wav* pWav = (ma_dr_wav*)pUserData;
  66212. MA_DR_WAV_ASSERT(pWav != NULL);
  66213. if (origin == ma_dr_wav_seek_origin_current) {
  66214. if (offset > 0) {
  66215. if (pWav->memoryStreamWrite.currentWritePos + offset > pWav->memoryStreamWrite.dataSize) {
  66216. offset = (int)(pWav->memoryStreamWrite.dataSize - pWav->memoryStreamWrite.currentWritePos);
  66217. }
  66218. } else {
  66219. if (pWav->memoryStreamWrite.currentWritePos < (size_t)-offset) {
  66220. offset = -(int)pWav->memoryStreamWrite.currentWritePos;
  66221. }
  66222. }
  66223. pWav->memoryStreamWrite.currentWritePos += offset;
  66224. } else {
  66225. if ((ma_uint32)offset <= pWav->memoryStreamWrite.dataSize) {
  66226. pWav->memoryStreamWrite.currentWritePos = offset;
  66227. } else {
  66228. pWav->memoryStreamWrite.currentWritePos = pWav->memoryStreamWrite.dataSize;
  66229. }
  66230. }
  66231. return MA_TRUE;
  66232. }
  66233. MA_API ma_bool32 ma_dr_wav_init_memory(ma_dr_wav* pWav, const void* data, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks)
  66234. {
  66235. return ma_dr_wav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0, pAllocationCallbacks);
  66236. }
  66237. MA_API ma_bool32 ma_dr_wav_init_memory_ex(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_dr_wav_chunk_proc onChunk, void* pChunkUserData, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66238. {
  66239. if (data == NULL || dataSize == 0) {
  66240. return MA_FALSE;
  66241. }
  66242. if (!ma_dr_wav_preinit(pWav, ma_dr_wav__on_read_memory, ma_dr_wav__on_seek_memory, pWav, pAllocationCallbacks)) {
  66243. return MA_FALSE;
  66244. }
  66245. pWav->memoryStream.data = (const ma_uint8*)data;
  66246. pWav->memoryStream.dataSize = dataSize;
  66247. pWav->memoryStream.currentReadPos = 0;
  66248. return ma_dr_wav_init__internal(pWav, onChunk, pChunkUserData, flags);
  66249. }
  66250. MA_API ma_bool32 ma_dr_wav_init_memory_with_metadata(ma_dr_wav* pWav, const void* data, size_t dataSize, ma_uint32 flags, const ma_allocation_callbacks* pAllocationCallbacks)
  66251. {
  66252. if (data == NULL || dataSize == 0) {
  66253. return MA_FALSE;
  66254. }
  66255. if (!ma_dr_wav_preinit(pWav, ma_dr_wav__on_read_memory, ma_dr_wav__on_seek_memory, pWav, pAllocationCallbacks)) {
  66256. return MA_FALSE;
  66257. }
  66258. pWav->memoryStream.data = (const ma_uint8*)data;
  66259. pWav->memoryStream.dataSize = dataSize;
  66260. pWav->memoryStream.currentReadPos = 0;
  66261. return ma_dr_wav_init__internal(pWav, NULL, NULL, flags | MA_DR_WAV_WITH_METADATA);
  66262. }
  66263. MA_PRIVATE ma_bool32 ma_dr_wav_init_memory_write__internal(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, ma_bool32 isSequential, const ma_allocation_callbacks* pAllocationCallbacks)
  66264. {
  66265. if (ppData == NULL || pDataSize == NULL) {
  66266. return MA_FALSE;
  66267. }
  66268. *ppData = NULL;
  66269. *pDataSize = 0;
  66270. if (!ma_dr_wav_preinit_write(pWav, pFormat, isSequential, ma_dr_wav__on_write_memory, ma_dr_wav__on_seek_memory_write, pWav, pAllocationCallbacks)) {
  66271. return MA_FALSE;
  66272. }
  66273. pWav->memoryStreamWrite.ppData = ppData;
  66274. pWav->memoryStreamWrite.pDataSize = pDataSize;
  66275. pWav->memoryStreamWrite.dataSize = 0;
  66276. pWav->memoryStreamWrite.dataCapacity = 0;
  66277. pWav->memoryStreamWrite.currentWritePos = 0;
  66278. return ma_dr_wav_init_write__internal(pWav, pFormat, totalSampleCount);
  66279. }
  66280. MA_API ma_bool32 ma_dr_wav_init_memory_write(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, const ma_allocation_callbacks* pAllocationCallbacks)
  66281. {
  66282. return ma_dr_wav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, MA_FALSE, pAllocationCallbacks);
  66283. }
  66284. MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalSampleCount, const ma_allocation_callbacks* pAllocationCallbacks)
  66285. {
  66286. return ma_dr_wav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, MA_TRUE, pAllocationCallbacks);
  66287. }
  66288. MA_API ma_bool32 ma_dr_wav_init_memory_write_sequential_pcm_frames(ma_dr_wav* pWav, void** ppData, size_t* pDataSize, const ma_dr_wav_data_format* pFormat, ma_uint64 totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  66289. {
  66290. if (pFormat == NULL) {
  66291. return MA_FALSE;
  66292. }
  66293. return ma_dr_wav_init_memory_write_sequential(pWav, ppData, pDataSize, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  66294. }
  66295. MA_API ma_result ma_dr_wav_uninit(ma_dr_wav* pWav)
  66296. {
  66297. ma_result result = MA_SUCCESS;
  66298. if (pWav == NULL) {
  66299. return MA_INVALID_ARGS;
  66300. }
  66301. if (pWav->onWrite != NULL) {
  66302. ma_uint32 paddingSize = 0;
  66303. if (pWav->container == ma_dr_wav_container_riff || pWav->container == ma_dr_wav_container_rf64) {
  66304. paddingSize = ma_dr_wav__chunk_padding_size_riff(pWav->dataChunkDataSize);
  66305. } else {
  66306. paddingSize = ma_dr_wav__chunk_padding_size_w64(pWav->dataChunkDataSize);
  66307. }
  66308. if (paddingSize > 0) {
  66309. ma_uint64 paddingData = 0;
  66310. ma_dr_wav__write(pWav, &paddingData, paddingSize);
  66311. }
  66312. if (pWav->onSeek && !pWav->isSequentialWrite) {
  66313. if (pWav->container == ma_dr_wav_container_riff) {
  66314. if (pWav->onSeek(pWav->pUserData, 4, ma_dr_wav_seek_origin_start)) {
  66315. ma_uint32 riffChunkSize = ma_dr_wav__riff_chunk_size_riff(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
  66316. ma_dr_wav__write_u32ne_to_le(pWav, riffChunkSize);
  66317. }
  66318. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 4, ma_dr_wav_seek_origin_start)) {
  66319. ma_uint32 dataChunkSize = ma_dr_wav__data_chunk_size_riff(pWav->dataChunkDataSize);
  66320. ma_dr_wav__write_u32ne_to_le(pWav, dataChunkSize);
  66321. }
  66322. } else if (pWav->container == ma_dr_wav_container_w64) {
  66323. if (pWav->onSeek(pWav->pUserData, 16, ma_dr_wav_seek_origin_start)) {
  66324. ma_uint64 riffChunkSize = ma_dr_wav__riff_chunk_size_w64(pWav->dataChunkDataSize);
  66325. ma_dr_wav__write_u64ne_to_le(pWav, riffChunkSize);
  66326. }
  66327. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 8, ma_dr_wav_seek_origin_start)) {
  66328. ma_uint64 dataChunkSize = ma_dr_wav__data_chunk_size_w64(pWav->dataChunkDataSize);
  66329. ma_dr_wav__write_u64ne_to_le(pWav, dataChunkSize);
  66330. }
  66331. } else if (pWav->container == ma_dr_wav_container_rf64) {
  66332. int ds64BodyPos = 12 + 8;
  66333. if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 0, ma_dr_wav_seek_origin_start)) {
  66334. ma_uint64 riffChunkSize = ma_dr_wav__riff_chunk_size_rf64(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
  66335. ma_dr_wav__write_u64ne_to_le(pWav, riffChunkSize);
  66336. }
  66337. if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 8, ma_dr_wav_seek_origin_start)) {
  66338. ma_uint64 dataChunkSize = ma_dr_wav__data_chunk_size_rf64(pWav->dataChunkDataSize);
  66339. ma_dr_wav__write_u64ne_to_le(pWav, dataChunkSize);
  66340. }
  66341. }
  66342. }
  66343. if (pWav->isSequentialWrite) {
  66344. if (pWav->dataChunkDataSize != pWav->dataChunkDataSizeTargetWrite) {
  66345. result = MA_INVALID_FILE;
  66346. }
  66347. }
  66348. } else {
  66349. ma_dr_wav_free(pWav->pMetadata, &pWav->allocationCallbacks);
  66350. }
  66351. #ifndef MA_DR_WAV_NO_STDIO
  66352. if (pWav->onRead == ma_dr_wav__on_read_stdio || pWav->onWrite == ma_dr_wav__on_write_stdio) {
  66353. fclose((FILE*)pWav->pUserData);
  66354. }
  66355. #endif
  66356. return result;
  66357. }
  66358. MA_API size_t ma_dr_wav_read_raw(ma_dr_wav* pWav, size_t bytesToRead, void* pBufferOut)
  66359. {
  66360. size_t bytesRead;
  66361. ma_uint32 bytesPerFrame;
  66362. if (pWav == NULL || bytesToRead == 0) {
  66363. return 0;
  66364. }
  66365. if (bytesToRead > pWav->bytesRemaining) {
  66366. bytesToRead = (size_t)pWav->bytesRemaining;
  66367. }
  66368. if (bytesToRead == 0) {
  66369. return 0;
  66370. }
  66371. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  66372. if (bytesPerFrame == 0) {
  66373. return 0;
  66374. }
  66375. if (pBufferOut != NULL) {
  66376. bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead);
  66377. } else {
  66378. bytesRead = 0;
  66379. while (bytesRead < bytesToRead) {
  66380. size_t bytesToSeek = (bytesToRead - bytesRead);
  66381. if (bytesToSeek > 0x7FFFFFFF) {
  66382. bytesToSeek = 0x7FFFFFFF;
  66383. }
  66384. if (pWav->onSeek(pWav->pUserData, (int)bytesToSeek, ma_dr_wav_seek_origin_current) == MA_FALSE) {
  66385. break;
  66386. }
  66387. bytesRead += bytesToSeek;
  66388. }
  66389. while (bytesRead < bytesToRead) {
  66390. ma_uint8 buffer[4096];
  66391. size_t bytesSeeked;
  66392. size_t bytesToSeek = (bytesToRead - bytesRead);
  66393. if (bytesToSeek > sizeof(buffer)) {
  66394. bytesToSeek = sizeof(buffer);
  66395. }
  66396. bytesSeeked = pWav->onRead(pWav->pUserData, buffer, bytesToSeek);
  66397. bytesRead += bytesSeeked;
  66398. if (bytesSeeked < bytesToSeek) {
  66399. break;
  66400. }
  66401. }
  66402. }
  66403. pWav->readCursorInPCMFrames += bytesRead / bytesPerFrame;
  66404. pWav->bytesRemaining -= bytesRead;
  66405. return bytesRead;
  66406. }
  66407. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut)
  66408. {
  66409. ma_uint32 bytesPerFrame;
  66410. ma_uint64 bytesToRead;
  66411. ma_uint64 framesRemainingInFile;
  66412. if (pWav == NULL || framesToRead == 0) {
  66413. return 0;
  66414. }
  66415. if (ma_dr_wav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  66416. return 0;
  66417. }
  66418. framesRemainingInFile = pWav->totalPCMFrameCount - pWav->readCursorInPCMFrames;
  66419. if (framesToRead > framesRemainingInFile) {
  66420. framesToRead = framesRemainingInFile;
  66421. }
  66422. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  66423. if (bytesPerFrame == 0) {
  66424. return 0;
  66425. }
  66426. bytesToRead = framesToRead * bytesPerFrame;
  66427. if (bytesToRead > MA_SIZE_MAX) {
  66428. bytesToRead = (MA_SIZE_MAX / bytesPerFrame) * bytesPerFrame;
  66429. }
  66430. if (bytesToRead == 0) {
  66431. return 0;
  66432. }
  66433. return ma_dr_wav_read_raw(pWav, (size_t)bytesToRead, pBufferOut) / bytesPerFrame;
  66434. }
  66435. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut)
  66436. {
  66437. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  66438. if (pBufferOut != NULL) {
  66439. ma_uint32 bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  66440. if (bytesPerFrame == 0) {
  66441. return 0;
  66442. }
  66443. ma_dr_wav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels);
  66444. }
  66445. return framesRead;
  66446. }
  66447. MA_API ma_uint64 ma_dr_wav_read_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToRead, void* pBufferOut)
  66448. {
  66449. ma_uint64 framesRead = 0;
  66450. if (ma_dr_wav_is_container_be(pWav->container)) {
  66451. if (pWav->container != ma_dr_wav_container_aiff || pWav->aiff.isLE == MA_FALSE) {
  66452. if (ma_dr_wav__is_little_endian()) {
  66453. framesRead = ma_dr_wav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
  66454. } else {
  66455. framesRead = ma_dr_wav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  66456. }
  66457. goto post_process;
  66458. }
  66459. }
  66460. if (ma_dr_wav__is_little_endian()) {
  66461. framesRead = ma_dr_wav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  66462. } else {
  66463. framesRead = ma_dr_wav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
  66464. }
  66465. post_process:
  66466. {
  66467. if (pWav->container == ma_dr_wav_container_aiff && pWav->bitsPerSample == 8 && pWav->aiff.isUnsigned == MA_FALSE) {
  66468. if (pBufferOut != NULL) {
  66469. ma_uint64 iSample;
  66470. for (iSample = 0; iSample < framesRead * pWav->channels; iSample += 1) {
  66471. ((ma_uint8*)pBufferOut)[iSample] += 128;
  66472. }
  66473. }
  66474. }
  66475. }
  66476. return framesRead;
  66477. }
  66478. MA_PRIVATE ma_bool32 ma_dr_wav_seek_to_first_pcm_frame(ma_dr_wav* pWav)
  66479. {
  66480. if (pWav->onWrite != NULL) {
  66481. return MA_FALSE;
  66482. }
  66483. if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, ma_dr_wav_seek_origin_start)) {
  66484. return MA_FALSE;
  66485. }
  66486. if (ma_dr_wav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  66487. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) {
  66488. MA_DR_WAV_ZERO_OBJECT(&pWav->msadpcm);
  66489. } else if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  66490. MA_DR_WAV_ZERO_OBJECT(&pWav->ima);
  66491. } else {
  66492. MA_DR_WAV_ASSERT(MA_FALSE);
  66493. }
  66494. }
  66495. pWav->readCursorInPCMFrames = 0;
  66496. pWav->bytesRemaining = pWav->dataChunkDataSize;
  66497. return MA_TRUE;
  66498. }
  66499. MA_API ma_bool32 ma_dr_wav_seek_to_pcm_frame(ma_dr_wav* pWav, ma_uint64 targetFrameIndex)
  66500. {
  66501. if (pWav == NULL || pWav->onSeek == NULL) {
  66502. return MA_FALSE;
  66503. }
  66504. if (pWav->onWrite != NULL) {
  66505. return MA_FALSE;
  66506. }
  66507. if (pWav->totalPCMFrameCount == 0) {
  66508. return MA_TRUE;
  66509. }
  66510. if (targetFrameIndex > pWav->totalPCMFrameCount) {
  66511. targetFrameIndex = pWav->totalPCMFrameCount;
  66512. }
  66513. if (ma_dr_wav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  66514. if (targetFrameIndex < pWav->readCursorInPCMFrames) {
  66515. if (!ma_dr_wav_seek_to_first_pcm_frame(pWav)) {
  66516. return MA_FALSE;
  66517. }
  66518. }
  66519. if (targetFrameIndex > pWav->readCursorInPCMFrames) {
  66520. ma_uint64 offsetInFrames = targetFrameIndex - pWav->readCursorInPCMFrames;
  66521. ma_int16 devnull[2048];
  66522. while (offsetInFrames > 0) {
  66523. ma_uint64 framesRead = 0;
  66524. ma_uint64 framesToRead = offsetInFrames;
  66525. if (framesToRead > ma_dr_wav_countof(devnull)/pWav->channels) {
  66526. framesToRead = ma_dr_wav_countof(devnull)/pWav->channels;
  66527. }
  66528. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) {
  66529. framesRead = ma_dr_wav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, devnull);
  66530. } else if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  66531. framesRead = ma_dr_wav_read_pcm_frames_s16__ima(pWav, framesToRead, devnull);
  66532. } else {
  66533. MA_DR_WAV_ASSERT(MA_FALSE);
  66534. }
  66535. if (framesRead != framesToRead) {
  66536. return MA_FALSE;
  66537. }
  66538. offsetInFrames -= framesRead;
  66539. }
  66540. }
  66541. } else {
  66542. ma_uint64 totalSizeInBytes;
  66543. ma_uint64 currentBytePos;
  66544. ma_uint64 targetBytePos;
  66545. ma_uint64 offset;
  66546. ma_uint32 bytesPerFrame;
  66547. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  66548. if (bytesPerFrame == 0) {
  66549. return MA_FALSE;
  66550. }
  66551. totalSizeInBytes = pWav->totalPCMFrameCount * bytesPerFrame;
  66552. currentBytePos = totalSizeInBytes - pWav->bytesRemaining;
  66553. targetBytePos = targetFrameIndex * bytesPerFrame;
  66554. if (currentBytePos < targetBytePos) {
  66555. offset = (targetBytePos - currentBytePos);
  66556. } else {
  66557. if (!ma_dr_wav_seek_to_first_pcm_frame(pWav)) {
  66558. return MA_FALSE;
  66559. }
  66560. offset = targetBytePos;
  66561. }
  66562. while (offset > 0) {
  66563. int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset);
  66564. if (!pWav->onSeek(pWav->pUserData, offset32, ma_dr_wav_seek_origin_current)) {
  66565. return MA_FALSE;
  66566. }
  66567. pWav->readCursorInPCMFrames += offset32 / bytesPerFrame;
  66568. pWav->bytesRemaining -= offset32;
  66569. offset -= offset32;
  66570. }
  66571. }
  66572. return MA_TRUE;
  66573. }
  66574. MA_API ma_result ma_dr_wav_get_cursor_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pCursor)
  66575. {
  66576. if (pCursor == NULL) {
  66577. return MA_INVALID_ARGS;
  66578. }
  66579. *pCursor = 0;
  66580. if (pWav == NULL) {
  66581. return MA_INVALID_ARGS;
  66582. }
  66583. *pCursor = pWav->readCursorInPCMFrames;
  66584. return MA_SUCCESS;
  66585. }
  66586. MA_API ma_result ma_dr_wav_get_length_in_pcm_frames(ma_dr_wav* pWav, ma_uint64* pLength)
  66587. {
  66588. if (pLength == NULL) {
  66589. return MA_INVALID_ARGS;
  66590. }
  66591. *pLength = 0;
  66592. if (pWav == NULL) {
  66593. return MA_INVALID_ARGS;
  66594. }
  66595. *pLength = pWav->totalPCMFrameCount;
  66596. return MA_SUCCESS;
  66597. }
  66598. MA_API size_t ma_dr_wav_write_raw(ma_dr_wav* pWav, size_t bytesToWrite, const void* pData)
  66599. {
  66600. size_t bytesWritten;
  66601. if (pWav == NULL || bytesToWrite == 0 || pData == NULL) {
  66602. return 0;
  66603. }
  66604. bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite);
  66605. pWav->dataChunkDataSize += bytesWritten;
  66606. return bytesWritten;
  66607. }
  66608. MA_API ma_uint64 ma_dr_wav_write_pcm_frames_le(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData)
  66609. {
  66610. ma_uint64 bytesToWrite;
  66611. ma_uint64 bytesWritten;
  66612. const ma_uint8* pRunningData;
  66613. if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
  66614. return 0;
  66615. }
  66616. bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
  66617. if (bytesToWrite > MA_SIZE_MAX) {
  66618. return 0;
  66619. }
  66620. bytesWritten = 0;
  66621. pRunningData = (const ma_uint8*)pData;
  66622. while (bytesToWrite > 0) {
  66623. size_t bytesJustWritten;
  66624. ma_uint64 bytesToWriteThisIteration;
  66625. bytesToWriteThisIteration = bytesToWrite;
  66626. MA_DR_WAV_ASSERT(bytesToWriteThisIteration <= MA_SIZE_MAX);
  66627. bytesJustWritten = ma_dr_wav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData);
  66628. if (bytesJustWritten == 0) {
  66629. break;
  66630. }
  66631. bytesToWrite -= bytesJustWritten;
  66632. bytesWritten += bytesJustWritten;
  66633. pRunningData += bytesJustWritten;
  66634. }
  66635. return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
  66636. }
  66637. MA_API ma_uint64 ma_dr_wav_write_pcm_frames_be(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData)
  66638. {
  66639. ma_uint64 bytesToWrite;
  66640. ma_uint64 bytesWritten;
  66641. ma_uint32 bytesPerSample;
  66642. const ma_uint8* pRunningData;
  66643. if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
  66644. return 0;
  66645. }
  66646. bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
  66647. if (bytesToWrite > MA_SIZE_MAX) {
  66648. return 0;
  66649. }
  66650. bytesWritten = 0;
  66651. pRunningData = (const ma_uint8*)pData;
  66652. bytesPerSample = ma_dr_wav_get_bytes_per_pcm_frame(pWav) / pWav->channels;
  66653. if (bytesPerSample == 0) {
  66654. return 0;
  66655. }
  66656. while (bytesToWrite > 0) {
  66657. ma_uint8 temp[4096];
  66658. ma_uint32 sampleCount;
  66659. size_t bytesJustWritten;
  66660. ma_uint64 bytesToWriteThisIteration;
  66661. bytesToWriteThisIteration = bytesToWrite;
  66662. MA_DR_WAV_ASSERT(bytesToWriteThisIteration <= MA_SIZE_MAX);
  66663. sampleCount = sizeof(temp)/bytesPerSample;
  66664. if (bytesToWriteThisIteration > ((ma_uint64)sampleCount)*bytesPerSample) {
  66665. bytesToWriteThisIteration = ((ma_uint64)sampleCount)*bytesPerSample;
  66666. }
  66667. MA_DR_WAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration);
  66668. ma_dr_wav__bswap_samples(temp, sampleCount, bytesPerSample);
  66669. bytesJustWritten = ma_dr_wav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp);
  66670. if (bytesJustWritten == 0) {
  66671. break;
  66672. }
  66673. bytesToWrite -= bytesJustWritten;
  66674. bytesWritten += bytesJustWritten;
  66675. pRunningData += bytesJustWritten;
  66676. }
  66677. return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
  66678. }
  66679. MA_API ma_uint64 ma_dr_wav_write_pcm_frames(ma_dr_wav* pWav, ma_uint64 framesToWrite, const void* pData)
  66680. {
  66681. if (ma_dr_wav__is_little_endian()) {
  66682. return ma_dr_wav_write_pcm_frames_le(pWav, framesToWrite, pData);
  66683. } else {
  66684. return ma_dr_wav_write_pcm_frames_be(pWav, framesToWrite, pData);
  66685. }
  66686. }
  66687. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__msadpcm(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  66688. {
  66689. ma_uint64 totalFramesRead = 0;
  66690. MA_DR_WAV_ASSERT(pWav != NULL);
  66691. MA_DR_WAV_ASSERT(framesToRead > 0);
  66692. while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66693. MA_DR_WAV_ASSERT(framesToRead > 0);
  66694. if (pWav->msadpcm.cachedFrameCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) {
  66695. if (pWav->channels == 1) {
  66696. ma_uint8 header[7];
  66697. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66698. return totalFramesRead;
  66699. }
  66700. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66701. pWav->msadpcm.predictor[0] = header[0];
  66702. pWav->msadpcm.delta[0] = ma_dr_wav_bytes_to_s16(header + 1);
  66703. pWav->msadpcm.prevFrames[0][1] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 3);
  66704. pWav->msadpcm.prevFrames[0][0] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 5);
  66705. pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0];
  66706. pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1];
  66707. pWav->msadpcm.cachedFrameCount = 2;
  66708. } else {
  66709. ma_uint8 header[14];
  66710. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66711. return totalFramesRead;
  66712. }
  66713. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66714. pWav->msadpcm.predictor[0] = header[0];
  66715. pWav->msadpcm.predictor[1] = header[1];
  66716. pWav->msadpcm.delta[0] = ma_dr_wav_bytes_to_s16(header + 2);
  66717. pWav->msadpcm.delta[1] = ma_dr_wav_bytes_to_s16(header + 4);
  66718. pWav->msadpcm.prevFrames[0][1] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 6);
  66719. pWav->msadpcm.prevFrames[1][1] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 8);
  66720. pWav->msadpcm.prevFrames[0][0] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 10);
  66721. pWav->msadpcm.prevFrames[1][0] = (ma_int32)ma_dr_wav_bytes_to_s16(header + 12);
  66722. pWav->msadpcm.cachedFrames[0] = pWav->msadpcm.prevFrames[0][0];
  66723. pWav->msadpcm.cachedFrames[1] = pWav->msadpcm.prevFrames[1][0];
  66724. pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1];
  66725. pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1];
  66726. pWav->msadpcm.cachedFrameCount = 2;
  66727. }
  66728. }
  66729. while (framesToRead > 0 && pWav->msadpcm.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66730. if (pBufferOut != NULL) {
  66731. ma_uint32 iSample = 0;
  66732. for (iSample = 0; iSample < pWav->channels; iSample += 1) {
  66733. pBufferOut[iSample] = (ma_int16)pWav->msadpcm.cachedFrames[(ma_dr_wav_countof(pWav->msadpcm.cachedFrames) - (pWav->msadpcm.cachedFrameCount*pWav->channels)) + iSample];
  66734. }
  66735. pBufferOut += pWav->channels;
  66736. }
  66737. framesToRead -= 1;
  66738. totalFramesRead += 1;
  66739. pWav->readCursorInPCMFrames += 1;
  66740. pWav->msadpcm.cachedFrameCount -= 1;
  66741. }
  66742. if (framesToRead == 0) {
  66743. break;
  66744. }
  66745. if (pWav->msadpcm.cachedFrameCount == 0) {
  66746. if (pWav->msadpcm.bytesRemainingInBlock == 0) {
  66747. continue;
  66748. } else {
  66749. static ma_int32 adaptationTable[] = {
  66750. 230, 230, 230, 230, 307, 409, 512, 614,
  66751. 768, 614, 512, 409, 307, 230, 230, 230
  66752. };
  66753. static ma_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 };
  66754. static ma_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 };
  66755. ma_uint8 nibbles;
  66756. ma_int32 nibble0;
  66757. ma_int32 nibble1;
  66758. if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) {
  66759. return totalFramesRead;
  66760. }
  66761. pWav->msadpcm.bytesRemainingInBlock -= 1;
  66762. nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; }
  66763. nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; }
  66764. if (pWav->channels == 1) {
  66765. ma_int32 newSample0;
  66766. ma_int32 newSample1;
  66767. newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  66768. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  66769. newSample0 = ma_dr_wav_clamp(newSample0, -32768, 32767);
  66770. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  66771. if (pWav->msadpcm.delta[0] < 16) {
  66772. pWav->msadpcm.delta[0] = 16;
  66773. }
  66774. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  66775. pWav->msadpcm.prevFrames[0][1] = newSample0;
  66776. newSample1 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  66777. newSample1 += nibble1 * pWav->msadpcm.delta[0];
  66778. newSample1 = ma_dr_wav_clamp(newSample1, -32768, 32767);
  66779. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8;
  66780. if (pWav->msadpcm.delta[0] < 16) {
  66781. pWav->msadpcm.delta[0] = 16;
  66782. }
  66783. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  66784. pWav->msadpcm.prevFrames[0][1] = newSample1;
  66785. pWav->msadpcm.cachedFrames[2] = newSample0;
  66786. pWav->msadpcm.cachedFrames[3] = newSample1;
  66787. pWav->msadpcm.cachedFrameCount = 2;
  66788. } else {
  66789. ma_int32 newSample0;
  66790. ma_int32 newSample1;
  66791. newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  66792. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  66793. newSample0 = ma_dr_wav_clamp(newSample0, -32768, 32767);
  66794. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  66795. if (pWav->msadpcm.delta[0] < 16) {
  66796. pWav->msadpcm.delta[0] = 16;
  66797. }
  66798. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  66799. pWav->msadpcm.prevFrames[0][1] = newSample0;
  66800. newSample1 = ((pWav->msadpcm.prevFrames[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevFrames[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8;
  66801. newSample1 += nibble1 * pWav->msadpcm.delta[1];
  66802. newSample1 = ma_dr_wav_clamp(newSample1, -32768, 32767);
  66803. pWav->msadpcm.delta[1] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8;
  66804. if (pWav->msadpcm.delta[1] < 16) {
  66805. pWav->msadpcm.delta[1] = 16;
  66806. }
  66807. pWav->msadpcm.prevFrames[1][0] = pWav->msadpcm.prevFrames[1][1];
  66808. pWav->msadpcm.prevFrames[1][1] = newSample1;
  66809. pWav->msadpcm.cachedFrames[2] = newSample0;
  66810. pWav->msadpcm.cachedFrames[3] = newSample1;
  66811. pWav->msadpcm.cachedFrameCount = 1;
  66812. }
  66813. }
  66814. }
  66815. }
  66816. return totalFramesRead;
  66817. }
  66818. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__ima(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  66819. {
  66820. ma_uint64 totalFramesRead = 0;
  66821. ma_uint32 iChannel;
  66822. static ma_int32 indexTable[16] = {
  66823. -1, -1, -1, -1, 2, 4, 6, 8,
  66824. -1, -1, -1, -1, 2, 4, 6, 8
  66825. };
  66826. static ma_int32 stepTable[89] = {
  66827. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  66828. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  66829. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  66830. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  66831. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  66832. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  66833. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  66834. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  66835. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  66836. };
  66837. MA_DR_WAV_ASSERT(pWav != NULL);
  66838. MA_DR_WAV_ASSERT(framesToRead > 0);
  66839. while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66840. MA_DR_WAV_ASSERT(framesToRead > 0);
  66841. if (pWav->ima.cachedFrameCount == 0 && pWav->ima.bytesRemainingInBlock == 0) {
  66842. if (pWav->channels == 1) {
  66843. ma_uint8 header[4];
  66844. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66845. return totalFramesRead;
  66846. }
  66847. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66848. if (header[2] >= ma_dr_wav_countof(stepTable)) {
  66849. pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, ma_dr_wav_seek_origin_current);
  66850. pWav->ima.bytesRemainingInBlock = 0;
  66851. return totalFramesRead;
  66852. }
  66853. pWav->ima.predictor[0] = (ma_int16)ma_dr_wav_bytes_to_u16(header + 0);
  66854. pWav->ima.stepIndex[0] = ma_dr_wav_clamp(header[2], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1);
  66855. pWav->ima.cachedFrames[ma_dr_wav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0];
  66856. pWav->ima.cachedFrameCount = 1;
  66857. } else {
  66858. ma_uint8 header[8];
  66859. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  66860. return totalFramesRead;
  66861. }
  66862. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  66863. if (header[2] >= ma_dr_wav_countof(stepTable) || header[6] >= ma_dr_wav_countof(stepTable)) {
  66864. pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, ma_dr_wav_seek_origin_current);
  66865. pWav->ima.bytesRemainingInBlock = 0;
  66866. return totalFramesRead;
  66867. }
  66868. pWav->ima.predictor[0] = ma_dr_wav_bytes_to_s16(header + 0);
  66869. pWav->ima.stepIndex[0] = ma_dr_wav_clamp(header[2], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1);
  66870. pWav->ima.predictor[1] = ma_dr_wav_bytes_to_s16(header + 4);
  66871. pWav->ima.stepIndex[1] = ma_dr_wav_clamp(header[6], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1);
  66872. pWav->ima.cachedFrames[ma_dr_wav_countof(pWav->ima.cachedFrames) - 2] = pWav->ima.predictor[0];
  66873. pWav->ima.cachedFrames[ma_dr_wav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[1];
  66874. pWav->ima.cachedFrameCount = 1;
  66875. }
  66876. }
  66877. while (framesToRead > 0 && pWav->ima.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  66878. if (pBufferOut != NULL) {
  66879. ma_uint32 iSample;
  66880. for (iSample = 0; iSample < pWav->channels; iSample += 1) {
  66881. pBufferOut[iSample] = (ma_int16)pWav->ima.cachedFrames[(ma_dr_wav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + iSample];
  66882. }
  66883. pBufferOut += pWav->channels;
  66884. }
  66885. framesToRead -= 1;
  66886. totalFramesRead += 1;
  66887. pWav->readCursorInPCMFrames += 1;
  66888. pWav->ima.cachedFrameCount -= 1;
  66889. }
  66890. if (framesToRead == 0) {
  66891. break;
  66892. }
  66893. if (pWav->ima.cachedFrameCount == 0) {
  66894. if (pWav->ima.bytesRemainingInBlock == 0) {
  66895. continue;
  66896. } else {
  66897. pWav->ima.cachedFrameCount = 8;
  66898. for (iChannel = 0; iChannel < pWav->channels; ++iChannel) {
  66899. ma_uint32 iByte;
  66900. ma_uint8 nibbles[4];
  66901. if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) {
  66902. pWav->ima.cachedFrameCount = 0;
  66903. return totalFramesRead;
  66904. }
  66905. pWav->ima.bytesRemainingInBlock -= 4;
  66906. for (iByte = 0; iByte < 4; ++iByte) {
  66907. ma_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0);
  66908. ma_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4);
  66909. ma_int32 step = stepTable[pWav->ima.stepIndex[iChannel]];
  66910. ma_int32 predictor = pWav->ima.predictor[iChannel];
  66911. ma_int32 diff = step >> 3;
  66912. if (nibble0 & 1) diff += step >> 2;
  66913. if (nibble0 & 2) diff += step >> 1;
  66914. if (nibble0 & 4) diff += step;
  66915. if (nibble0 & 8) diff = -diff;
  66916. predictor = ma_dr_wav_clamp(predictor + diff, -32768, 32767);
  66917. pWav->ima.predictor[iChannel] = predictor;
  66918. pWav->ima.stepIndex[iChannel] = ma_dr_wav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1);
  66919. pWav->ima.cachedFrames[(ma_dr_wav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+0)*pWav->channels + iChannel] = predictor;
  66920. step = stepTable[pWav->ima.stepIndex[iChannel]];
  66921. predictor = pWav->ima.predictor[iChannel];
  66922. diff = step >> 3;
  66923. if (nibble1 & 1) diff += step >> 2;
  66924. if (nibble1 & 2) diff += step >> 1;
  66925. if (nibble1 & 4) diff += step;
  66926. if (nibble1 & 8) diff = -diff;
  66927. predictor = ma_dr_wav_clamp(predictor + diff, -32768, 32767);
  66928. pWav->ima.predictor[iChannel] = predictor;
  66929. pWav->ima.stepIndex[iChannel] = ma_dr_wav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (ma_int32)ma_dr_wav_countof(stepTable)-1);
  66930. pWav->ima.cachedFrames[(ma_dr_wav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+1)*pWav->channels + iChannel] = predictor;
  66931. }
  66932. }
  66933. }
  66934. }
  66935. }
  66936. return totalFramesRead;
  66937. }
  66938. #ifndef MA_DR_WAV_NO_CONVERSION_API
  66939. static unsigned short g_ma_dr_wavAlawTable[256] = {
  66940. 0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580,
  66941. 0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0,
  66942. 0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600,
  66943. 0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00,
  66944. 0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58,
  66945. 0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58,
  66946. 0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960,
  66947. 0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0,
  66948. 0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80,
  66949. 0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40,
  66950. 0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00,
  66951. 0x2B00, 0x2900, 0x2F00, 0x2D00, 0x2300, 0x2100, 0x2700, 0x2500, 0x3B00, 0x3900, 0x3F00, 0x3D00, 0x3300, 0x3100, 0x3700, 0x3500,
  66952. 0x0158, 0x0148, 0x0178, 0x0168, 0x0118, 0x0108, 0x0138, 0x0128, 0x01D8, 0x01C8, 0x01F8, 0x01E8, 0x0198, 0x0188, 0x01B8, 0x01A8,
  66953. 0x0058, 0x0048, 0x0078, 0x0068, 0x0018, 0x0008, 0x0038, 0x0028, 0x00D8, 0x00C8, 0x00F8, 0x00E8, 0x0098, 0x0088, 0x00B8, 0x00A8,
  66954. 0x0560, 0x0520, 0x05E0, 0x05A0, 0x0460, 0x0420, 0x04E0, 0x04A0, 0x0760, 0x0720, 0x07E0, 0x07A0, 0x0660, 0x0620, 0x06E0, 0x06A0,
  66955. 0x02B0, 0x0290, 0x02F0, 0x02D0, 0x0230, 0x0210, 0x0270, 0x0250, 0x03B0, 0x0390, 0x03F0, 0x03D0, 0x0330, 0x0310, 0x0370, 0x0350
  66956. };
  66957. static unsigned short g_ma_dr_wavMulawTable[256] = {
  66958. 0x8284, 0x8684, 0x8A84, 0x8E84, 0x9284, 0x9684, 0x9A84, 0x9E84, 0xA284, 0xA684, 0xAA84, 0xAE84, 0xB284, 0xB684, 0xBA84, 0xBE84,
  66959. 0xC184, 0xC384, 0xC584, 0xC784, 0xC984, 0xCB84, 0xCD84, 0xCF84, 0xD184, 0xD384, 0xD584, 0xD784, 0xD984, 0xDB84, 0xDD84, 0xDF84,
  66960. 0xE104, 0xE204, 0xE304, 0xE404, 0xE504, 0xE604, 0xE704, 0xE804, 0xE904, 0xEA04, 0xEB04, 0xEC04, 0xED04, 0xEE04, 0xEF04, 0xF004,
  66961. 0xF0C4, 0xF144, 0xF1C4, 0xF244, 0xF2C4, 0xF344, 0xF3C4, 0xF444, 0xF4C4, 0xF544, 0xF5C4, 0xF644, 0xF6C4, 0xF744, 0xF7C4, 0xF844,
  66962. 0xF8A4, 0xF8E4, 0xF924, 0xF964, 0xF9A4, 0xF9E4, 0xFA24, 0xFA64, 0xFAA4, 0xFAE4, 0xFB24, 0xFB64, 0xFBA4, 0xFBE4, 0xFC24, 0xFC64,
  66963. 0xFC94, 0xFCB4, 0xFCD4, 0xFCF4, 0xFD14, 0xFD34, 0xFD54, 0xFD74, 0xFD94, 0xFDB4, 0xFDD4, 0xFDF4, 0xFE14, 0xFE34, 0xFE54, 0xFE74,
  66964. 0xFE8C, 0xFE9C, 0xFEAC, 0xFEBC, 0xFECC, 0xFEDC, 0xFEEC, 0xFEFC, 0xFF0C, 0xFF1C, 0xFF2C, 0xFF3C, 0xFF4C, 0xFF5C, 0xFF6C, 0xFF7C,
  66965. 0xFF88, 0xFF90, 0xFF98, 0xFFA0, 0xFFA8, 0xFFB0, 0xFFB8, 0xFFC0, 0xFFC8, 0xFFD0, 0xFFD8, 0xFFE0, 0xFFE8, 0xFFF0, 0xFFF8, 0x0000,
  66966. 0x7D7C, 0x797C, 0x757C, 0x717C, 0x6D7C, 0x697C, 0x657C, 0x617C, 0x5D7C, 0x597C, 0x557C, 0x517C, 0x4D7C, 0x497C, 0x457C, 0x417C,
  66967. 0x3E7C, 0x3C7C, 0x3A7C, 0x387C, 0x367C, 0x347C, 0x327C, 0x307C, 0x2E7C, 0x2C7C, 0x2A7C, 0x287C, 0x267C, 0x247C, 0x227C, 0x207C,
  66968. 0x1EFC, 0x1DFC, 0x1CFC, 0x1BFC, 0x1AFC, 0x19FC, 0x18FC, 0x17FC, 0x16FC, 0x15FC, 0x14FC, 0x13FC, 0x12FC, 0x11FC, 0x10FC, 0x0FFC,
  66969. 0x0F3C, 0x0EBC, 0x0E3C, 0x0DBC, 0x0D3C, 0x0CBC, 0x0C3C, 0x0BBC, 0x0B3C, 0x0ABC, 0x0A3C, 0x09BC, 0x093C, 0x08BC, 0x083C, 0x07BC,
  66970. 0x075C, 0x071C, 0x06DC, 0x069C, 0x065C, 0x061C, 0x05DC, 0x059C, 0x055C, 0x051C, 0x04DC, 0x049C, 0x045C, 0x041C, 0x03DC, 0x039C,
  66971. 0x036C, 0x034C, 0x032C, 0x030C, 0x02EC, 0x02CC, 0x02AC, 0x028C, 0x026C, 0x024C, 0x022C, 0x020C, 0x01EC, 0x01CC, 0x01AC, 0x018C,
  66972. 0x0174, 0x0164, 0x0154, 0x0144, 0x0134, 0x0124, 0x0114, 0x0104, 0x00F4, 0x00E4, 0x00D4, 0x00C4, 0x00B4, 0x00A4, 0x0094, 0x0084,
  66973. 0x0078, 0x0070, 0x0068, 0x0060, 0x0058, 0x0050, 0x0048, 0x0040, 0x0038, 0x0030, 0x0028, 0x0020, 0x0018, 0x0010, 0x0008, 0x0000
  66974. };
  66975. static MA_INLINE ma_int16 ma_dr_wav__alaw_to_s16(ma_uint8 sampleIn)
  66976. {
  66977. return (short)g_ma_dr_wavAlawTable[sampleIn];
  66978. }
  66979. static MA_INLINE ma_int16 ma_dr_wav__mulaw_to_s16(ma_uint8 sampleIn)
  66980. {
  66981. return (short)g_ma_dr_wavMulawTable[sampleIn];
  66982. }
  66983. MA_PRIVATE void ma_dr_wav__pcm_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  66984. {
  66985. size_t i;
  66986. if (bytesPerSample == 1) {
  66987. ma_dr_wav_u8_to_s16(pOut, pIn, totalSampleCount);
  66988. return;
  66989. }
  66990. if (bytesPerSample == 2) {
  66991. for (i = 0; i < totalSampleCount; ++i) {
  66992. *pOut++ = ((const ma_int16*)pIn)[i];
  66993. }
  66994. return;
  66995. }
  66996. if (bytesPerSample == 3) {
  66997. ma_dr_wav_s24_to_s16(pOut, pIn, totalSampleCount);
  66998. return;
  66999. }
  67000. if (bytesPerSample == 4) {
  67001. ma_dr_wav_s32_to_s16(pOut, (const ma_int32*)pIn, totalSampleCount);
  67002. return;
  67003. }
  67004. if (bytesPerSample > 8) {
  67005. MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  67006. return;
  67007. }
  67008. for (i = 0; i < totalSampleCount; ++i) {
  67009. ma_uint64 sample = 0;
  67010. unsigned int shift = (8 - bytesPerSample) * 8;
  67011. unsigned int j;
  67012. for (j = 0; j < bytesPerSample; j += 1) {
  67013. MA_DR_WAV_ASSERT(j < 8);
  67014. sample |= (ma_uint64)(pIn[j]) << shift;
  67015. shift += 8;
  67016. }
  67017. pIn += j;
  67018. *pOut++ = (ma_int16)((ma_int64)sample >> 48);
  67019. }
  67020. }
  67021. MA_PRIVATE void ma_dr_wav__ieee_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  67022. {
  67023. if (bytesPerSample == 4) {
  67024. ma_dr_wav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount);
  67025. return;
  67026. } else if (bytesPerSample == 8) {
  67027. ma_dr_wav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount);
  67028. return;
  67029. } else {
  67030. MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  67031. return;
  67032. }
  67033. }
  67034. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__pcm(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67035. {
  67036. ma_uint64 totalFramesRead;
  67037. ma_uint8 sampleData[4096] = {0};
  67038. ma_uint32 bytesPerFrame;
  67039. ma_uint32 bytesPerSample;
  67040. ma_uint64 samplesRead;
  67041. if ((pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) || pBufferOut == NULL) {
  67042. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  67043. }
  67044. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67045. if (bytesPerFrame == 0) {
  67046. return 0;
  67047. }
  67048. bytesPerSample = bytesPerFrame / pWav->channels;
  67049. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67050. return 0;
  67051. }
  67052. totalFramesRead = 0;
  67053. while (framesToRead > 0) {
  67054. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67055. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67056. if (framesRead == 0) {
  67057. break;
  67058. }
  67059. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67060. samplesRead = framesRead * pWav->channels;
  67061. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67062. MA_DR_WAV_ASSERT(MA_FALSE);
  67063. break;
  67064. }
  67065. ma_dr_wav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67066. pBufferOut += samplesRead;
  67067. framesToRead -= framesRead;
  67068. totalFramesRead += framesRead;
  67069. }
  67070. return totalFramesRead;
  67071. }
  67072. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__ieee(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67073. {
  67074. ma_uint64 totalFramesRead;
  67075. ma_uint8 sampleData[4096] = {0};
  67076. ma_uint32 bytesPerFrame;
  67077. ma_uint32 bytesPerSample;
  67078. ma_uint64 samplesRead;
  67079. if (pBufferOut == NULL) {
  67080. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL);
  67081. }
  67082. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67083. if (bytesPerFrame == 0) {
  67084. return 0;
  67085. }
  67086. bytesPerSample = bytesPerFrame / pWav->channels;
  67087. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67088. return 0;
  67089. }
  67090. totalFramesRead = 0;
  67091. while (framesToRead > 0) {
  67092. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67093. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67094. if (framesRead == 0) {
  67095. break;
  67096. }
  67097. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67098. samplesRead = framesRead * pWav->channels;
  67099. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67100. MA_DR_WAV_ASSERT(MA_FALSE);
  67101. break;
  67102. }
  67103. ma_dr_wav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67104. pBufferOut += samplesRead;
  67105. framesToRead -= framesRead;
  67106. totalFramesRead += framesRead;
  67107. }
  67108. return totalFramesRead;
  67109. }
  67110. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__alaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67111. {
  67112. ma_uint64 totalFramesRead;
  67113. ma_uint8 sampleData[4096] = {0};
  67114. ma_uint32 bytesPerFrame;
  67115. ma_uint32 bytesPerSample;
  67116. ma_uint64 samplesRead;
  67117. if (pBufferOut == NULL) {
  67118. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL);
  67119. }
  67120. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67121. if (bytesPerFrame == 0) {
  67122. return 0;
  67123. }
  67124. bytesPerSample = bytesPerFrame / pWav->channels;
  67125. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67126. return 0;
  67127. }
  67128. totalFramesRead = 0;
  67129. while (framesToRead > 0) {
  67130. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67131. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67132. if (framesRead == 0) {
  67133. break;
  67134. }
  67135. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67136. samplesRead = framesRead * pWav->channels;
  67137. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67138. MA_DR_WAV_ASSERT(MA_FALSE);
  67139. break;
  67140. }
  67141. ma_dr_wav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  67142. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67143. {
  67144. if (pWav->container == ma_dr_wav_container_aiff) {
  67145. ma_uint64 iSample;
  67146. for (iSample = 0; iSample < samplesRead; iSample += 1) {
  67147. pBufferOut[iSample] = -pBufferOut[iSample];
  67148. }
  67149. }
  67150. }
  67151. #endif
  67152. pBufferOut += samplesRead;
  67153. framesToRead -= framesRead;
  67154. totalFramesRead += framesRead;
  67155. }
  67156. return totalFramesRead;
  67157. }
  67158. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s16__mulaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67159. {
  67160. ma_uint64 totalFramesRead;
  67161. ma_uint8 sampleData[4096] = {0};
  67162. ma_uint32 bytesPerFrame;
  67163. ma_uint32 bytesPerSample;
  67164. ma_uint64 samplesRead;
  67165. if (pBufferOut == NULL) {
  67166. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL);
  67167. }
  67168. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67169. if (bytesPerFrame == 0) {
  67170. return 0;
  67171. }
  67172. bytesPerSample = bytesPerFrame / pWav->channels;
  67173. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67174. return 0;
  67175. }
  67176. totalFramesRead = 0;
  67177. while (framesToRead > 0) {
  67178. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67179. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67180. if (framesRead == 0) {
  67181. break;
  67182. }
  67183. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67184. samplesRead = framesRead * pWav->channels;
  67185. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67186. MA_DR_WAV_ASSERT(MA_FALSE);
  67187. break;
  67188. }
  67189. ma_dr_wav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  67190. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67191. {
  67192. if (pWav->container == ma_dr_wav_container_aiff) {
  67193. ma_uint64 iSample;
  67194. for (iSample = 0; iSample < samplesRead; iSample += 1) {
  67195. pBufferOut[iSample] = -pBufferOut[iSample];
  67196. }
  67197. }
  67198. }
  67199. #endif
  67200. pBufferOut += samplesRead;
  67201. framesToRead -= framesRead;
  67202. totalFramesRead += framesRead;
  67203. }
  67204. return totalFramesRead;
  67205. }
  67206. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67207. {
  67208. if (pWav == NULL || framesToRead == 0) {
  67209. return 0;
  67210. }
  67211. if (pBufferOut == NULL) {
  67212. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL);
  67213. }
  67214. if (framesToRead * pWav->channels * sizeof(ma_int16) > MA_SIZE_MAX) {
  67215. framesToRead = MA_SIZE_MAX / sizeof(ma_int16) / pWav->channels;
  67216. }
  67217. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM) {
  67218. return ma_dr_wav_read_pcm_frames_s16__pcm(pWav, framesToRead, pBufferOut);
  67219. }
  67220. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT) {
  67221. return ma_dr_wav_read_pcm_frames_s16__ieee(pWav, framesToRead, pBufferOut);
  67222. }
  67223. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW) {
  67224. return ma_dr_wav_read_pcm_frames_s16__alaw(pWav, framesToRead, pBufferOut);
  67225. }
  67226. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) {
  67227. return ma_dr_wav_read_pcm_frames_s16__mulaw(pWav, framesToRead, pBufferOut);
  67228. }
  67229. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM) {
  67230. return ma_dr_wav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, pBufferOut);
  67231. }
  67232. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  67233. return ma_dr_wav_read_pcm_frames_s16__ima(pWav, framesToRead, pBufferOut);
  67234. }
  67235. return 0;
  67236. }
  67237. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67238. {
  67239. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
  67240. if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_FALSE) {
  67241. ma_dr_wav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
  67242. }
  67243. return framesRead;
  67244. }
  67245. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s16be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int16* pBufferOut)
  67246. {
  67247. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
  67248. if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_TRUE) {
  67249. ma_dr_wav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
  67250. }
  67251. return framesRead;
  67252. }
  67253. MA_API void ma_dr_wav_u8_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount)
  67254. {
  67255. int r;
  67256. size_t i;
  67257. for (i = 0; i < sampleCount; ++i) {
  67258. int x = pIn[i];
  67259. r = x << 8;
  67260. r = r - 32768;
  67261. pOut[i] = (short)r;
  67262. }
  67263. }
  67264. MA_API void ma_dr_wav_s24_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount)
  67265. {
  67266. int r;
  67267. size_t i;
  67268. for (i = 0; i < sampleCount; ++i) {
  67269. int x = ((int)(((unsigned int)(((const ma_uint8*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const ma_uint8*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const ma_uint8*)pIn)[i*3+2])) << 24)) >> 8;
  67270. r = x >> 8;
  67271. pOut[i] = (short)r;
  67272. }
  67273. }
  67274. MA_API void ma_dr_wav_s32_to_s16(ma_int16* pOut, const ma_int32* pIn, size_t sampleCount)
  67275. {
  67276. int r;
  67277. size_t i;
  67278. for (i = 0; i < sampleCount; ++i) {
  67279. int x = pIn[i];
  67280. r = x >> 16;
  67281. pOut[i] = (short)r;
  67282. }
  67283. }
  67284. MA_API void ma_dr_wav_f32_to_s16(ma_int16* pOut, const float* pIn, size_t sampleCount)
  67285. {
  67286. int r;
  67287. size_t i;
  67288. for (i = 0; i < sampleCount; ++i) {
  67289. float x = pIn[i];
  67290. float c;
  67291. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  67292. c = c + 1;
  67293. r = (int)(c * 32767.5f);
  67294. r = r - 32768;
  67295. pOut[i] = (short)r;
  67296. }
  67297. }
  67298. MA_API void ma_dr_wav_f64_to_s16(ma_int16* pOut, const double* pIn, size_t sampleCount)
  67299. {
  67300. int r;
  67301. size_t i;
  67302. for (i = 0; i < sampleCount; ++i) {
  67303. double x = pIn[i];
  67304. double c;
  67305. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  67306. c = c + 1;
  67307. r = (int)(c * 32767.5);
  67308. r = r - 32768;
  67309. pOut[i] = (short)r;
  67310. }
  67311. }
  67312. MA_API void ma_dr_wav_alaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount)
  67313. {
  67314. size_t i;
  67315. for (i = 0; i < sampleCount; ++i) {
  67316. pOut[i] = ma_dr_wav__alaw_to_s16(pIn[i]);
  67317. }
  67318. }
  67319. MA_API void ma_dr_wav_mulaw_to_s16(ma_int16* pOut, const ma_uint8* pIn, size_t sampleCount)
  67320. {
  67321. size_t i;
  67322. for (i = 0; i < sampleCount; ++i) {
  67323. pOut[i] = ma_dr_wav__mulaw_to_s16(pIn[i]);
  67324. }
  67325. }
  67326. MA_PRIVATE void ma_dr_wav__pcm_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
  67327. {
  67328. unsigned int i;
  67329. if (bytesPerSample == 1) {
  67330. ma_dr_wav_u8_to_f32(pOut, pIn, sampleCount);
  67331. return;
  67332. }
  67333. if (bytesPerSample == 2) {
  67334. ma_dr_wav_s16_to_f32(pOut, (const ma_int16*)pIn, sampleCount);
  67335. return;
  67336. }
  67337. if (bytesPerSample == 3) {
  67338. ma_dr_wav_s24_to_f32(pOut, pIn, sampleCount);
  67339. return;
  67340. }
  67341. if (bytesPerSample == 4) {
  67342. ma_dr_wav_s32_to_f32(pOut, (const ma_int32*)pIn, sampleCount);
  67343. return;
  67344. }
  67345. if (bytesPerSample > 8) {
  67346. MA_DR_WAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
  67347. return;
  67348. }
  67349. for (i = 0; i < sampleCount; ++i) {
  67350. ma_uint64 sample = 0;
  67351. unsigned int shift = (8 - bytesPerSample) * 8;
  67352. unsigned int j;
  67353. for (j = 0; j < bytesPerSample; j += 1) {
  67354. MA_DR_WAV_ASSERT(j < 8);
  67355. sample |= (ma_uint64)(pIn[j]) << shift;
  67356. shift += 8;
  67357. }
  67358. pIn += j;
  67359. *pOut++ = (float)((ma_int64)sample / 9223372036854775807.0);
  67360. }
  67361. }
  67362. MA_PRIVATE void ma_dr_wav__ieee_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
  67363. {
  67364. if (bytesPerSample == 4) {
  67365. unsigned int i;
  67366. for (i = 0; i < sampleCount; ++i) {
  67367. *pOut++ = ((const float*)pIn)[i];
  67368. }
  67369. return;
  67370. } else if (bytesPerSample == 8) {
  67371. ma_dr_wav_f64_to_f32(pOut, (const double*)pIn, sampleCount);
  67372. return;
  67373. } else {
  67374. MA_DR_WAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
  67375. return;
  67376. }
  67377. }
  67378. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__pcm(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67379. {
  67380. ma_uint64 totalFramesRead;
  67381. ma_uint8 sampleData[4096] = {0};
  67382. ma_uint32 bytesPerFrame;
  67383. ma_uint32 bytesPerSample;
  67384. ma_uint64 samplesRead;
  67385. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67386. if (bytesPerFrame == 0) {
  67387. return 0;
  67388. }
  67389. bytesPerSample = bytesPerFrame / pWav->channels;
  67390. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67391. return 0;
  67392. }
  67393. totalFramesRead = 0;
  67394. while (framesToRead > 0) {
  67395. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67396. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67397. if (framesRead == 0) {
  67398. break;
  67399. }
  67400. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67401. samplesRead = framesRead * pWav->channels;
  67402. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67403. MA_DR_WAV_ASSERT(MA_FALSE);
  67404. break;
  67405. }
  67406. ma_dr_wav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67407. pBufferOut += samplesRead;
  67408. framesToRead -= framesRead;
  67409. totalFramesRead += framesRead;
  67410. }
  67411. return totalFramesRead;
  67412. }
  67413. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__msadpcm_ima(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67414. {
  67415. ma_uint64 totalFramesRead;
  67416. ma_int16 samples16[2048];
  67417. totalFramesRead = 0;
  67418. while (framesToRead > 0) {
  67419. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, ma_dr_wav_countof(samples16)/pWav->channels);
  67420. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
  67421. if (framesRead == 0) {
  67422. break;
  67423. }
  67424. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67425. ma_dr_wav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
  67426. pBufferOut += framesRead*pWav->channels;
  67427. framesToRead -= framesRead;
  67428. totalFramesRead += framesRead;
  67429. }
  67430. return totalFramesRead;
  67431. }
  67432. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__ieee(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67433. {
  67434. ma_uint64 totalFramesRead;
  67435. ma_uint8 sampleData[4096] = {0};
  67436. ma_uint32 bytesPerFrame;
  67437. ma_uint32 bytesPerSample;
  67438. ma_uint64 samplesRead;
  67439. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) {
  67440. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  67441. }
  67442. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67443. if (bytesPerFrame == 0) {
  67444. return 0;
  67445. }
  67446. bytesPerSample = bytesPerFrame / pWav->channels;
  67447. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67448. return 0;
  67449. }
  67450. totalFramesRead = 0;
  67451. while (framesToRead > 0) {
  67452. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67453. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67454. if (framesRead == 0) {
  67455. break;
  67456. }
  67457. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67458. samplesRead = framesRead * pWav->channels;
  67459. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67460. MA_DR_WAV_ASSERT(MA_FALSE);
  67461. break;
  67462. }
  67463. ma_dr_wav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67464. pBufferOut += samplesRead;
  67465. framesToRead -= framesRead;
  67466. totalFramesRead += framesRead;
  67467. }
  67468. return totalFramesRead;
  67469. }
  67470. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__alaw(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67471. {
  67472. ma_uint64 totalFramesRead;
  67473. ma_uint8 sampleData[4096] = {0};
  67474. ma_uint32 bytesPerFrame;
  67475. ma_uint32 bytesPerSample;
  67476. ma_uint64 samplesRead;
  67477. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67478. if (bytesPerFrame == 0) {
  67479. return 0;
  67480. }
  67481. bytesPerSample = bytesPerFrame / pWav->channels;
  67482. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67483. return 0;
  67484. }
  67485. totalFramesRead = 0;
  67486. while (framesToRead > 0) {
  67487. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67488. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67489. if (framesRead == 0) {
  67490. break;
  67491. }
  67492. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67493. samplesRead = framesRead * pWav->channels;
  67494. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67495. MA_DR_WAV_ASSERT(MA_FALSE);
  67496. break;
  67497. }
  67498. ma_dr_wav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  67499. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67500. {
  67501. if (pWav->container == ma_dr_wav_container_aiff) {
  67502. ma_uint64 iSample;
  67503. for (iSample = 0; iSample < samplesRead; iSample += 1) {
  67504. pBufferOut[iSample] = -pBufferOut[iSample];
  67505. }
  67506. }
  67507. }
  67508. #endif
  67509. pBufferOut += samplesRead;
  67510. framesToRead -= framesRead;
  67511. totalFramesRead += framesRead;
  67512. }
  67513. return totalFramesRead;
  67514. }
  67515. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_f32__mulaw(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67516. {
  67517. ma_uint64 totalFramesRead;
  67518. ma_uint8 sampleData[4096] = {0};
  67519. ma_uint32 bytesPerFrame;
  67520. ma_uint32 bytesPerSample;
  67521. ma_uint64 samplesRead;
  67522. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67523. if (bytesPerFrame == 0) {
  67524. return 0;
  67525. }
  67526. bytesPerSample = bytesPerFrame / pWav->channels;
  67527. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67528. return 0;
  67529. }
  67530. totalFramesRead = 0;
  67531. while (framesToRead > 0) {
  67532. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67533. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67534. if (framesRead == 0) {
  67535. break;
  67536. }
  67537. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67538. samplesRead = framesRead * pWav->channels;
  67539. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67540. MA_DR_WAV_ASSERT(MA_FALSE);
  67541. break;
  67542. }
  67543. ma_dr_wav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  67544. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67545. {
  67546. if (pWav->container == ma_dr_wav_container_aiff) {
  67547. ma_uint64 iSample;
  67548. for (iSample = 0; iSample < samplesRead; iSample += 1) {
  67549. pBufferOut[iSample] = -pBufferOut[iSample];
  67550. }
  67551. }
  67552. }
  67553. #endif
  67554. pBufferOut += samplesRead;
  67555. framesToRead -= framesRead;
  67556. totalFramesRead += framesRead;
  67557. }
  67558. return totalFramesRead;
  67559. }
  67560. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67561. {
  67562. if (pWav == NULL || framesToRead == 0) {
  67563. return 0;
  67564. }
  67565. if (pBufferOut == NULL) {
  67566. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL);
  67567. }
  67568. if (framesToRead * pWav->channels * sizeof(float) > MA_SIZE_MAX) {
  67569. framesToRead = MA_SIZE_MAX / sizeof(float) / pWav->channels;
  67570. }
  67571. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM) {
  67572. return ma_dr_wav_read_pcm_frames_f32__pcm(pWav, framesToRead, pBufferOut);
  67573. }
  67574. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  67575. return ma_dr_wav_read_pcm_frames_f32__msadpcm_ima(pWav, framesToRead, pBufferOut);
  67576. }
  67577. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT) {
  67578. return ma_dr_wav_read_pcm_frames_f32__ieee(pWav, framesToRead, pBufferOut);
  67579. }
  67580. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW) {
  67581. return ma_dr_wav_read_pcm_frames_f32__alaw(pWav, framesToRead, pBufferOut);
  67582. }
  67583. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) {
  67584. return ma_dr_wav_read_pcm_frames_f32__mulaw(pWav, framesToRead, pBufferOut);
  67585. }
  67586. return 0;
  67587. }
  67588. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32le(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67589. {
  67590. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
  67591. if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_FALSE) {
  67592. ma_dr_wav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
  67593. }
  67594. return framesRead;
  67595. }
  67596. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_f32be(ma_dr_wav* pWav, ma_uint64 framesToRead, float* pBufferOut)
  67597. {
  67598. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
  67599. if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_TRUE) {
  67600. ma_dr_wav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
  67601. }
  67602. return framesRead;
  67603. }
  67604. MA_API void ma_dr_wav_u8_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount)
  67605. {
  67606. size_t i;
  67607. if (pOut == NULL || pIn == NULL) {
  67608. return;
  67609. }
  67610. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67611. for (i = 0; i < sampleCount; ++i) {
  67612. *pOut++ = (pIn[i] / 256.0f) * 2 - 1;
  67613. }
  67614. #else
  67615. for (i = 0; i < sampleCount; ++i) {
  67616. float x = pIn[i];
  67617. x = x * 0.00784313725490196078f;
  67618. x = x - 1;
  67619. *pOut++ = x;
  67620. }
  67621. #endif
  67622. }
  67623. MA_API void ma_dr_wav_s16_to_f32(float* pOut, const ma_int16* pIn, size_t sampleCount)
  67624. {
  67625. size_t i;
  67626. if (pOut == NULL || pIn == NULL) {
  67627. return;
  67628. }
  67629. for (i = 0; i < sampleCount; ++i) {
  67630. *pOut++ = pIn[i] * 0.000030517578125f;
  67631. }
  67632. }
  67633. MA_API void ma_dr_wav_s24_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount)
  67634. {
  67635. size_t i;
  67636. if (pOut == NULL || pIn == NULL) {
  67637. return;
  67638. }
  67639. for (i = 0; i < sampleCount; ++i) {
  67640. double x;
  67641. ma_uint32 a = ((ma_uint32)(pIn[i*3+0]) << 8);
  67642. ma_uint32 b = ((ma_uint32)(pIn[i*3+1]) << 16);
  67643. ma_uint32 c = ((ma_uint32)(pIn[i*3+2]) << 24);
  67644. x = (double)((ma_int32)(a | b | c) >> 8);
  67645. *pOut++ = (float)(x * 0.00000011920928955078125);
  67646. }
  67647. }
  67648. MA_API void ma_dr_wav_s32_to_f32(float* pOut, const ma_int32* pIn, size_t sampleCount)
  67649. {
  67650. size_t i;
  67651. if (pOut == NULL || pIn == NULL) {
  67652. return;
  67653. }
  67654. for (i = 0; i < sampleCount; ++i) {
  67655. *pOut++ = (float)(pIn[i] / 2147483648.0);
  67656. }
  67657. }
  67658. MA_API void ma_dr_wav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount)
  67659. {
  67660. size_t i;
  67661. if (pOut == NULL || pIn == NULL) {
  67662. return;
  67663. }
  67664. for (i = 0; i < sampleCount; ++i) {
  67665. *pOut++ = (float)pIn[i];
  67666. }
  67667. }
  67668. MA_API void ma_dr_wav_alaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount)
  67669. {
  67670. size_t i;
  67671. if (pOut == NULL || pIn == NULL) {
  67672. return;
  67673. }
  67674. for (i = 0; i < sampleCount; ++i) {
  67675. *pOut++ = ma_dr_wav__alaw_to_s16(pIn[i]) / 32768.0f;
  67676. }
  67677. }
  67678. MA_API void ma_dr_wav_mulaw_to_f32(float* pOut, const ma_uint8* pIn, size_t sampleCount)
  67679. {
  67680. size_t i;
  67681. if (pOut == NULL || pIn == NULL) {
  67682. return;
  67683. }
  67684. for (i = 0; i < sampleCount; ++i) {
  67685. *pOut++ = ma_dr_wav__mulaw_to_s16(pIn[i]) / 32768.0f;
  67686. }
  67687. }
  67688. MA_PRIVATE void ma_dr_wav__pcm_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  67689. {
  67690. unsigned int i;
  67691. if (bytesPerSample == 1) {
  67692. ma_dr_wav_u8_to_s32(pOut, pIn, totalSampleCount);
  67693. return;
  67694. }
  67695. if (bytesPerSample == 2) {
  67696. ma_dr_wav_s16_to_s32(pOut, (const ma_int16*)pIn, totalSampleCount);
  67697. return;
  67698. }
  67699. if (bytesPerSample == 3) {
  67700. ma_dr_wav_s24_to_s32(pOut, pIn, totalSampleCount);
  67701. return;
  67702. }
  67703. if (bytesPerSample == 4) {
  67704. for (i = 0; i < totalSampleCount; ++i) {
  67705. *pOut++ = ((const ma_int32*)pIn)[i];
  67706. }
  67707. return;
  67708. }
  67709. if (bytesPerSample > 8) {
  67710. MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  67711. return;
  67712. }
  67713. for (i = 0; i < totalSampleCount; ++i) {
  67714. ma_uint64 sample = 0;
  67715. unsigned int shift = (8 - bytesPerSample) * 8;
  67716. unsigned int j;
  67717. for (j = 0; j < bytesPerSample; j += 1) {
  67718. MA_DR_WAV_ASSERT(j < 8);
  67719. sample |= (ma_uint64)(pIn[j]) << shift;
  67720. shift += 8;
  67721. }
  67722. pIn += j;
  67723. *pOut++ = (ma_int32)((ma_int64)sample >> 32);
  67724. }
  67725. }
  67726. MA_PRIVATE void ma_dr_wav__ieee_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  67727. {
  67728. if (bytesPerSample == 4) {
  67729. ma_dr_wav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount);
  67730. return;
  67731. } else if (bytesPerSample == 8) {
  67732. ma_dr_wav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount);
  67733. return;
  67734. } else {
  67735. MA_DR_WAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  67736. return;
  67737. }
  67738. }
  67739. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__pcm(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67740. {
  67741. ma_uint64 totalFramesRead;
  67742. ma_uint8 sampleData[4096] = {0};
  67743. ma_uint32 bytesPerFrame;
  67744. ma_uint32 bytesPerSample;
  67745. ma_uint64 samplesRead;
  67746. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) {
  67747. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  67748. }
  67749. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67750. if (bytesPerFrame == 0) {
  67751. return 0;
  67752. }
  67753. bytesPerSample = bytesPerFrame / pWav->channels;
  67754. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67755. return 0;
  67756. }
  67757. totalFramesRead = 0;
  67758. while (framesToRead > 0) {
  67759. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67760. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67761. if (framesRead == 0) {
  67762. break;
  67763. }
  67764. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67765. samplesRead = framesRead * pWav->channels;
  67766. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67767. MA_DR_WAV_ASSERT(MA_FALSE);
  67768. break;
  67769. }
  67770. ma_dr_wav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67771. pBufferOut += samplesRead;
  67772. framesToRead -= framesRead;
  67773. totalFramesRead += framesRead;
  67774. }
  67775. return totalFramesRead;
  67776. }
  67777. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__msadpcm_ima(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67778. {
  67779. ma_uint64 totalFramesRead = 0;
  67780. ma_int16 samples16[2048];
  67781. while (framesToRead > 0) {
  67782. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, ma_dr_wav_countof(samples16)/pWav->channels);
  67783. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
  67784. if (framesRead == 0) {
  67785. break;
  67786. }
  67787. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67788. ma_dr_wav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
  67789. pBufferOut += framesRead*pWav->channels;
  67790. framesToRead -= framesRead;
  67791. totalFramesRead += framesRead;
  67792. }
  67793. return totalFramesRead;
  67794. }
  67795. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__ieee(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67796. {
  67797. ma_uint64 totalFramesRead;
  67798. ma_uint8 sampleData[4096] = {0};
  67799. ma_uint32 bytesPerFrame;
  67800. ma_uint32 bytesPerSample;
  67801. ma_uint64 samplesRead;
  67802. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67803. if (bytesPerFrame == 0) {
  67804. return 0;
  67805. }
  67806. bytesPerSample = bytesPerFrame / pWav->channels;
  67807. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67808. return 0;
  67809. }
  67810. totalFramesRead = 0;
  67811. while (framesToRead > 0) {
  67812. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67813. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67814. if (framesRead == 0) {
  67815. break;
  67816. }
  67817. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67818. samplesRead = framesRead * pWav->channels;
  67819. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67820. MA_DR_WAV_ASSERT(MA_FALSE);
  67821. break;
  67822. }
  67823. ma_dr_wav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  67824. pBufferOut += samplesRead;
  67825. framesToRead -= framesRead;
  67826. totalFramesRead += framesRead;
  67827. }
  67828. return totalFramesRead;
  67829. }
  67830. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__alaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67831. {
  67832. ma_uint64 totalFramesRead;
  67833. ma_uint8 sampleData[4096] = {0};
  67834. ma_uint32 bytesPerFrame;
  67835. ma_uint32 bytesPerSample;
  67836. ma_uint64 samplesRead;
  67837. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67838. if (bytesPerFrame == 0) {
  67839. return 0;
  67840. }
  67841. bytesPerSample = bytesPerFrame / pWav->channels;
  67842. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67843. return 0;
  67844. }
  67845. totalFramesRead = 0;
  67846. while (framesToRead > 0) {
  67847. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67848. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67849. if (framesRead == 0) {
  67850. break;
  67851. }
  67852. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67853. samplesRead = framesRead * pWav->channels;
  67854. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67855. MA_DR_WAV_ASSERT(MA_FALSE);
  67856. break;
  67857. }
  67858. ma_dr_wav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  67859. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67860. {
  67861. if (pWav->container == ma_dr_wav_container_aiff) {
  67862. ma_uint64 iSample;
  67863. for (iSample = 0; iSample < samplesRead; iSample += 1) {
  67864. pBufferOut[iSample] = -pBufferOut[iSample];
  67865. }
  67866. }
  67867. }
  67868. #endif
  67869. pBufferOut += samplesRead;
  67870. framesToRead -= framesRead;
  67871. totalFramesRead += framesRead;
  67872. }
  67873. return totalFramesRead;
  67874. }
  67875. MA_PRIVATE ma_uint64 ma_dr_wav_read_pcm_frames_s32__mulaw(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67876. {
  67877. ma_uint64 totalFramesRead;
  67878. ma_uint8 sampleData[4096] = {0};
  67879. ma_uint32 bytesPerFrame;
  67880. ma_uint32 bytesPerSample;
  67881. ma_uint64 samplesRead;
  67882. bytesPerFrame = ma_dr_wav_get_bytes_per_pcm_frame(pWav);
  67883. if (bytesPerFrame == 0) {
  67884. return 0;
  67885. }
  67886. bytesPerSample = bytesPerFrame / pWav->channels;
  67887. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  67888. return 0;
  67889. }
  67890. totalFramesRead = 0;
  67891. while (framesToRead > 0) {
  67892. ma_uint64 framesToReadThisIteration = ma_dr_wav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  67893. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  67894. if (framesRead == 0) {
  67895. break;
  67896. }
  67897. MA_DR_WAV_ASSERT(framesRead <= framesToReadThisIteration);
  67898. samplesRead = framesRead * pWav->channels;
  67899. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  67900. MA_DR_WAV_ASSERT(MA_FALSE);
  67901. break;
  67902. }
  67903. ma_dr_wav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  67904. #ifdef MA_DR_WAV_LIBSNDFILE_COMPAT
  67905. {
  67906. if (pWav->container == ma_dr_wav_container_aiff) {
  67907. ma_uint64 iSample;
  67908. for (iSample = 0; iSample < samplesRead; iSample += 1) {
  67909. pBufferOut[iSample] = -pBufferOut[iSample];
  67910. }
  67911. }
  67912. }
  67913. #endif
  67914. pBufferOut += samplesRead;
  67915. framesToRead -= framesRead;
  67916. totalFramesRead += framesRead;
  67917. }
  67918. return totalFramesRead;
  67919. }
  67920. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67921. {
  67922. if (pWav == NULL || framesToRead == 0) {
  67923. return 0;
  67924. }
  67925. if (pBufferOut == NULL) {
  67926. return ma_dr_wav_read_pcm_frames(pWav, framesToRead, NULL);
  67927. }
  67928. if (framesToRead * pWav->channels * sizeof(ma_int32) > MA_SIZE_MAX) {
  67929. framesToRead = MA_SIZE_MAX / sizeof(ma_int32) / pWav->channels;
  67930. }
  67931. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_PCM) {
  67932. return ma_dr_wav_read_pcm_frames_s32__pcm(pWav, framesToRead, pBufferOut);
  67933. }
  67934. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_DVI_ADPCM) {
  67935. return ma_dr_wav_read_pcm_frames_s32__msadpcm_ima(pWav, framesToRead, pBufferOut);
  67936. }
  67937. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_IEEE_FLOAT) {
  67938. return ma_dr_wav_read_pcm_frames_s32__ieee(pWav, framesToRead, pBufferOut);
  67939. }
  67940. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_ALAW) {
  67941. return ma_dr_wav_read_pcm_frames_s32__alaw(pWav, framesToRead, pBufferOut);
  67942. }
  67943. if (pWav->translatedFormatTag == MA_DR_WAVE_FORMAT_MULAW) {
  67944. return ma_dr_wav_read_pcm_frames_s32__mulaw(pWav, framesToRead, pBufferOut);
  67945. }
  67946. return 0;
  67947. }
  67948. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32le(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67949. {
  67950. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
  67951. if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_FALSE) {
  67952. ma_dr_wav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
  67953. }
  67954. return framesRead;
  67955. }
  67956. MA_API ma_uint64 ma_dr_wav_read_pcm_frames_s32be(ma_dr_wav* pWav, ma_uint64 framesToRead, ma_int32* pBufferOut)
  67957. {
  67958. ma_uint64 framesRead = ma_dr_wav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
  67959. if (pBufferOut != NULL && ma_dr_wav__is_little_endian() == MA_TRUE) {
  67960. ma_dr_wav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
  67961. }
  67962. return framesRead;
  67963. }
  67964. MA_API void ma_dr_wav_u8_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount)
  67965. {
  67966. size_t i;
  67967. if (pOut == NULL || pIn == NULL) {
  67968. return;
  67969. }
  67970. for (i = 0; i < sampleCount; ++i) {
  67971. *pOut++ = ((int)pIn[i] - 128) << 24;
  67972. }
  67973. }
  67974. MA_API void ma_dr_wav_s16_to_s32(ma_int32* pOut, const ma_int16* pIn, size_t sampleCount)
  67975. {
  67976. size_t i;
  67977. if (pOut == NULL || pIn == NULL) {
  67978. return;
  67979. }
  67980. for (i = 0; i < sampleCount; ++i) {
  67981. *pOut++ = pIn[i] << 16;
  67982. }
  67983. }
  67984. MA_API void ma_dr_wav_s24_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount)
  67985. {
  67986. size_t i;
  67987. if (pOut == NULL || pIn == NULL) {
  67988. return;
  67989. }
  67990. for (i = 0; i < sampleCount; ++i) {
  67991. unsigned int s0 = pIn[i*3 + 0];
  67992. unsigned int s1 = pIn[i*3 + 1];
  67993. unsigned int s2 = pIn[i*3 + 2];
  67994. ma_int32 sample32 = (ma_int32)((s0 << 8) | (s1 << 16) | (s2 << 24));
  67995. *pOut++ = sample32;
  67996. }
  67997. }
  67998. MA_API void ma_dr_wav_f32_to_s32(ma_int32* pOut, const float* pIn, size_t sampleCount)
  67999. {
  68000. size_t i;
  68001. if (pOut == NULL || pIn == NULL) {
  68002. return;
  68003. }
  68004. for (i = 0; i < sampleCount; ++i) {
  68005. *pOut++ = (ma_int32)(2147483648.0 * pIn[i]);
  68006. }
  68007. }
  68008. MA_API void ma_dr_wav_f64_to_s32(ma_int32* pOut, const double* pIn, size_t sampleCount)
  68009. {
  68010. size_t i;
  68011. if (pOut == NULL || pIn == NULL) {
  68012. return;
  68013. }
  68014. for (i = 0; i < sampleCount; ++i) {
  68015. *pOut++ = (ma_int32)(2147483648.0 * pIn[i]);
  68016. }
  68017. }
  68018. MA_API void ma_dr_wav_alaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount)
  68019. {
  68020. size_t i;
  68021. if (pOut == NULL || pIn == NULL) {
  68022. return;
  68023. }
  68024. for (i = 0; i < sampleCount; ++i) {
  68025. *pOut++ = ((ma_int32)ma_dr_wav__alaw_to_s16(pIn[i])) << 16;
  68026. }
  68027. }
  68028. MA_API void ma_dr_wav_mulaw_to_s32(ma_int32* pOut, const ma_uint8* pIn, size_t sampleCount)
  68029. {
  68030. size_t i;
  68031. if (pOut == NULL || pIn == NULL) {
  68032. return;
  68033. }
  68034. for (i= 0; i < sampleCount; ++i) {
  68035. *pOut++ = ((ma_int32)ma_dr_wav__mulaw_to_s16(pIn[i])) << 16;
  68036. }
  68037. }
  68038. MA_PRIVATE ma_int16* ma_dr_wav__read_pcm_frames_and_close_s16(ma_dr_wav* pWav, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalFrameCount)
  68039. {
  68040. ma_uint64 sampleDataSize;
  68041. ma_int16* pSampleData;
  68042. ma_uint64 framesRead;
  68043. MA_DR_WAV_ASSERT(pWav != NULL);
  68044. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(ma_int16);
  68045. if (sampleDataSize > MA_SIZE_MAX) {
  68046. ma_dr_wav_uninit(pWav);
  68047. return NULL;
  68048. }
  68049. pSampleData = (ma_int16*)ma_dr_wav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  68050. if (pSampleData == NULL) {
  68051. ma_dr_wav_uninit(pWav);
  68052. return NULL;
  68053. }
  68054. framesRead = ma_dr_wav_read_pcm_frames_s16(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  68055. if (framesRead != pWav->totalPCMFrameCount) {
  68056. ma_dr_wav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  68057. ma_dr_wav_uninit(pWav);
  68058. return NULL;
  68059. }
  68060. ma_dr_wav_uninit(pWav);
  68061. if (sampleRate) {
  68062. *sampleRate = pWav->sampleRate;
  68063. }
  68064. if (channels) {
  68065. *channels = pWav->channels;
  68066. }
  68067. if (totalFrameCount) {
  68068. *totalFrameCount = pWav->totalPCMFrameCount;
  68069. }
  68070. return pSampleData;
  68071. }
  68072. MA_PRIVATE float* ma_dr_wav__read_pcm_frames_and_close_f32(ma_dr_wav* pWav, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalFrameCount)
  68073. {
  68074. ma_uint64 sampleDataSize;
  68075. float* pSampleData;
  68076. ma_uint64 framesRead;
  68077. MA_DR_WAV_ASSERT(pWav != NULL);
  68078. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(float);
  68079. if (sampleDataSize > MA_SIZE_MAX) {
  68080. ma_dr_wav_uninit(pWav);
  68081. return NULL;
  68082. }
  68083. pSampleData = (float*)ma_dr_wav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  68084. if (pSampleData == NULL) {
  68085. ma_dr_wav_uninit(pWav);
  68086. return NULL;
  68087. }
  68088. framesRead = ma_dr_wav_read_pcm_frames_f32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  68089. if (framesRead != pWav->totalPCMFrameCount) {
  68090. ma_dr_wav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  68091. ma_dr_wav_uninit(pWav);
  68092. return NULL;
  68093. }
  68094. ma_dr_wav_uninit(pWav);
  68095. if (sampleRate) {
  68096. *sampleRate = pWav->sampleRate;
  68097. }
  68098. if (channels) {
  68099. *channels = pWav->channels;
  68100. }
  68101. if (totalFrameCount) {
  68102. *totalFrameCount = pWav->totalPCMFrameCount;
  68103. }
  68104. return pSampleData;
  68105. }
  68106. MA_PRIVATE ma_int32* ma_dr_wav__read_pcm_frames_and_close_s32(ma_dr_wav* pWav, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalFrameCount)
  68107. {
  68108. ma_uint64 sampleDataSize;
  68109. ma_int32* pSampleData;
  68110. ma_uint64 framesRead;
  68111. MA_DR_WAV_ASSERT(pWav != NULL);
  68112. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(ma_int32);
  68113. if (sampleDataSize > MA_SIZE_MAX) {
  68114. ma_dr_wav_uninit(pWav);
  68115. return NULL;
  68116. }
  68117. pSampleData = (ma_int32*)ma_dr_wav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  68118. if (pSampleData == NULL) {
  68119. ma_dr_wav_uninit(pWav);
  68120. return NULL;
  68121. }
  68122. framesRead = ma_dr_wav_read_pcm_frames_s32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  68123. if (framesRead != pWav->totalPCMFrameCount) {
  68124. ma_dr_wav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  68125. ma_dr_wav_uninit(pWav);
  68126. return NULL;
  68127. }
  68128. ma_dr_wav_uninit(pWav);
  68129. if (sampleRate) {
  68130. *sampleRate = pWav->sampleRate;
  68131. }
  68132. if (channels) {
  68133. *channels = pWav->channels;
  68134. }
  68135. if (totalFrameCount) {
  68136. *totalFrameCount = pWav->totalPCMFrameCount;
  68137. }
  68138. return pSampleData;
  68139. }
  68140. MA_API ma_int16* ma_dr_wav_open_and_read_pcm_frames_s16(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68141. {
  68142. ma_dr_wav wav;
  68143. if (channelsOut) {
  68144. *channelsOut = 0;
  68145. }
  68146. if (sampleRateOut) {
  68147. *sampleRateOut = 0;
  68148. }
  68149. if (totalFrameCountOut) {
  68150. *totalFrameCountOut = 0;
  68151. }
  68152. if (!ma_dr_wav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  68153. return NULL;
  68154. }
  68155. return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68156. }
  68157. MA_API float* ma_dr_wav_open_and_read_pcm_frames_f32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68158. {
  68159. ma_dr_wav wav;
  68160. if (channelsOut) {
  68161. *channelsOut = 0;
  68162. }
  68163. if (sampleRateOut) {
  68164. *sampleRateOut = 0;
  68165. }
  68166. if (totalFrameCountOut) {
  68167. *totalFrameCountOut = 0;
  68168. }
  68169. if (!ma_dr_wav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  68170. return NULL;
  68171. }
  68172. return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68173. }
  68174. MA_API ma_int32* ma_dr_wav_open_and_read_pcm_frames_s32(ma_dr_wav_read_proc onRead, ma_dr_wav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68175. {
  68176. ma_dr_wav wav;
  68177. if (channelsOut) {
  68178. *channelsOut = 0;
  68179. }
  68180. if (sampleRateOut) {
  68181. *sampleRateOut = 0;
  68182. }
  68183. if (totalFrameCountOut) {
  68184. *totalFrameCountOut = 0;
  68185. }
  68186. if (!ma_dr_wav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  68187. return NULL;
  68188. }
  68189. return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68190. }
  68191. #ifndef MA_DR_WAV_NO_STDIO
  68192. MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68193. {
  68194. ma_dr_wav wav;
  68195. if (channelsOut) {
  68196. *channelsOut = 0;
  68197. }
  68198. if (sampleRateOut) {
  68199. *sampleRateOut = 0;
  68200. }
  68201. if (totalFrameCountOut) {
  68202. *totalFrameCountOut = 0;
  68203. }
  68204. if (!ma_dr_wav_init_file(&wav, filename, pAllocationCallbacks)) {
  68205. return NULL;
  68206. }
  68207. return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68208. }
  68209. MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68210. {
  68211. ma_dr_wav wav;
  68212. if (channelsOut) {
  68213. *channelsOut = 0;
  68214. }
  68215. if (sampleRateOut) {
  68216. *sampleRateOut = 0;
  68217. }
  68218. if (totalFrameCountOut) {
  68219. *totalFrameCountOut = 0;
  68220. }
  68221. if (!ma_dr_wav_init_file(&wav, filename, pAllocationCallbacks)) {
  68222. return NULL;
  68223. }
  68224. return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68225. }
  68226. MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68227. {
  68228. ma_dr_wav wav;
  68229. if (channelsOut) {
  68230. *channelsOut = 0;
  68231. }
  68232. if (sampleRateOut) {
  68233. *sampleRateOut = 0;
  68234. }
  68235. if (totalFrameCountOut) {
  68236. *totalFrameCountOut = 0;
  68237. }
  68238. if (!ma_dr_wav_init_file(&wav, filename, pAllocationCallbacks)) {
  68239. return NULL;
  68240. }
  68241. return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68242. }
  68243. #ifndef MA_DR_WAV_NO_WCHAR
  68244. MA_API ma_int16* ma_dr_wav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68245. {
  68246. ma_dr_wav wav;
  68247. if (sampleRateOut) {
  68248. *sampleRateOut = 0;
  68249. }
  68250. if (channelsOut) {
  68251. *channelsOut = 0;
  68252. }
  68253. if (totalFrameCountOut) {
  68254. *totalFrameCountOut = 0;
  68255. }
  68256. if (!ma_dr_wav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  68257. return NULL;
  68258. }
  68259. return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68260. }
  68261. MA_API float* ma_dr_wav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68262. {
  68263. ma_dr_wav wav;
  68264. if (sampleRateOut) {
  68265. *sampleRateOut = 0;
  68266. }
  68267. if (channelsOut) {
  68268. *channelsOut = 0;
  68269. }
  68270. if (totalFrameCountOut) {
  68271. *totalFrameCountOut = 0;
  68272. }
  68273. if (!ma_dr_wav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  68274. return NULL;
  68275. }
  68276. return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68277. }
  68278. MA_API ma_int32* ma_dr_wav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68279. {
  68280. ma_dr_wav wav;
  68281. if (sampleRateOut) {
  68282. *sampleRateOut = 0;
  68283. }
  68284. if (channelsOut) {
  68285. *channelsOut = 0;
  68286. }
  68287. if (totalFrameCountOut) {
  68288. *totalFrameCountOut = 0;
  68289. }
  68290. if (!ma_dr_wav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  68291. return NULL;
  68292. }
  68293. return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68294. }
  68295. #endif
  68296. #endif
  68297. MA_API ma_int16* ma_dr_wav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68298. {
  68299. ma_dr_wav wav;
  68300. if (channelsOut) {
  68301. *channelsOut = 0;
  68302. }
  68303. if (sampleRateOut) {
  68304. *sampleRateOut = 0;
  68305. }
  68306. if (totalFrameCountOut) {
  68307. *totalFrameCountOut = 0;
  68308. }
  68309. if (!ma_dr_wav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  68310. return NULL;
  68311. }
  68312. return ma_dr_wav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68313. }
  68314. MA_API float* ma_dr_wav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68315. {
  68316. ma_dr_wav wav;
  68317. if (channelsOut) {
  68318. *channelsOut = 0;
  68319. }
  68320. if (sampleRateOut) {
  68321. *sampleRateOut = 0;
  68322. }
  68323. if (totalFrameCountOut) {
  68324. *totalFrameCountOut = 0;
  68325. }
  68326. if (!ma_dr_wav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  68327. return NULL;
  68328. }
  68329. return ma_dr_wav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68330. }
  68331. MA_API ma_int32* ma_dr_wav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  68332. {
  68333. ma_dr_wav wav;
  68334. if (channelsOut) {
  68335. *channelsOut = 0;
  68336. }
  68337. if (sampleRateOut) {
  68338. *sampleRateOut = 0;
  68339. }
  68340. if (totalFrameCountOut) {
  68341. *totalFrameCountOut = 0;
  68342. }
  68343. if (!ma_dr_wav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  68344. return NULL;
  68345. }
  68346. return ma_dr_wav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  68347. }
  68348. #endif
  68349. MA_API void ma_dr_wav_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  68350. {
  68351. if (pAllocationCallbacks != NULL) {
  68352. ma_dr_wav__free_from_callbacks(p, pAllocationCallbacks);
  68353. } else {
  68354. ma_dr_wav__free_default(p, NULL);
  68355. }
  68356. }
  68357. MA_API ma_uint16 ma_dr_wav_bytes_to_u16(const ma_uint8* data)
  68358. {
  68359. return ((ma_uint16)data[0] << 0) | ((ma_uint16)data[1] << 8);
  68360. }
  68361. MA_API ma_int16 ma_dr_wav_bytes_to_s16(const ma_uint8* data)
  68362. {
  68363. return (ma_int16)ma_dr_wav_bytes_to_u16(data);
  68364. }
  68365. MA_API ma_uint32 ma_dr_wav_bytes_to_u32(const ma_uint8* data)
  68366. {
  68367. return ma_dr_wav_bytes_to_u32_le(data);
  68368. }
  68369. MA_API float ma_dr_wav_bytes_to_f32(const ma_uint8* data)
  68370. {
  68371. union {
  68372. ma_uint32 u32;
  68373. float f32;
  68374. } value;
  68375. value.u32 = ma_dr_wav_bytes_to_u32(data);
  68376. return value.f32;
  68377. }
  68378. MA_API ma_int32 ma_dr_wav_bytes_to_s32(const ma_uint8* data)
  68379. {
  68380. return (ma_int32)ma_dr_wav_bytes_to_u32(data);
  68381. }
  68382. MA_API ma_uint64 ma_dr_wav_bytes_to_u64(const ma_uint8* data)
  68383. {
  68384. return
  68385. ((ma_uint64)data[0] << 0) | ((ma_uint64)data[1] << 8) | ((ma_uint64)data[2] << 16) | ((ma_uint64)data[3] << 24) |
  68386. ((ma_uint64)data[4] << 32) | ((ma_uint64)data[5] << 40) | ((ma_uint64)data[6] << 48) | ((ma_uint64)data[7] << 56);
  68387. }
  68388. MA_API ma_int64 ma_dr_wav_bytes_to_s64(const ma_uint8* data)
  68389. {
  68390. return (ma_int64)ma_dr_wav_bytes_to_u64(data);
  68391. }
  68392. MA_API ma_bool32 ma_dr_wav_guid_equal(const ma_uint8 a[16], const ma_uint8 b[16])
  68393. {
  68394. int i;
  68395. for (i = 0; i < 16; i += 1) {
  68396. if (a[i] != b[i]) {
  68397. return MA_FALSE;
  68398. }
  68399. }
  68400. return MA_TRUE;
  68401. }
  68402. MA_API ma_bool32 ma_dr_wav_fourcc_equal(const ma_uint8* a, const char* b)
  68403. {
  68404. return
  68405. a[0] == b[0] &&
  68406. a[1] == b[1] &&
  68407. a[2] == b[2] &&
  68408. a[3] == b[3];
  68409. }
  68410. #ifdef __MRC__
  68411. #pragma options opt reset
  68412. #endif
  68413. #endif
  68414. /* dr_wav_c end */
  68415. #endif /* MA_DR_WAV_IMPLEMENTATION */
  68416. #endif /* MA_NO_WAV */
  68417. #if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
  68418. #if !defined(MA_DR_FLAC_IMPLEMENTATION) && !defined(MA_DR_FLAC_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  68419. /* dr_flac_c begin */
  68420. #ifndef ma_dr_flac_c
  68421. #define ma_dr_flac_c
  68422. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  68423. #pragma GCC diagnostic push
  68424. #if __GNUC__ >= 7
  68425. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  68426. #endif
  68427. #endif
  68428. #ifdef __linux__
  68429. #ifndef _BSD_SOURCE
  68430. #define _BSD_SOURCE
  68431. #endif
  68432. #ifndef _DEFAULT_SOURCE
  68433. #define _DEFAULT_SOURCE
  68434. #endif
  68435. #ifndef __USE_BSD
  68436. #define __USE_BSD
  68437. #endif
  68438. #include <endian.h>
  68439. #endif
  68440. #include <stdlib.h>
  68441. #include <string.h>
  68442. #if !defined(MA_DR_FLAC_NO_SIMD)
  68443. #if defined(MA_X64) || defined(MA_X86)
  68444. #if defined(_MSC_VER) && !defined(__clang__)
  68445. #if _MSC_VER >= 1400 && !defined(MA_DR_FLAC_NO_SSE2)
  68446. #define MA_DR_FLAC_SUPPORT_SSE2
  68447. #endif
  68448. #if _MSC_VER >= 1600 && !defined(MA_DR_FLAC_NO_SSE41)
  68449. #define MA_DR_FLAC_SUPPORT_SSE41
  68450. #endif
  68451. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
  68452. #if defined(__SSE2__) && !defined(MA_DR_FLAC_NO_SSE2)
  68453. #define MA_DR_FLAC_SUPPORT_SSE2
  68454. #endif
  68455. #if defined(__SSE4_1__) && !defined(MA_DR_FLAC_NO_SSE41)
  68456. #define MA_DR_FLAC_SUPPORT_SSE41
  68457. #endif
  68458. #endif
  68459. #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  68460. #if !defined(MA_DR_FLAC_SUPPORT_SSE2) && !defined(MA_DR_FLAC_NO_SSE2) && __has_include(<emmintrin.h>)
  68461. #define MA_DR_FLAC_SUPPORT_SSE2
  68462. #endif
  68463. #if !defined(MA_DR_FLAC_SUPPORT_SSE41) && !defined(MA_DR_FLAC_NO_SSE41) && __has_include(<smmintrin.h>)
  68464. #define MA_DR_FLAC_SUPPORT_SSE41
  68465. #endif
  68466. #endif
  68467. #if defined(MA_DR_FLAC_SUPPORT_SSE41)
  68468. #include <smmintrin.h>
  68469. #elif defined(MA_DR_FLAC_SUPPORT_SSE2)
  68470. #include <emmintrin.h>
  68471. #endif
  68472. #endif
  68473. #if defined(MA_ARM)
  68474. #if !defined(MA_DR_FLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  68475. #define MA_DR_FLAC_SUPPORT_NEON
  68476. #include <arm_neon.h>
  68477. #endif
  68478. #endif
  68479. #endif
  68480. #if !defined(MA_DR_FLAC_NO_SIMD) && (defined(MA_X86) || defined(MA_X64))
  68481. #if defined(_MSC_VER) && !defined(__clang__)
  68482. #if _MSC_VER >= 1400
  68483. #include <intrin.h>
  68484. static void ma_dr_flac__cpuid(int info[4], int fid)
  68485. {
  68486. __cpuid(info, fid);
  68487. }
  68488. #else
  68489. #define MA_DR_FLAC_NO_CPUID
  68490. #endif
  68491. #else
  68492. #if defined(__GNUC__) || defined(__clang__)
  68493. static void ma_dr_flac__cpuid(int info[4], int fid)
  68494. {
  68495. #if defined(MA_X86) && defined(__PIC__)
  68496. __asm__ __volatile__ (
  68497. "xchg{l} {%%}ebx, %k1;"
  68498. "cpuid;"
  68499. "xchg{l} {%%}ebx, %k1;"
  68500. : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  68501. );
  68502. #else
  68503. __asm__ __volatile__ (
  68504. "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  68505. );
  68506. #endif
  68507. }
  68508. #else
  68509. #define MA_DR_FLAC_NO_CPUID
  68510. #endif
  68511. #endif
  68512. #else
  68513. #define MA_DR_FLAC_NO_CPUID
  68514. #endif
  68515. static MA_INLINE ma_bool32 ma_dr_flac_has_sse2(void)
  68516. {
  68517. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  68518. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_DR_FLAC_NO_SSE2)
  68519. #if defined(MA_X64)
  68520. return MA_TRUE;
  68521. #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  68522. return MA_TRUE;
  68523. #else
  68524. #if defined(MA_DR_FLAC_NO_CPUID)
  68525. return MA_FALSE;
  68526. #else
  68527. int info[4];
  68528. ma_dr_flac__cpuid(info, 1);
  68529. return (info[3] & (1 << 26)) != 0;
  68530. #endif
  68531. #endif
  68532. #else
  68533. return MA_FALSE;
  68534. #endif
  68535. #else
  68536. return MA_FALSE;
  68537. #endif
  68538. }
  68539. static MA_INLINE ma_bool32 ma_dr_flac_has_sse41(void)
  68540. {
  68541. #if defined(MA_DR_FLAC_SUPPORT_SSE41)
  68542. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_DR_FLAC_NO_SSE41)
  68543. #if defined(__SSE4_1__) || defined(__AVX__)
  68544. return MA_TRUE;
  68545. #else
  68546. #if defined(MA_DR_FLAC_NO_CPUID)
  68547. return MA_FALSE;
  68548. #else
  68549. int info[4];
  68550. ma_dr_flac__cpuid(info, 1);
  68551. return (info[2] & (1 << 19)) != 0;
  68552. #endif
  68553. #endif
  68554. #else
  68555. return MA_FALSE;
  68556. #endif
  68557. #else
  68558. return MA_FALSE;
  68559. #endif
  68560. }
  68561. #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(MA_X86) || defined(MA_X64)) && !defined(__clang__)
  68562. #define MA_DR_FLAC_HAS_LZCNT_INTRINSIC
  68563. #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  68564. #define MA_DR_FLAC_HAS_LZCNT_INTRINSIC
  68565. #elif defined(__clang__)
  68566. #if defined(__has_builtin)
  68567. #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
  68568. #define MA_DR_FLAC_HAS_LZCNT_INTRINSIC
  68569. #endif
  68570. #endif
  68571. #endif
  68572. #if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__)
  68573. #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC
  68574. #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC
  68575. #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC
  68576. #elif defined(__clang__)
  68577. #if defined(__has_builtin)
  68578. #if __has_builtin(__builtin_bswap16)
  68579. #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC
  68580. #endif
  68581. #if __has_builtin(__builtin_bswap32)
  68582. #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC
  68583. #endif
  68584. #if __has_builtin(__builtin_bswap64)
  68585. #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC
  68586. #endif
  68587. #endif
  68588. #elif defined(__GNUC__)
  68589. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  68590. #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC
  68591. #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC
  68592. #endif
  68593. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  68594. #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC
  68595. #endif
  68596. #elif defined(__WATCOMC__) && defined(__386__)
  68597. #define MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC
  68598. #define MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC
  68599. #define MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC
  68600. extern __inline ma_uint16 _watcom_bswap16(ma_uint16);
  68601. extern __inline ma_uint32 _watcom_bswap32(ma_uint32);
  68602. extern __inline ma_uint64 _watcom_bswap64(ma_uint64);
  68603. #pragma aux _watcom_bswap16 = \
  68604. "xchg al, ah" \
  68605. parm [ax] \
  68606. value [ax] \
  68607. modify nomemory;
  68608. #pragma aux _watcom_bswap32 = \
  68609. "bswap eax" \
  68610. parm [eax] \
  68611. value [eax] \
  68612. modify nomemory;
  68613. #pragma aux _watcom_bswap64 = \
  68614. "bswap eax" \
  68615. "bswap edx" \
  68616. "xchg eax,edx" \
  68617. parm [eax edx] \
  68618. value [eax edx] \
  68619. modify nomemory;
  68620. #endif
  68621. #ifndef MA_DR_FLAC_ASSERT
  68622. #include <assert.h>
  68623. #define MA_DR_FLAC_ASSERT(expression) assert(expression)
  68624. #endif
  68625. #ifndef MA_DR_FLAC_MALLOC
  68626. #define MA_DR_FLAC_MALLOC(sz) malloc((sz))
  68627. #endif
  68628. #ifndef MA_DR_FLAC_REALLOC
  68629. #define MA_DR_FLAC_REALLOC(p, sz) realloc((p), (sz))
  68630. #endif
  68631. #ifndef MA_DR_FLAC_FREE
  68632. #define MA_DR_FLAC_FREE(p) free((p))
  68633. #endif
  68634. #ifndef MA_DR_FLAC_COPY_MEMORY
  68635. #define MA_DR_FLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  68636. #endif
  68637. #ifndef MA_DR_FLAC_ZERO_MEMORY
  68638. #define MA_DR_FLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  68639. #endif
  68640. #ifndef MA_DR_FLAC_ZERO_OBJECT
  68641. #define MA_DR_FLAC_ZERO_OBJECT(p) MA_DR_FLAC_ZERO_MEMORY((p), sizeof(*(p)))
  68642. #endif
  68643. #define MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE 64
  68644. #define MA_DR_FLAC_SUBFRAME_CONSTANT 0
  68645. #define MA_DR_FLAC_SUBFRAME_VERBATIM 1
  68646. #define MA_DR_FLAC_SUBFRAME_FIXED 8
  68647. #define MA_DR_FLAC_SUBFRAME_LPC 32
  68648. #define MA_DR_FLAC_SUBFRAME_RESERVED 255
  68649. #define MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
  68650. #define MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
  68651. #define MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
  68652. #define MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
  68653. #define MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
  68654. #define MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
  68655. #define MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES 18
  68656. #define MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36
  68657. #define MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12
  68658. #define ma_dr_flac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  68659. MA_API void ma_dr_flac_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
  68660. {
  68661. if (pMajor) {
  68662. *pMajor = MA_DR_FLAC_VERSION_MAJOR;
  68663. }
  68664. if (pMinor) {
  68665. *pMinor = MA_DR_FLAC_VERSION_MINOR;
  68666. }
  68667. if (pRevision) {
  68668. *pRevision = MA_DR_FLAC_VERSION_REVISION;
  68669. }
  68670. }
  68671. MA_API const char* ma_dr_flac_version_string(void)
  68672. {
  68673. return MA_DR_FLAC_VERSION_STRING;
  68674. }
  68675. #if defined(__has_feature)
  68676. #if __has_feature(thread_sanitizer)
  68677. #define MA_DR_FLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
  68678. #else
  68679. #define MA_DR_FLAC_NO_THREAD_SANITIZE
  68680. #endif
  68681. #else
  68682. #define MA_DR_FLAC_NO_THREAD_SANITIZE
  68683. #endif
  68684. #if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC)
  68685. static ma_bool32 ma_dr_flac__gIsLZCNTSupported = MA_FALSE;
  68686. #endif
  68687. #ifndef MA_DR_FLAC_NO_CPUID
  68688. static ma_bool32 ma_dr_flac__gIsSSE2Supported = MA_FALSE;
  68689. static ma_bool32 ma_dr_flac__gIsSSE41Supported = MA_FALSE;
  68690. MA_DR_FLAC_NO_THREAD_SANITIZE static void ma_dr_flac__init_cpu_caps(void)
  68691. {
  68692. static ma_bool32 isCPUCapsInitialized = MA_FALSE;
  68693. if (!isCPUCapsInitialized) {
  68694. #if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC)
  68695. int info[4] = {0};
  68696. ma_dr_flac__cpuid(info, 0x80000001);
  68697. ma_dr_flac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
  68698. #endif
  68699. ma_dr_flac__gIsSSE2Supported = ma_dr_flac_has_sse2();
  68700. ma_dr_flac__gIsSSE41Supported = ma_dr_flac_has_sse41();
  68701. isCPUCapsInitialized = MA_TRUE;
  68702. }
  68703. }
  68704. #else
  68705. static ma_bool32 ma_dr_flac__gIsNEONSupported = MA_FALSE;
  68706. static MA_INLINE ma_bool32 ma_dr_flac__has_neon(void)
  68707. {
  68708. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  68709. #if defined(MA_ARM) && !defined(MA_DR_FLAC_NO_NEON)
  68710. #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  68711. return MA_TRUE;
  68712. #else
  68713. return MA_FALSE;
  68714. #endif
  68715. #else
  68716. return MA_FALSE;
  68717. #endif
  68718. #else
  68719. return MA_FALSE;
  68720. #endif
  68721. }
  68722. MA_DR_FLAC_NO_THREAD_SANITIZE static void ma_dr_flac__init_cpu_caps(void)
  68723. {
  68724. ma_dr_flac__gIsNEONSupported = ma_dr_flac__has_neon();
  68725. #if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) && defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  68726. ma_dr_flac__gIsLZCNTSupported = MA_TRUE;
  68727. #endif
  68728. }
  68729. #endif
  68730. static MA_INLINE ma_bool32 ma_dr_flac__is_little_endian(void)
  68731. {
  68732. #if defined(MA_X86) || defined(MA_X64)
  68733. return MA_TRUE;
  68734. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  68735. return MA_TRUE;
  68736. #else
  68737. int n = 1;
  68738. return (*(char*)&n) == 1;
  68739. #endif
  68740. }
  68741. static MA_INLINE ma_uint16 ma_dr_flac__swap_endian_uint16(ma_uint16 n)
  68742. {
  68743. #ifdef MA_DR_FLAC_HAS_BYTESWAP16_INTRINSIC
  68744. #if defined(_MSC_VER) && !defined(__clang__)
  68745. return _byteswap_ushort(n);
  68746. #elif defined(__GNUC__) || defined(__clang__)
  68747. return __builtin_bswap16(n);
  68748. #elif defined(__WATCOMC__) && defined(__386__)
  68749. return _watcom_bswap16(n);
  68750. #else
  68751. #error "This compiler does not support the byte swap intrinsic."
  68752. #endif
  68753. #else
  68754. return ((n & 0xFF00) >> 8) |
  68755. ((n & 0x00FF) << 8);
  68756. #endif
  68757. }
  68758. static MA_INLINE ma_uint32 ma_dr_flac__swap_endian_uint32(ma_uint32 n)
  68759. {
  68760. #ifdef MA_DR_FLAC_HAS_BYTESWAP32_INTRINSIC
  68761. #if defined(_MSC_VER) && !defined(__clang__)
  68762. return _byteswap_ulong(n);
  68763. #elif defined(__GNUC__) || defined(__clang__)
  68764. #if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(__ARM_ARCH_6M__) && !defined(MA_64BIT)
  68765. ma_uint32 r;
  68766. __asm__ __volatile__ (
  68767. #if defined(MA_64BIT)
  68768. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)
  68769. #else
  68770. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  68771. #endif
  68772. );
  68773. return r;
  68774. #else
  68775. return __builtin_bswap32(n);
  68776. #endif
  68777. #elif defined(__WATCOMC__) && defined(__386__)
  68778. return _watcom_bswap32(n);
  68779. #else
  68780. #error "This compiler does not support the byte swap intrinsic."
  68781. #endif
  68782. #else
  68783. return ((n & 0xFF000000) >> 24) |
  68784. ((n & 0x00FF0000) >> 8) |
  68785. ((n & 0x0000FF00) << 8) |
  68786. ((n & 0x000000FF) << 24);
  68787. #endif
  68788. }
  68789. static MA_INLINE ma_uint64 ma_dr_flac__swap_endian_uint64(ma_uint64 n)
  68790. {
  68791. #ifdef MA_DR_FLAC_HAS_BYTESWAP64_INTRINSIC
  68792. #if defined(_MSC_VER) && !defined(__clang__)
  68793. return _byteswap_uint64(n);
  68794. #elif defined(__GNUC__) || defined(__clang__)
  68795. return __builtin_bswap64(n);
  68796. #elif defined(__WATCOMC__) && defined(__386__)
  68797. return _watcom_bswap64(n);
  68798. #else
  68799. #error "This compiler does not support the byte swap intrinsic."
  68800. #endif
  68801. #else
  68802. return ((n & ((ma_uint64)0xFF000000 << 32)) >> 56) |
  68803. ((n & ((ma_uint64)0x00FF0000 << 32)) >> 40) |
  68804. ((n & ((ma_uint64)0x0000FF00 << 32)) >> 24) |
  68805. ((n & ((ma_uint64)0x000000FF << 32)) >> 8) |
  68806. ((n & ((ma_uint64)0xFF000000 )) << 8) |
  68807. ((n & ((ma_uint64)0x00FF0000 )) << 24) |
  68808. ((n & ((ma_uint64)0x0000FF00 )) << 40) |
  68809. ((n & ((ma_uint64)0x000000FF )) << 56);
  68810. #endif
  68811. }
  68812. static MA_INLINE ma_uint16 ma_dr_flac__be2host_16(ma_uint16 n)
  68813. {
  68814. if (ma_dr_flac__is_little_endian()) {
  68815. return ma_dr_flac__swap_endian_uint16(n);
  68816. }
  68817. return n;
  68818. }
  68819. static MA_INLINE ma_uint32 ma_dr_flac__be2host_32(ma_uint32 n)
  68820. {
  68821. if (ma_dr_flac__is_little_endian()) {
  68822. return ma_dr_flac__swap_endian_uint32(n);
  68823. }
  68824. return n;
  68825. }
  68826. static MA_INLINE ma_uint32 ma_dr_flac__be2host_32_ptr_unaligned(const void* pData)
  68827. {
  68828. const ma_uint8* pNum = (ma_uint8*)pData;
  68829. return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3);
  68830. }
  68831. static MA_INLINE ma_uint64 ma_dr_flac__be2host_64(ma_uint64 n)
  68832. {
  68833. if (ma_dr_flac__is_little_endian()) {
  68834. return ma_dr_flac__swap_endian_uint64(n);
  68835. }
  68836. return n;
  68837. }
  68838. static MA_INLINE ma_uint32 ma_dr_flac__le2host_32(ma_uint32 n)
  68839. {
  68840. if (!ma_dr_flac__is_little_endian()) {
  68841. return ma_dr_flac__swap_endian_uint32(n);
  68842. }
  68843. return n;
  68844. }
  68845. static MA_INLINE ma_uint32 ma_dr_flac__le2host_32_ptr_unaligned(const void* pData)
  68846. {
  68847. const ma_uint8* pNum = (ma_uint8*)pData;
  68848. return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24;
  68849. }
  68850. static MA_INLINE ma_uint32 ma_dr_flac__unsynchsafe_32(ma_uint32 n)
  68851. {
  68852. ma_uint32 result = 0;
  68853. result |= (n & 0x7F000000) >> 3;
  68854. result |= (n & 0x007F0000) >> 2;
  68855. result |= (n & 0x00007F00) >> 1;
  68856. result |= (n & 0x0000007F) >> 0;
  68857. return result;
  68858. }
  68859. static ma_uint8 ma_dr_flac__crc8_table[] = {
  68860. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  68861. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  68862. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  68863. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  68864. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  68865. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  68866. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  68867. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  68868. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  68869. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  68870. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  68871. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  68872. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  68873. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  68874. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  68875. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  68876. };
  68877. static ma_uint16 ma_dr_flac__crc16_table[] = {
  68878. 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
  68879. 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
  68880. 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
  68881. 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
  68882. 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
  68883. 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
  68884. 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
  68885. 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
  68886. 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
  68887. 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
  68888. 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
  68889. 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
  68890. 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
  68891. 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
  68892. 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
  68893. 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
  68894. 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
  68895. 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
  68896. 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
  68897. 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
  68898. 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
  68899. 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
  68900. 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
  68901. 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
  68902. 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
  68903. 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
  68904. 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
  68905. 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
  68906. 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
  68907. 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
  68908. 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
  68909. 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
  68910. };
  68911. static MA_INLINE ma_uint8 ma_dr_flac_crc8_byte(ma_uint8 crc, ma_uint8 data)
  68912. {
  68913. return ma_dr_flac__crc8_table[crc ^ data];
  68914. }
  68915. static MA_INLINE ma_uint8 ma_dr_flac_crc8(ma_uint8 crc, ma_uint32 data, ma_uint32 count)
  68916. {
  68917. #ifdef MA_DR_FLAC_NO_CRC
  68918. (void)crc;
  68919. (void)data;
  68920. (void)count;
  68921. return 0;
  68922. #else
  68923. #if 0
  68924. ma_uint8 p = 0x07;
  68925. for (int i = count-1; i >= 0; --i) {
  68926. ma_uint8 bit = (data & (1 << i)) >> i;
  68927. if (crc & 0x80) {
  68928. crc = ((crc << 1) | bit) ^ p;
  68929. } else {
  68930. crc = ((crc << 1) | bit);
  68931. }
  68932. }
  68933. return crc;
  68934. #else
  68935. ma_uint32 wholeBytes;
  68936. ma_uint32 leftoverBits;
  68937. ma_uint64 leftoverDataMask;
  68938. static ma_uint64 leftoverDataMaskTable[8] = {
  68939. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  68940. };
  68941. MA_DR_FLAC_ASSERT(count <= 32);
  68942. wholeBytes = count >> 3;
  68943. leftoverBits = count - (wholeBytes*8);
  68944. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  68945. switch (wholeBytes) {
  68946. case 4: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  68947. case 3: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  68948. case 2: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  68949. case 1: crc = ma_dr_flac_crc8_byte(crc, (ma_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  68950. case 0: if (leftoverBits > 0) crc = (ma_uint8)((crc << leftoverBits) ^ ma_dr_flac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
  68951. }
  68952. return crc;
  68953. #endif
  68954. #endif
  68955. }
  68956. static MA_INLINE ma_uint16 ma_dr_flac_crc16_byte(ma_uint16 crc, ma_uint8 data)
  68957. {
  68958. return (crc << 8) ^ ma_dr_flac__crc16_table[(ma_uint8)(crc >> 8) ^ data];
  68959. }
  68960. static MA_INLINE ma_uint16 ma_dr_flac_crc16_cache(ma_uint16 crc, ma_dr_flac_cache_t data)
  68961. {
  68962. #ifdef MA_64BIT
  68963. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 56) & 0xFF));
  68964. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 48) & 0xFF));
  68965. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 40) & 0xFF));
  68966. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 32) & 0xFF));
  68967. #endif
  68968. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 24) & 0xFF));
  68969. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 16) & 0xFF));
  68970. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 8) & 0xFF));
  68971. crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 0) & 0xFF));
  68972. return crc;
  68973. }
  68974. static MA_INLINE ma_uint16 ma_dr_flac_crc16_bytes(ma_uint16 crc, ma_dr_flac_cache_t data, ma_uint32 byteCount)
  68975. {
  68976. switch (byteCount)
  68977. {
  68978. #ifdef MA_64BIT
  68979. case 8: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 56) & 0xFF));
  68980. case 7: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 48) & 0xFF));
  68981. case 6: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 40) & 0xFF));
  68982. case 5: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 32) & 0xFF));
  68983. #endif
  68984. case 4: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 24) & 0xFF));
  68985. case 3: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 16) & 0xFF));
  68986. case 2: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 8) & 0xFF));
  68987. case 1: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data >> 0) & 0xFF));
  68988. }
  68989. return crc;
  68990. }
  68991. #if 0
  68992. static MA_INLINE ma_uint16 ma_dr_flac_crc16__32bit(ma_uint16 crc, ma_uint32 data, ma_uint32 count)
  68993. {
  68994. #ifdef MA_DR_FLAC_NO_CRC
  68995. (void)crc;
  68996. (void)data;
  68997. (void)count;
  68998. return 0;
  68999. #else
  69000. #if 0
  69001. ma_uint16 p = 0x8005;
  69002. for (int i = count-1; i >= 0; --i) {
  69003. ma_uint16 bit = (data & (1ULL << i)) >> i;
  69004. if (r & 0x8000) {
  69005. r = ((r << 1) | bit) ^ p;
  69006. } else {
  69007. r = ((r << 1) | bit);
  69008. }
  69009. }
  69010. return crc;
  69011. #else
  69012. ma_uint32 wholeBytes;
  69013. ma_uint32 leftoverBits;
  69014. ma_uint64 leftoverDataMask;
  69015. static ma_uint64 leftoverDataMaskTable[8] = {
  69016. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  69017. };
  69018. MA_DR_FLAC_ASSERT(count <= 64);
  69019. wholeBytes = count >> 3;
  69020. leftoverBits = count & 7;
  69021. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  69022. switch (wholeBytes) {
  69023. default:
  69024. case 4: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  69025. case 3: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  69026. case 2: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  69027. case 1: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  69028. case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ ma_dr_flac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  69029. }
  69030. return crc;
  69031. #endif
  69032. #endif
  69033. }
  69034. static MA_INLINE ma_uint16 ma_dr_flac_crc16__64bit(ma_uint16 crc, ma_uint64 data, ma_uint32 count)
  69035. {
  69036. #ifdef MA_DR_FLAC_NO_CRC
  69037. (void)crc;
  69038. (void)data;
  69039. (void)count;
  69040. return 0;
  69041. #else
  69042. ma_uint32 wholeBytes;
  69043. ma_uint32 leftoverBits;
  69044. ma_uint64 leftoverDataMask;
  69045. static ma_uint64 leftoverDataMaskTable[8] = {
  69046. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  69047. };
  69048. MA_DR_FLAC_ASSERT(count <= 64);
  69049. wholeBytes = count >> 3;
  69050. leftoverBits = count & 7;
  69051. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  69052. switch (wholeBytes) {
  69053. default:
  69054. case 8: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits)));
  69055. case 7: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
  69056. case 6: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
  69057. case 5: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
  69058. case 4: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits)));
  69059. case 3: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits)));
  69060. case 2: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits)));
  69061. case 1: crc = ma_dr_flac_crc16_byte(crc, (ma_uint8)((data & (((ma_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits)));
  69062. case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ ma_dr_flac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  69063. }
  69064. return crc;
  69065. #endif
  69066. }
  69067. static MA_INLINE ma_uint16 ma_dr_flac_crc16(ma_uint16 crc, ma_dr_flac_cache_t data, ma_uint32 count)
  69068. {
  69069. #ifdef MA_64BIT
  69070. return ma_dr_flac_crc16__64bit(crc, data, count);
  69071. #else
  69072. return ma_dr_flac_crc16__32bit(crc, data, count);
  69073. #endif
  69074. }
  69075. #endif
  69076. #ifdef MA_64BIT
  69077. #define ma_dr_flac__be2host__cache_line ma_dr_flac__be2host_64
  69078. #else
  69079. #define ma_dr_flac__be2host__cache_line ma_dr_flac__be2host_32
  69080. #endif
  69081. #define MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
  69082. #define MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
  69083. #define MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
  69084. #define MA_DR_FLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(ma_dr_flac_cache_t)0) >> (_bitCount)))
  69085. #define MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
  69086. #define MA_DR_FLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & MA_DR_FLAC_CACHE_L1_SELECTION_MASK(_bitCount))
  69087. #define MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (MA_DR_FLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
  69088. #define MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(MA_DR_FLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)-1)))
  69089. #define MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
  69090. #define MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs) (MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
  69091. #define MA_DR_FLAC_CACHE_L2_LINES_REMAINING(bs) (MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
  69092. #ifndef MA_DR_FLAC_NO_CRC
  69093. static MA_INLINE void ma_dr_flac__reset_crc16(ma_dr_flac_bs* bs)
  69094. {
  69095. bs->crc16 = 0;
  69096. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  69097. }
  69098. static MA_INLINE void ma_dr_flac__update_crc16(ma_dr_flac_bs* bs)
  69099. {
  69100. if (bs->crc16CacheIgnoredBytes == 0) {
  69101. bs->crc16 = ma_dr_flac_crc16_cache(bs->crc16, bs->crc16Cache);
  69102. } else {
  69103. bs->crc16 = ma_dr_flac_crc16_bytes(bs->crc16, bs->crc16Cache, MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
  69104. bs->crc16CacheIgnoredBytes = 0;
  69105. }
  69106. }
  69107. static MA_INLINE ma_uint16 ma_dr_flac__flush_crc16(ma_dr_flac_bs* bs)
  69108. {
  69109. MA_DR_FLAC_ASSERT((MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
  69110. if (MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
  69111. ma_dr_flac__update_crc16(bs);
  69112. } else {
  69113. bs->crc16 = ma_dr_flac_crc16_bytes(bs->crc16, bs->crc16Cache >> MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
  69114. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  69115. }
  69116. return bs->crc16;
  69117. }
  69118. #endif
  69119. static MA_INLINE ma_bool32 ma_dr_flac__reload_l1_cache_from_l2(ma_dr_flac_bs* bs)
  69120. {
  69121. size_t bytesRead;
  69122. size_t alignedL1LineCount;
  69123. if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) {
  69124. bs->cache = bs->cacheL2[bs->nextL2Line++];
  69125. return MA_TRUE;
  69126. }
  69127. if (bs->unalignedByteCount > 0) {
  69128. return MA_FALSE;
  69129. }
  69130. bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs));
  69131. bs->nextL2Line = 0;
  69132. if (bytesRead == MA_DR_FLAC_CACHE_L2_SIZE_BYTES(bs)) {
  69133. bs->cache = bs->cacheL2[bs->nextL2Line++];
  69134. return MA_TRUE;
  69135. }
  69136. alignedL1LineCount = bytesRead / MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs);
  69137. bs->unalignedByteCount = bytesRead - (alignedL1LineCount * MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs));
  69138. if (bs->unalignedByteCount > 0) {
  69139. bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
  69140. }
  69141. if (alignedL1LineCount > 0) {
  69142. size_t offset = MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
  69143. size_t i;
  69144. for (i = alignedL1LineCount; i > 0; --i) {
  69145. bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
  69146. }
  69147. bs->nextL2Line = (ma_uint32)offset;
  69148. bs->cache = bs->cacheL2[bs->nextL2Line++];
  69149. return MA_TRUE;
  69150. } else {
  69151. bs->nextL2Line = MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs);
  69152. return MA_FALSE;
  69153. }
  69154. }
  69155. static ma_bool32 ma_dr_flac__reload_cache(ma_dr_flac_bs* bs)
  69156. {
  69157. size_t bytesRead;
  69158. #ifndef MA_DR_FLAC_NO_CRC
  69159. ma_dr_flac__update_crc16(bs);
  69160. #endif
  69161. if (ma_dr_flac__reload_l1_cache_from_l2(bs)) {
  69162. bs->cache = ma_dr_flac__be2host__cache_line(bs->cache);
  69163. bs->consumedBits = 0;
  69164. #ifndef MA_DR_FLAC_NO_CRC
  69165. bs->crc16Cache = bs->cache;
  69166. #endif
  69167. return MA_TRUE;
  69168. }
  69169. bytesRead = bs->unalignedByteCount;
  69170. if (bytesRead == 0) {
  69171. bs->consumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs);
  69172. return MA_FALSE;
  69173. }
  69174. MA_DR_FLAC_ASSERT(bytesRead < MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs));
  69175. bs->consumedBits = (ma_uint32)(MA_DR_FLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
  69176. bs->cache = ma_dr_flac__be2host__cache_line(bs->unalignedCache);
  69177. bs->cache &= MA_DR_FLAC_CACHE_L1_SELECTION_MASK(MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs));
  69178. bs->unalignedByteCount = 0;
  69179. #ifndef MA_DR_FLAC_NO_CRC
  69180. bs->crc16Cache = bs->cache >> bs->consumedBits;
  69181. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  69182. #endif
  69183. return MA_TRUE;
  69184. }
  69185. static void ma_dr_flac__reset_cache(ma_dr_flac_bs* bs)
  69186. {
  69187. bs->nextL2Line = MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs);
  69188. bs->consumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs);
  69189. bs->cache = 0;
  69190. bs->unalignedByteCount = 0;
  69191. bs->unalignedCache = 0;
  69192. #ifndef MA_DR_FLAC_NO_CRC
  69193. bs->crc16Cache = 0;
  69194. bs->crc16CacheIgnoredBytes = 0;
  69195. #endif
  69196. }
  69197. static MA_INLINE ma_bool32 ma_dr_flac__read_uint32(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint32* pResultOut)
  69198. {
  69199. MA_DR_FLAC_ASSERT(bs != NULL);
  69200. MA_DR_FLAC_ASSERT(pResultOut != NULL);
  69201. MA_DR_FLAC_ASSERT(bitCount > 0);
  69202. MA_DR_FLAC_ASSERT(bitCount <= 32);
  69203. if (bs->consumedBits == MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) {
  69204. if (!ma_dr_flac__reload_cache(bs)) {
  69205. return MA_FALSE;
  69206. }
  69207. }
  69208. if (bitCount <= MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69209. #ifdef MA_64BIT
  69210. *pResultOut = (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  69211. bs->consumedBits += bitCount;
  69212. bs->cache <<= bitCount;
  69213. #else
  69214. if (bitCount < MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) {
  69215. *pResultOut = (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  69216. bs->consumedBits += bitCount;
  69217. bs->cache <<= bitCount;
  69218. } else {
  69219. *pResultOut = (ma_uint32)bs->cache;
  69220. bs->consumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs);
  69221. bs->cache = 0;
  69222. }
  69223. #endif
  69224. return MA_TRUE;
  69225. } else {
  69226. ma_uint32 bitCountHi = MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs);
  69227. ma_uint32 bitCountLo = bitCount - bitCountHi;
  69228. ma_uint32 resultHi;
  69229. MA_DR_FLAC_ASSERT(bitCountHi > 0);
  69230. MA_DR_FLAC_ASSERT(bitCountHi < 32);
  69231. resultHi = (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
  69232. if (!ma_dr_flac__reload_cache(bs)) {
  69233. return MA_FALSE;
  69234. }
  69235. if (bitCountLo > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69236. return MA_FALSE;
  69237. }
  69238. *pResultOut = (resultHi << bitCountLo) | (ma_uint32)MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
  69239. bs->consumedBits += bitCountLo;
  69240. bs->cache <<= bitCountLo;
  69241. return MA_TRUE;
  69242. }
  69243. }
  69244. static ma_bool32 ma_dr_flac__read_int32(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int32* pResult)
  69245. {
  69246. ma_uint32 result;
  69247. MA_DR_FLAC_ASSERT(bs != NULL);
  69248. MA_DR_FLAC_ASSERT(pResult != NULL);
  69249. MA_DR_FLAC_ASSERT(bitCount > 0);
  69250. MA_DR_FLAC_ASSERT(bitCount <= 32);
  69251. if (!ma_dr_flac__read_uint32(bs, bitCount, &result)) {
  69252. return MA_FALSE;
  69253. }
  69254. if (bitCount < 32) {
  69255. ma_uint32 signbit;
  69256. signbit = ((result >> (bitCount-1)) & 0x01);
  69257. result |= (~signbit + 1) << bitCount;
  69258. }
  69259. *pResult = (ma_int32)result;
  69260. return MA_TRUE;
  69261. }
  69262. #ifdef MA_64BIT
  69263. static ma_bool32 ma_dr_flac__read_uint64(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint64* pResultOut)
  69264. {
  69265. ma_uint32 resultHi;
  69266. ma_uint32 resultLo;
  69267. MA_DR_FLAC_ASSERT(bitCount <= 64);
  69268. MA_DR_FLAC_ASSERT(bitCount > 32);
  69269. if (!ma_dr_flac__read_uint32(bs, bitCount - 32, &resultHi)) {
  69270. return MA_FALSE;
  69271. }
  69272. if (!ma_dr_flac__read_uint32(bs, 32, &resultLo)) {
  69273. return MA_FALSE;
  69274. }
  69275. *pResultOut = (((ma_uint64)resultHi) << 32) | ((ma_uint64)resultLo);
  69276. return MA_TRUE;
  69277. }
  69278. #endif
  69279. #if 0
  69280. static ma_bool32 ma_dr_flac__read_int64(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int64* pResultOut)
  69281. {
  69282. ma_uint64 result;
  69283. ma_uint64 signbit;
  69284. MA_DR_FLAC_ASSERT(bitCount <= 64);
  69285. if (!ma_dr_flac__read_uint64(bs, bitCount, &result)) {
  69286. return MA_FALSE;
  69287. }
  69288. signbit = ((result >> (bitCount-1)) & 0x01);
  69289. result |= (~signbit + 1) << bitCount;
  69290. *pResultOut = (ma_int64)result;
  69291. return MA_TRUE;
  69292. }
  69293. #endif
  69294. static ma_bool32 ma_dr_flac__read_uint16(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint16* pResult)
  69295. {
  69296. ma_uint32 result;
  69297. MA_DR_FLAC_ASSERT(bs != NULL);
  69298. MA_DR_FLAC_ASSERT(pResult != NULL);
  69299. MA_DR_FLAC_ASSERT(bitCount > 0);
  69300. MA_DR_FLAC_ASSERT(bitCount <= 16);
  69301. if (!ma_dr_flac__read_uint32(bs, bitCount, &result)) {
  69302. return MA_FALSE;
  69303. }
  69304. *pResult = (ma_uint16)result;
  69305. return MA_TRUE;
  69306. }
  69307. #if 0
  69308. static ma_bool32 ma_dr_flac__read_int16(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int16* pResult)
  69309. {
  69310. ma_int32 result;
  69311. MA_DR_FLAC_ASSERT(bs != NULL);
  69312. MA_DR_FLAC_ASSERT(pResult != NULL);
  69313. MA_DR_FLAC_ASSERT(bitCount > 0);
  69314. MA_DR_FLAC_ASSERT(bitCount <= 16);
  69315. if (!ma_dr_flac__read_int32(bs, bitCount, &result)) {
  69316. return MA_FALSE;
  69317. }
  69318. *pResult = (ma_int16)result;
  69319. return MA_TRUE;
  69320. }
  69321. #endif
  69322. static ma_bool32 ma_dr_flac__read_uint8(ma_dr_flac_bs* bs, unsigned int bitCount, ma_uint8* pResult)
  69323. {
  69324. ma_uint32 result;
  69325. MA_DR_FLAC_ASSERT(bs != NULL);
  69326. MA_DR_FLAC_ASSERT(pResult != NULL);
  69327. MA_DR_FLAC_ASSERT(bitCount > 0);
  69328. MA_DR_FLAC_ASSERT(bitCount <= 8);
  69329. if (!ma_dr_flac__read_uint32(bs, bitCount, &result)) {
  69330. return MA_FALSE;
  69331. }
  69332. *pResult = (ma_uint8)result;
  69333. return MA_TRUE;
  69334. }
  69335. static ma_bool32 ma_dr_flac__read_int8(ma_dr_flac_bs* bs, unsigned int bitCount, ma_int8* pResult)
  69336. {
  69337. ma_int32 result;
  69338. MA_DR_FLAC_ASSERT(bs != NULL);
  69339. MA_DR_FLAC_ASSERT(pResult != NULL);
  69340. MA_DR_FLAC_ASSERT(bitCount > 0);
  69341. MA_DR_FLAC_ASSERT(bitCount <= 8);
  69342. if (!ma_dr_flac__read_int32(bs, bitCount, &result)) {
  69343. return MA_FALSE;
  69344. }
  69345. *pResult = (ma_int8)result;
  69346. return MA_TRUE;
  69347. }
  69348. static ma_bool32 ma_dr_flac__seek_bits(ma_dr_flac_bs* bs, size_t bitsToSeek)
  69349. {
  69350. if (bitsToSeek <= MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69351. bs->consumedBits += (ma_uint32)bitsToSeek;
  69352. bs->cache <<= bitsToSeek;
  69353. return MA_TRUE;
  69354. } else {
  69355. bitsToSeek -= MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs);
  69356. bs->consumedBits += MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs);
  69357. bs->cache = 0;
  69358. #ifdef MA_64BIT
  69359. while (bitsToSeek >= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) {
  69360. ma_uint64 bin;
  69361. if (!ma_dr_flac__read_uint64(bs, MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  69362. return MA_FALSE;
  69363. }
  69364. bitsToSeek -= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs);
  69365. }
  69366. #else
  69367. while (bitsToSeek >= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)) {
  69368. ma_uint32 bin;
  69369. if (!ma_dr_flac__read_uint32(bs, MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  69370. return MA_FALSE;
  69371. }
  69372. bitsToSeek -= MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs);
  69373. }
  69374. #endif
  69375. while (bitsToSeek >= 8) {
  69376. ma_uint8 bin;
  69377. if (!ma_dr_flac__read_uint8(bs, 8, &bin)) {
  69378. return MA_FALSE;
  69379. }
  69380. bitsToSeek -= 8;
  69381. }
  69382. if (bitsToSeek > 0) {
  69383. ma_uint8 bin;
  69384. if (!ma_dr_flac__read_uint8(bs, (ma_uint32)bitsToSeek, &bin)) {
  69385. return MA_FALSE;
  69386. }
  69387. bitsToSeek = 0;
  69388. }
  69389. MA_DR_FLAC_ASSERT(bitsToSeek == 0);
  69390. return MA_TRUE;
  69391. }
  69392. }
  69393. static ma_bool32 ma_dr_flac__find_and_seek_to_next_sync_code(ma_dr_flac_bs* bs)
  69394. {
  69395. MA_DR_FLAC_ASSERT(bs != NULL);
  69396. if (!ma_dr_flac__seek_bits(bs, MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  69397. return MA_FALSE;
  69398. }
  69399. for (;;) {
  69400. ma_uint8 hi;
  69401. #ifndef MA_DR_FLAC_NO_CRC
  69402. ma_dr_flac__reset_crc16(bs);
  69403. #endif
  69404. if (!ma_dr_flac__read_uint8(bs, 8, &hi)) {
  69405. return MA_FALSE;
  69406. }
  69407. if (hi == 0xFF) {
  69408. ma_uint8 lo;
  69409. if (!ma_dr_flac__read_uint8(bs, 6, &lo)) {
  69410. return MA_FALSE;
  69411. }
  69412. if (lo == 0x3E) {
  69413. return MA_TRUE;
  69414. } else {
  69415. if (!ma_dr_flac__seek_bits(bs, MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  69416. return MA_FALSE;
  69417. }
  69418. }
  69419. }
  69420. }
  69421. }
  69422. #if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC)
  69423. #define MA_DR_FLAC_IMPLEMENT_CLZ_LZCNT
  69424. #endif
  69425. #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(MA_X64) || defined(MA_X86)) && !defined(__clang__)
  69426. #define MA_DR_FLAC_IMPLEMENT_CLZ_MSVC
  69427. #endif
  69428. #if defined(__WATCOMC__) && defined(__386__)
  69429. #define MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM
  69430. #endif
  69431. #ifdef __MRC__
  69432. #include <intrinsics.h>
  69433. #define MA_DR_FLAC_IMPLEMENT_CLZ_MRC
  69434. #endif
  69435. static MA_INLINE ma_uint32 ma_dr_flac__clz_software(ma_dr_flac_cache_t x)
  69436. {
  69437. ma_uint32 n;
  69438. static ma_uint32 clz_table_4[] = {
  69439. 0,
  69440. 4,
  69441. 3, 3,
  69442. 2, 2, 2, 2,
  69443. 1, 1, 1, 1, 1, 1, 1, 1
  69444. };
  69445. if (x == 0) {
  69446. return sizeof(x)*8;
  69447. }
  69448. n = clz_table_4[x >> (sizeof(x)*8 - 4)];
  69449. if (n == 0) {
  69450. #ifdef MA_64BIT
  69451. if ((x & ((ma_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; }
  69452. if ((x & ((ma_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
  69453. if ((x & ((ma_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; }
  69454. if ((x & ((ma_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; }
  69455. #else
  69456. if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
  69457. if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
  69458. if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
  69459. #endif
  69460. n += clz_table_4[x >> (sizeof(x)*8 - 4)];
  69461. }
  69462. return n - 1;
  69463. }
  69464. #ifdef MA_DR_FLAC_IMPLEMENT_CLZ_LZCNT
  69465. static MA_INLINE ma_bool32 ma_dr_flac__is_lzcnt_supported(void)
  69466. {
  69467. #if defined(MA_DR_FLAC_HAS_LZCNT_INTRINSIC) && defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  69468. return MA_TRUE;
  69469. #elif defined(__MRC__)
  69470. return MA_TRUE;
  69471. #else
  69472. #ifdef MA_DR_FLAC_HAS_LZCNT_INTRINSIC
  69473. return ma_dr_flac__gIsLZCNTSupported;
  69474. #else
  69475. return MA_FALSE;
  69476. #endif
  69477. #endif
  69478. }
  69479. static MA_INLINE ma_uint32 ma_dr_flac__clz_lzcnt(ma_dr_flac_cache_t x)
  69480. {
  69481. #if defined(_MSC_VER)
  69482. #ifdef MA_64BIT
  69483. return (ma_uint32)__lzcnt64(x);
  69484. #else
  69485. return (ma_uint32)__lzcnt(x);
  69486. #endif
  69487. #else
  69488. #if defined(__GNUC__) || defined(__clang__)
  69489. #if defined(MA_X64)
  69490. {
  69491. ma_uint64 r;
  69492. __asm__ __volatile__ (
  69493. "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
  69494. );
  69495. return (ma_uint32)r;
  69496. }
  69497. #elif defined(MA_X86)
  69498. {
  69499. ma_uint32 r;
  69500. __asm__ __volatile__ (
  69501. "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
  69502. );
  69503. return r;
  69504. }
  69505. #elif defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(__ARM_ARCH_6M__) && !defined(MA_64BIT)
  69506. {
  69507. unsigned int r;
  69508. __asm__ __volatile__ (
  69509. #if defined(MA_64BIT)
  69510. "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x)
  69511. #else
  69512. "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
  69513. #endif
  69514. );
  69515. return r;
  69516. }
  69517. #else
  69518. if (x == 0) {
  69519. return sizeof(x)*8;
  69520. }
  69521. #ifdef MA_64BIT
  69522. return (ma_uint32)__builtin_clzll((ma_uint64)x);
  69523. #else
  69524. return (ma_uint32)__builtin_clzl((ma_uint32)x);
  69525. #endif
  69526. #endif
  69527. #else
  69528. #error "This compiler does not support the lzcnt intrinsic."
  69529. #endif
  69530. #endif
  69531. }
  69532. #endif
  69533. #ifdef MA_DR_FLAC_IMPLEMENT_CLZ_MSVC
  69534. #include <intrin.h>
  69535. static MA_INLINE ma_uint32 ma_dr_flac__clz_msvc(ma_dr_flac_cache_t x)
  69536. {
  69537. ma_uint32 n;
  69538. if (x == 0) {
  69539. return sizeof(x)*8;
  69540. }
  69541. #ifdef MA_64BIT
  69542. _BitScanReverse64((unsigned long*)&n, x);
  69543. #else
  69544. _BitScanReverse((unsigned long*)&n, x);
  69545. #endif
  69546. return sizeof(x)*8 - n - 1;
  69547. }
  69548. #endif
  69549. #ifdef MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM
  69550. static __inline ma_uint32 ma_dr_flac__clz_watcom (ma_uint32);
  69551. #ifdef MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM_LZCNT
  69552. #pragma aux ma_dr_flac__clz_watcom_lzcnt = \
  69553. "db 0F3h, 0Fh, 0BDh, 0C0h" \
  69554. parm [eax] \
  69555. value [eax] \
  69556. modify nomemory;
  69557. #else
  69558. #pragma aux ma_dr_flac__clz_watcom = \
  69559. "bsr eax, eax" \
  69560. "xor eax, 31" \
  69561. parm [eax] nomemory \
  69562. value [eax] \
  69563. modify exact [eax] nomemory;
  69564. #endif
  69565. #endif
  69566. static MA_INLINE ma_uint32 ma_dr_flac__clz(ma_dr_flac_cache_t x)
  69567. {
  69568. #ifdef MA_DR_FLAC_IMPLEMENT_CLZ_LZCNT
  69569. if (ma_dr_flac__is_lzcnt_supported()) {
  69570. return ma_dr_flac__clz_lzcnt(x);
  69571. } else
  69572. #endif
  69573. {
  69574. #ifdef MA_DR_FLAC_IMPLEMENT_CLZ_MSVC
  69575. return ma_dr_flac__clz_msvc(x);
  69576. #elif defined(MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM_LZCNT)
  69577. return ma_dr_flac__clz_watcom_lzcnt(x);
  69578. #elif defined(MA_DR_FLAC_IMPLEMENT_CLZ_WATCOM)
  69579. return (x == 0) ? sizeof(x)*8 : ma_dr_flac__clz_watcom(x);
  69580. #elif defined(__MRC__)
  69581. return __cntlzw(x);
  69582. #else
  69583. return ma_dr_flac__clz_software(x);
  69584. #endif
  69585. }
  69586. }
  69587. static MA_INLINE ma_bool32 ma_dr_flac__seek_past_next_set_bit(ma_dr_flac_bs* bs, unsigned int* pOffsetOut)
  69588. {
  69589. ma_uint32 zeroCounter = 0;
  69590. ma_uint32 setBitOffsetPlus1;
  69591. while (bs->cache == 0) {
  69592. zeroCounter += (ma_uint32)MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs);
  69593. if (!ma_dr_flac__reload_cache(bs)) {
  69594. return MA_FALSE;
  69595. }
  69596. }
  69597. if (bs->cache == 1) {
  69598. *pOffsetOut = zeroCounter + (ma_uint32)MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
  69599. if (!ma_dr_flac__reload_cache(bs)) {
  69600. return MA_FALSE;
  69601. }
  69602. return MA_TRUE;
  69603. }
  69604. setBitOffsetPlus1 = ma_dr_flac__clz(bs->cache);
  69605. setBitOffsetPlus1 += 1;
  69606. if (setBitOffsetPlus1 > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  69607. return MA_FALSE;
  69608. }
  69609. bs->consumedBits += setBitOffsetPlus1;
  69610. bs->cache <<= setBitOffsetPlus1;
  69611. *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
  69612. return MA_TRUE;
  69613. }
  69614. static ma_bool32 ma_dr_flac__seek_to_byte(ma_dr_flac_bs* bs, ma_uint64 offsetFromStart)
  69615. {
  69616. MA_DR_FLAC_ASSERT(bs != NULL);
  69617. MA_DR_FLAC_ASSERT(offsetFromStart > 0);
  69618. if (offsetFromStart > 0x7FFFFFFF) {
  69619. ma_uint64 bytesRemaining = offsetFromStart;
  69620. if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_start)) {
  69621. return MA_FALSE;
  69622. }
  69623. bytesRemaining -= 0x7FFFFFFF;
  69624. while (bytesRemaining > 0x7FFFFFFF) {
  69625. if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_current)) {
  69626. return MA_FALSE;
  69627. }
  69628. bytesRemaining -= 0x7FFFFFFF;
  69629. }
  69630. if (bytesRemaining > 0) {
  69631. if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, ma_dr_flac_seek_origin_current)) {
  69632. return MA_FALSE;
  69633. }
  69634. }
  69635. } else {
  69636. if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, ma_dr_flac_seek_origin_start)) {
  69637. return MA_FALSE;
  69638. }
  69639. }
  69640. ma_dr_flac__reset_cache(bs);
  69641. return MA_TRUE;
  69642. }
  69643. static ma_result ma_dr_flac__read_utf8_coded_number(ma_dr_flac_bs* bs, ma_uint64* pNumberOut, ma_uint8* pCRCOut)
  69644. {
  69645. ma_uint8 crc;
  69646. ma_uint64 result;
  69647. ma_uint8 utf8[7] = {0};
  69648. int byteCount;
  69649. int i;
  69650. MA_DR_FLAC_ASSERT(bs != NULL);
  69651. MA_DR_FLAC_ASSERT(pNumberOut != NULL);
  69652. MA_DR_FLAC_ASSERT(pCRCOut != NULL);
  69653. crc = *pCRCOut;
  69654. if (!ma_dr_flac__read_uint8(bs, 8, utf8)) {
  69655. *pNumberOut = 0;
  69656. return MA_AT_END;
  69657. }
  69658. crc = ma_dr_flac_crc8(crc, utf8[0], 8);
  69659. if ((utf8[0] & 0x80) == 0) {
  69660. *pNumberOut = utf8[0];
  69661. *pCRCOut = crc;
  69662. return MA_SUCCESS;
  69663. }
  69664. if ((utf8[0] & 0xE0) == 0xC0) {
  69665. byteCount = 2;
  69666. } else if ((utf8[0] & 0xF0) == 0xE0) {
  69667. byteCount = 3;
  69668. } else if ((utf8[0] & 0xF8) == 0xF0) {
  69669. byteCount = 4;
  69670. } else if ((utf8[0] & 0xFC) == 0xF8) {
  69671. byteCount = 5;
  69672. } else if ((utf8[0] & 0xFE) == 0xFC) {
  69673. byteCount = 6;
  69674. } else if ((utf8[0] & 0xFF) == 0xFE) {
  69675. byteCount = 7;
  69676. } else {
  69677. *pNumberOut = 0;
  69678. return MA_CRC_MISMATCH;
  69679. }
  69680. MA_DR_FLAC_ASSERT(byteCount > 1);
  69681. result = (ma_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
  69682. for (i = 1; i < byteCount; ++i) {
  69683. if (!ma_dr_flac__read_uint8(bs, 8, utf8 + i)) {
  69684. *pNumberOut = 0;
  69685. return MA_AT_END;
  69686. }
  69687. crc = ma_dr_flac_crc8(crc, utf8[i], 8);
  69688. result = (result << 6) | (utf8[i] & 0x3F);
  69689. }
  69690. *pNumberOut = result;
  69691. *pCRCOut = crc;
  69692. return MA_SUCCESS;
  69693. }
  69694. static MA_INLINE ma_uint32 ma_dr_flac__ilog2_u32(ma_uint32 x)
  69695. {
  69696. #if 1
  69697. ma_uint32 result = 0;
  69698. while (x > 0) {
  69699. result += 1;
  69700. x >>= 1;
  69701. }
  69702. return result;
  69703. #endif
  69704. }
  69705. static MA_INLINE ma_bool32 ma_dr_flac__use_64_bit_prediction(ma_uint32 bitsPerSample, ma_uint32 order, ma_uint32 precision)
  69706. {
  69707. return bitsPerSample + precision + ma_dr_flac__ilog2_u32(order) > 32;
  69708. }
  69709. #if defined(__clang__)
  69710. __attribute__((no_sanitize("signed-integer-overflow")))
  69711. #endif
  69712. static MA_INLINE ma_int32 ma_dr_flac__calculate_prediction_32(ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pDecodedSamples)
  69713. {
  69714. ma_int32 prediction = 0;
  69715. MA_DR_FLAC_ASSERT(order <= 32);
  69716. switch (order)
  69717. {
  69718. case 32: prediction += coefficients[31] * pDecodedSamples[-32];
  69719. case 31: prediction += coefficients[30] * pDecodedSamples[-31];
  69720. case 30: prediction += coefficients[29] * pDecodedSamples[-30];
  69721. case 29: prediction += coefficients[28] * pDecodedSamples[-29];
  69722. case 28: prediction += coefficients[27] * pDecodedSamples[-28];
  69723. case 27: prediction += coefficients[26] * pDecodedSamples[-27];
  69724. case 26: prediction += coefficients[25] * pDecodedSamples[-26];
  69725. case 25: prediction += coefficients[24] * pDecodedSamples[-25];
  69726. case 24: prediction += coefficients[23] * pDecodedSamples[-24];
  69727. case 23: prediction += coefficients[22] * pDecodedSamples[-23];
  69728. case 22: prediction += coefficients[21] * pDecodedSamples[-22];
  69729. case 21: prediction += coefficients[20] * pDecodedSamples[-21];
  69730. case 20: prediction += coefficients[19] * pDecodedSamples[-20];
  69731. case 19: prediction += coefficients[18] * pDecodedSamples[-19];
  69732. case 18: prediction += coefficients[17] * pDecodedSamples[-18];
  69733. case 17: prediction += coefficients[16] * pDecodedSamples[-17];
  69734. case 16: prediction += coefficients[15] * pDecodedSamples[-16];
  69735. case 15: prediction += coefficients[14] * pDecodedSamples[-15];
  69736. case 14: prediction += coefficients[13] * pDecodedSamples[-14];
  69737. case 13: prediction += coefficients[12] * pDecodedSamples[-13];
  69738. case 12: prediction += coefficients[11] * pDecodedSamples[-12];
  69739. case 11: prediction += coefficients[10] * pDecodedSamples[-11];
  69740. case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
  69741. case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
  69742. case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
  69743. case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
  69744. case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
  69745. case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
  69746. case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
  69747. case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
  69748. case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
  69749. case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
  69750. }
  69751. return (ma_int32)(prediction >> shift);
  69752. }
  69753. static MA_INLINE ma_int32 ma_dr_flac__calculate_prediction_64(ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pDecodedSamples)
  69754. {
  69755. ma_int64 prediction;
  69756. MA_DR_FLAC_ASSERT(order <= 32);
  69757. #ifndef MA_64BIT
  69758. if (order == 8)
  69759. {
  69760. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69761. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69762. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69763. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69764. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69765. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69766. prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7];
  69767. prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8];
  69768. }
  69769. else if (order == 7)
  69770. {
  69771. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69772. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69773. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69774. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69775. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69776. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69777. prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7];
  69778. }
  69779. else if (order == 3)
  69780. {
  69781. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69782. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69783. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69784. }
  69785. else if (order == 6)
  69786. {
  69787. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69788. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69789. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69790. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69791. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69792. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69793. }
  69794. else if (order == 5)
  69795. {
  69796. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69797. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69798. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69799. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69800. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69801. }
  69802. else if (order == 4)
  69803. {
  69804. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69805. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69806. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69807. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69808. }
  69809. else if (order == 12)
  69810. {
  69811. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69812. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69813. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69814. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69815. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69816. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69817. prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7];
  69818. prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8];
  69819. prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9];
  69820. prediction += coefficients[9] * (ma_int64)pDecodedSamples[-10];
  69821. prediction += coefficients[10] * (ma_int64)pDecodedSamples[-11];
  69822. prediction += coefficients[11] * (ma_int64)pDecodedSamples[-12];
  69823. }
  69824. else if (order == 2)
  69825. {
  69826. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69827. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69828. }
  69829. else if (order == 1)
  69830. {
  69831. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69832. }
  69833. else if (order == 10)
  69834. {
  69835. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69836. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69837. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69838. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69839. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69840. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69841. prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7];
  69842. prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8];
  69843. prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9];
  69844. prediction += coefficients[9] * (ma_int64)pDecodedSamples[-10];
  69845. }
  69846. else if (order == 9)
  69847. {
  69848. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69849. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69850. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69851. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69852. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69853. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69854. prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7];
  69855. prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8];
  69856. prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9];
  69857. }
  69858. else if (order == 11)
  69859. {
  69860. prediction = coefficients[0] * (ma_int64)pDecodedSamples[-1];
  69861. prediction += coefficients[1] * (ma_int64)pDecodedSamples[-2];
  69862. prediction += coefficients[2] * (ma_int64)pDecodedSamples[-3];
  69863. prediction += coefficients[3] * (ma_int64)pDecodedSamples[-4];
  69864. prediction += coefficients[4] * (ma_int64)pDecodedSamples[-5];
  69865. prediction += coefficients[5] * (ma_int64)pDecodedSamples[-6];
  69866. prediction += coefficients[6] * (ma_int64)pDecodedSamples[-7];
  69867. prediction += coefficients[7] * (ma_int64)pDecodedSamples[-8];
  69868. prediction += coefficients[8] * (ma_int64)pDecodedSamples[-9];
  69869. prediction += coefficients[9] * (ma_int64)pDecodedSamples[-10];
  69870. prediction += coefficients[10] * (ma_int64)pDecodedSamples[-11];
  69871. }
  69872. else
  69873. {
  69874. int j;
  69875. prediction = 0;
  69876. for (j = 0; j < (int)order; ++j) {
  69877. prediction += coefficients[j] * (ma_int64)pDecodedSamples[-j-1];
  69878. }
  69879. }
  69880. #endif
  69881. #ifdef MA_64BIT
  69882. prediction = 0;
  69883. switch (order)
  69884. {
  69885. case 32: prediction += coefficients[31] * (ma_int64)pDecodedSamples[-32];
  69886. case 31: prediction += coefficients[30] * (ma_int64)pDecodedSamples[-31];
  69887. case 30: prediction += coefficients[29] * (ma_int64)pDecodedSamples[-30];
  69888. case 29: prediction += coefficients[28] * (ma_int64)pDecodedSamples[-29];
  69889. case 28: prediction += coefficients[27] * (ma_int64)pDecodedSamples[-28];
  69890. case 27: prediction += coefficients[26] * (ma_int64)pDecodedSamples[-27];
  69891. case 26: prediction += coefficients[25] * (ma_int64)pDecodedSamples[-26];
  69892. case 25: prediction += coefficients[24] * (ma_int64)pDecodedSamples[-25];
  69893. case 24: prediction += coefficients[23] * (ma_int64)pDecodedSamples[-24];
  69894. case 23: prediction += coefficients[22] * (ma_int64)pDecodedSamples[-23];
  69895. case 22: prediction += coefficients[21] * (ma_int64)pDecodedSamples[-22];
  69896. case 21: prediction += coefficients[20] * (ma_int64)pDecodedSamples[-21];
  69897. case 20: prediction += coefficients[19] * (ma_int64)pDecodedSamples[-20];
  69898. case 19: prediction += coefficients[18] * (ma_int64)pDecodedSamples[-19];
  69899. case 18: prediction += coefficients[17] * (ma_int64)pDecodedSamples[-18];
  69900. case 17: prediction += coefficients[16] * (ma_int64)pDecodedSamples[-17];
  69901. case 16: prediction += coefficients[15] * (ma_int64)pDecodedSamples[-16];
  69902. case 15: prediction += coefficients[14] * (ma_int64)pDecodedSamples[-15];
  69903. case 14: prediction += coefficients[13] * (ma_int64)pDecodedSamples[-14];
  69904. case 13: prediction += coefficients[12] * (ma_int64)pDecodedSamples[-13];
  69905. case 12: prediction += coefficients[11] * (ma_int64)pDecodedSamples[-12];
  69906. case 11: prediction += coefficients[10] * (ma_int64)pDecodedSamples[-11];
  69907. case 10: prediction += coefficients[ 9] * (ma_int64)pDecodedSamples[-10];
  69908. case 9: prediction += coefficients[ 8] * (ma_int64)pDecodedSamples[- 9];
  69909. case 8: prediction += coefficients[ 7] * (ma_int64)pDecodedSamples[- 8];
  69910. case 7: prediction += coefficients[ 6] * (ma_int64)pDecodedSamples[- 7];
  69911. case 6: prediction += coefficients[ 5] * (ma_int64)pDecodedSamples[- 6];
  69912. case 5: prediction += coefficients[ 4] * (ma_int64)pDecodedSamples[- 5];
  69913. case 4: prediction += coefficients[ 3] * (ma_int64)pDecodedSamples[- 4];
  69914. case 3: prediction += coefficients[ 2] * (ma_int64)pDecodedSamples[- 3];
  69915. case 2: prediction += coefficients[ 1] * (ma_int64)pDecodedSamples[- 2];
  69916. case 1: prediction += coefficients[ 0] * (ma_int64)pDecodedSamples[- 1];
  69917. }
  69918. #endif
  69919. return (ma_int32)(prediction >> shift);
  69920. }
  69921. #if 0
  69922. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__reference(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut)
  69923. {
  69924. ma_uint32 i;
  69925. MA_DR_FLAC_ASSERT(bs != NULL);
  69926. MA_DR_FLAC_ASSERT(pSamplesOut != NULL);
  69927. for (i = 0; i < count; ++i) {
  69928. ma_uint32 zeroCounter = 0;
  69929. for (;;) {
  69930. ma_uint8 bit;
  69931. if (!ma_dr_flac__read_uint8(bs, 1, &bit)) {
  69932. return MA_FALSE;
  69933. }
  69934. if (bit == 0) {
  69935. zeroCounter += 1;
  69936. } else {
  69937. break;
  69938. }
  69939. }
  69940. ma_uint32 decodedRice;
  69941. if (riceParam > 0) {
  69942. if (!ma_dr_flac__read_uint32(bs, riceParam, &decodedRice)) {
  69943. return MA_FALSE;
  69944. }
  69945. } else {
  69946. decodedRice = 0;
  69947. }
  69948. decodedRice |= (zeroCounter << riceParam);
  69949. if ((decodedRice & 0x01)) {
  69950. decodedRice = ~(decodedRice >> 1);
  69951. } else {
  69952. decodedRice = (decodedRice >> 1);
  69953. }
  69954. if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  69955. pSamplesOut[i] = decodedRice + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  69956. } else {
  69957. pSamplesOut[i] = decodedRice + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  69958. }
  69959. }
  69960. return MA_TRUE;
  69961. }
  69962. #endif
  69963. #if 0
  69964. static ma_bool32 ma_dr_flac__read_rice_parts__reference(ma_dr_flac_bs* bs, ma_uint8 riceParam, ma_uint32* pZeroCounterOut, ma_uint32* pRiceParamPartOut)
  69965. {
  69966. ma_uint32 zeroCounter = 0;
  69967. ma_uint32 decodedRice;
  69968. for (;;) {
  69969. ma_uint8 bit;
  69970. if (!ma_dr_flac__read_uint8(bs, 1, &bit)) {
  69971. return MA_FALSE;
  69972. }
  69973. if (bit == 0) {
  69974. zeroCounter += 1;
  69975. } else {
  69976. break;
  69977. }
  69978. }
  69979. if (riceParam > 0) {
  69980. if (!ma_dr_flac__read_uint32(bs, riceParam, &decodedRice)) {
  69981. return MA_FALSE;
  69982. }
  69983. } else {
  69984. decodedRice = 0;
  69985. }
  69986. *pZeroCounterOut = zeroCounter;
  69987. *pRiceParamPartOut = decodedRice;
  69988. return MA_TRUE;
  69989. }
  69990. #endif
  69991. #if 0
  69992. static MA_INLINE ma_bool32 ma_dr_flac__read_rice_parts(ma_dr_flac_bs* bs, ma_uint8 riceParam, ma_uint32* pZeroCounterOut, ma_uint32* pRiceParamPartOut)
  69993. {
  69994. ma_dr_flac_cache_t riceParamMask;
  69995. ma_uint32 zeroCounter;
  69996. ma_uint32 setBitOffsetPlus1;
  69997. ma_uint32 riceParamPart;
  69998. ma_uint32 riceLength;
  69999. MA_DR_FLAC_ASSERT(riceParam > 0);
  70000. riceParamMask = MA_DR_FLAC_CACHE_L1_SELECTION_MASK(riceParam);
  70001. zeroCounter = 0;
  70002. while (bs->cache == 0) {
  70003. zeroCounter += (ma_uint32)MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs);
  70004. if (!ma_dr_flac__reload_cache(bs)) {
  70005. return MA_FALSE;
  70006. }
  70007. }
  70008. setBitOffsetPlus1 = ma_dr_flac__clz(bs->cache);
  70009. zeroCounter += setBitOffsetPlus1;
  70010. setBitOffsetPlus1 += 1;
  70011. riceLength = setBitOffsetPlus1 + riceParam;
  70012. if (riceLength < MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  70013. riceParamPart = (ma_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
  70014. bs->consumedBits += riceLength;
  70015. bs->cache <<= riceLength;
  70016. } else {
  70017. ma_uint32 bitCountLo;
  70018. ma_dr_flac_cache_t resultHi;
  70019. bs->consumedBits += riceLength;
  70020. bs->cache <<= setBitOffsetPlus1 & (MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs)-1);
  70021. bitCountLo = bs->consumedBits - MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs);
  70022. resultHi = MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam);
  70023. if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) {
  70024. #ifndef MA_DR_FLAC_NO_CRC
  70025. ma_dr_flac__update_crc16(bs);
  70026. #endif
  70027. bs->cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70028. bs->consumedBits = 0;
  70029. #ifndef MA_DR_FLAC_NO_CRC
  70030. bs->crc16Cache = bs->cache;
  70031. #endif
  70032. } else {
  70033. if (!ma_dr_flac__reload_cache(bs)) {
  70034. return MA_FALSE;
  70035. }
  70036. if (bitCountLo > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  70037. return MA_FALSE;
  70038. }
  70039. }
  70040. riceParamPart = (ma_uint32)(resultHi | MA_DR_FLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
  70041. bs->consumedBits += bitCountLo;
  70042. bs->cache <<= bitCountLo;
  70043. }
  70044. pZeroCounterOut[0] = zeroCounter;
  70045. pRiceParamPartOut[0] = riceParamPart;
  70046. return MA_TRUE;
  70047. }
  70048. #endif
  70049. static MA_INLINE ma_bool32 ma_dr_flac__read_rice_parts_x1(ma_dr_flac_bs* bs, ma_uint8 riceParam, ma_uint32* pZeroCounterOut, ma_uint32* pRiceParamPartOut)
  70050. {
  70051. ma_uint32 riceParamPlus1 = riceParam + 1;
  70052. ma_uint32 riceParamPlus1Shift = MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
  70053. ma_uint32 riceParamPlus1MaxConsumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  70054. ma_dr_flac_cache_t bs_cache = bs->cache;
  70055. ma_uint32 bs_consumedBits = bs->consumedBits;
  70056. ma_uint32 lzcount = ma_dr_flac__clz(bs_cache);
  70057. if (lzcount < sizeof(bs_cache)*8) {
  70058. pZeroCounterOut[0] = lzcount;
  70059. extract_rice_param_part:
  70060. bs_cache <<= lzcount;
  70061. bs_consumedBits += lzcount;
  70062. if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  70063. pRiceParamPartOut[0] = (ma_uint32)(bs_cache >> riceParamPlus1Shift);
  70064. bs_cache <<= riceParamPlus1;
  70065. bs_consumedBits += riceParamPlus1;
  70066. } else {
  70067. ma_uint32 riceParamPartHi;
  70068. ma_uint32 riceParamPartLo;
  70069. ma_uint32 riceParamPartLoBitCount;
  70070. riceParamPartHi = (ma_uint32)(bs_cache >> riceParamPlus1Shift);
  70071. riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  70072. MA_DR_FLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  70073. if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) {
  70074. #ifndef MA_DR_FLAC_NO_CRC
  70075. ma_dr_flac__update_crc16(bs);
  70076. #endif
  70077. bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70078. bs_consumedBits = riceParamPartLoBitCount;
  70079. #ifndef MA_DR_FLAC_NO_CRC
  70080. bs->crc16Cache = bs_cache;
  70081. #endif
  70082. } else {
  70083. if (!ma_dr_flac__reload_cache(bs)) {
  70084. return MA_FALSE;
  70085. }
  70086. if (riceParamPartLoBitCount > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  70087. return MA_FALSE;
  70088. }
  70089. bs_cache = bs->cache;
  70090. bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  70091. }
  70092. riceParamPartLo = (ma_uint32)(bs_cache >> (MA_DR_FLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
  70093. pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
  70094. bs_cache <<= riceParamPartLoBitCount;
  70095. }
  70096. } else {
  70097. ma_uint32 zeroCounter = (ma_uint32)(MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
  70098. for (;;) {
  70099. if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) {
  70100. #ifndef MA_DR_FLAC_NO_CRC
  70101. ma_dr_flac__update_crc16(bs);
  70102. #endif
  70103. bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70104. bs_consumedBits = 0;
  70105. #ifndef MA_DR_FLAC_NO_CRC
  70106. bs->crc16Cache = bs_cache;
  70107. #endif
  70108. } else {
  70109. if (!ma_dr_flac__reload_cache(bs)) {
  70110. return MA_FALSE;
  70111. }
  70112. bs_cache = bs->cache;
  70113. bs_consumedBits = bs->consumedBits;
  70114. }
  70115. lzcount = ma_dr_flac__clz(bs_cache);
  70116. zeroCounter += lzcount;
  70117. if (lzcount < sizeof(bs_cache)*8) {
  70118. break;
  70119. }
  70120. }
  70121. pZeroCounterOut[0] = zeroCounter;
  70122. goto extract_rice_param_part;
  70123. }
  70124. bs->cache = bs_cache;
  70125. bs->consumedBits = bs_consumedBits;
  70126. return MA_TRUE;
  70127. }
  70128. static MA_INLINE ma_bool32 ma_dr_flac__seek_rice_parts(ma_dr_flac_bs* bs, ma_uint8 riceParam)
  70129. {
  70130. ma_uint32 riceParamPlus1 = riceParam + 1;
  70131. ma_uint32 riceParamPlus1MaxConsumedBits = MA_DR_FLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  70132. ma_dr_flac_cache_t bs_cache = bs->cache;
  70133. ma_uint32 bs_consumedBits = bs->consumedBits;
  70134. ma_uint32 lzcount = ma_dr_flac__clz(bs_cache);
  70135. if (lzcount < sizeof(bs_cache)*8) {
  70136. extract_rice_param_part:
  70137. bs_cache <<= lzcount;
  70138. bs_consumedBits += lzcount;
  70139. if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  70140. bs_cache <<= riceParamPlus1;
  70141. bs_consumedBits += riceParamPlus1;
  70142. } else {
  70143. ma_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  70144. MA_DR_FLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  70145. if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) {
  70146. #ifndef MA_DR_FLAC_NO_CRC
  70147. ma_dr_flac__update_crc16(bs);
  70148. #endif
  70149. bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70150. bs_consumedBits = riceParamPartLoBitCount;
  70151. #ifndef MA_DR_FLAC_NO_CRC
  70152. bs->crc16Cache = bs_cache;
  70153. #endif
  70154. } else {
  70155. if (!ma_dr_flac__reload_cache(bs)) {
  70156. return MA_FALSE;
  70157. }
  70158. if (riceParamPartLoBitCount > MA_DR_FLAC_CACHE_L1_BITS_REMAINING(bs)) {
  70159. return MA_FALSE;
  70160. }
  70161. bs_cache = bs->cache;
  70162. bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  70163. }
  70164. bs_cache <<= riceParamPartLoBitCount;
  70165. }
  70166. } else {
  70167. for (;;) {
  70168. if (bs->nextL2Line < MA_DR_FLAC_CACHE_L2_LINE_COUNT(bs)) {
  70169. #ifndef MA_DR_FLAC_NO_CRC
  70170. ma_dr_flac__update_crc16(bs);
  70171. #endif
  70172. bs_cache = ma_dr_flac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  70173. bs_consumedBits = 0;
  70174. #ifndef MA_DR_FLAC_NO_CRC
  70175. bs->crc16Cache = bs_cache;
  70176. #endif
  70177. } else {
  70178. if (!ma_dr_flac__reload_cache(bs)) {
  70179. return MA_FALSE;
  70180. }
  70181. bs_cache = bs->cache;
  70182. bs_consumedBits = bs->consumedBits;
  70183. }
  70184. lzcount = ma_dr_flac__clz(bs_cache);
  70185. if (lzcount < sizeof(bs_cache)*8) {
  70186. break;
  70187. }
  70188. }
  70189. goto extract_rice_param_part;
  70190. }
  70191. bs->cache = bs_cache;
  70192. bs->consumedBits = bs_consumedBits;
  70193. return MA_TRUE;
  70194. }
  70195. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__scalar_zeroorder(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70196. {
  70197. ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70198. ma_uint32 zeroCountPart0;
  70199. ma_uint32 riceParamPart0;
  70200. ma_uint32 riceParamMask;
  70201. ma_uint32 i;
  70202. MA_DR_FLAC_ASSERT(bs != NULL);
  70203. MA_DR_FLAC_ASSERT(pSamplesOut != NULL);
  70204. (void)bitsPerSample;
  70205. (void)order;
  70206. (void)shift;
  70207. (void)coefficients;
  70208. riceParamMask = (ma_uint32)~((~0UL) << riceParam);
  70209. i = 0;
  70210. while (i < count) {
  70211. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  70212. return MA_FALSE;
  70213. }
  70214. riceParamPart0 &= riceParamMask;
  70215. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70216. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70217. pSamplesOut[i] = riceParamPart0;
  70218. i += 1;
  70219. }
  70220. return MA_TRUE;
  70221. }
  70222. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__scalar(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70223. {
  70224. ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70225. ma_uint32 zeroCountPart0 = 0;
  70226. ma_uint32 zeroCountPart1 = 0;
  70227. ma_uint32 zeroCountPart2 = 0;
  70228. ma_uint32 zeroCountPart3 = 0;
  70229. ma_uint32 riceParamPart0 = 0;
  70230. ma_uint32 riceParamPart1 = 0;
  70231. ma_uint32 riceParamPart2 = 0;
  70232. ma_uint32 riceParamPart3 = 0;
  70233. ma_uint32 riceParamMask;
  70234. const ma_int32* pSamplesOutEnd;
  70235. ma_uint32 i;
  70236. MA_DR_FLAC_ASSERT(bs != NULL);
  70237. MA_DR_FLAC_ASSERT(pSamplesOut != NULL);
  70238. if (lpcOrder == 0) {
  70239. return ma_dr_flac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70240. }
  70241. riceParamMask = (ma_uint32)~((~0UL) << riceParam);
  70242. pSamplesOutEnd = pSamplesOut + (count & ~3);
  70243. if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70244. while (pSamplesOut < pSamplesOutEnd) {
  70245. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  70246. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  70247. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  70248. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  70249. return MA_FALSE;
  70250. }
  70251. riceParamPart0 &= riceParamMask;
  70252. riceParamPart1 &= riceParamMask;
  70253. riceParamPart2 &= riceParamMask;
  70254. riceParamPart3 &= riceParamMask;
  70255. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70256. riceParamPart1 |= (zeroCountPart1 << riceParam);
  70257. riceParamPart2 |= (zeroCountPart2 << riceParam);
  70258. riceParamPart3 |= (zeroCountPart3 << riceParam);
  70259. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70260. riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  70261. riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  70262. riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  70263. pSamplesOut[0] = riceParamPart0 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70264. pSamplesOut[1] = riceParamPart1 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
  70265. pSamplesOut[2] = riceParamPart2 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
  70266. pSamplesOut[3] = riceParamPart3 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
  70267. pSamplesOut += 4;
  70268. }
  70269. } else {
  70270. while (pSamplesOut < pSamplesOutEnd) {
  70271. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  70272. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  70273. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  70274. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  70275. return MA_FALSE;
  70276. }
  70277. riceParamPart0 &= riceParamMask;
  70278. riceParamPart1 &= riceParamMask;
  70279. riceParamPart2 &= riceParamMask;
  70280. riceParamPart3 &= riceParamMask;
  70281. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70282. riceParamPart1 |= (zeroCountPart1 << riceParam);
  70283. riceParamPart2 |= (zeroCountPart2 << riceParam);
  70284. riceParamPart3 |= (zeroCountPart3 << riceParam);
  70285. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70286. riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  70287. riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  70288. riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  70289. pSamplesOut[0] = riceParamPart0 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70290. pSamplesOut[1] = riceParamPart1 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
  70291. pSamplesOut[2] = riceParamPart2 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
  70292. pSamplesOut[3] = riceParamPart3 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
  70293. pSamplesOut += 4;
  70294. }
  70295. }
  70296. i = (count & ~3);
  70297. while (i < count) {
  70298. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  70299. return MA_FALSE;
  70300. }
  70301. riceParamPart0 &= riceParamMask;
  70302. riceParamPart0 |= (zeroCountPart0 << riceParam);
  70303. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  70304. if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70305. pSamplesOut[0] = riceParamPart0 + ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70306. } else {
  70307. pSamplesOut[0] = riceParamPart0 + ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  70308. }
  70309. i += 1;
  70310. pSamplesOut += 1;
  70311. }
  70312. return MA_TRUE;
  70313. }
  70314. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  70315. static MA_INLINE __m128i ma_dr_flac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
  70316. {
  70317. __m128i r;
  70318. r = _mm_packs_epi32(a, b);
  70319. r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
  70320. r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  70321. r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  70322. return r;
  70323. }
  70324. #endif
  70325. #if defined(MA_DR_FLAC_SUPPORT_SSE41)
  70326. static MA_INLINE __m128i ma_dr_flac__mm_not_si128(__m128i a)
  70327. {
  70328. return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
  70329. }
  70330. static MA_INLINE __m128i ma_dr_flac__mm_hadd_epi32(__m128i x)
  70331. {
  70332. __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  70333. __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
  70334. return _mm_add_epi32(x64, x32);
  70335. }
  70336. static MA_INLINE __m128i ma_dr_flac__mm_hadd_epi64(__m128i x)
  70337. {
  70338. return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  70339. }
  70340. static MA_INLINE __m128i ma_dr_flac__mm_srai_epi64(__m128i x, int count)
  70341. {
  70342. __m128i lo = _mm_srli_epi64(x, count);
  70343. __m128i hi = _mm_srai_epi32(x, count);
  70344. hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0));
  70345. return _mm_or_si128(lo, hi);
  70346. }
  70347. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__sse41_32(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70348. {
  70349. int i;
  70350. ma_uint32 riceParamMask;
  70351. ma_int32* pDecodedSamples = pSamplesOut;
  70352. ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70353. ma_uint32 zeroCountParts0 = 0;
  70354. ma_uint32 zeroCountParts1 = 0;
  70355. ma_uint32 zeroCountParts2 = 0;
  70356. ma_uint32 zeroCountParts3 = 0;
  70357. ma_uint32 riceParamParts0 = 0;
  70358. ma_uint32 riceParamParts1 = 0;
  70359. ma_uint32 riceParamParts2 = 0;
  70360. ma_uint32 riceParamParts3 = 0;
  70361. __m128i coefficients128_0;
  70362. __m128i coefficients128_4;
  70363. __m128i coefficients128_8;
  70364. __m128i samples128_0;
  70365. __m128i samples128_4;
  70366. __m128i samples128_8;
  70367. __m128i riceParamMask128;
  70368. const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70369. riceParamMask = (ma_uint32)~((~0UL) << riceParam);
  70370. riceParamMask128 = _mm_set1_epi32(riceParamMask);
  70371. coefficients128_0 = _mm_setzero_si128();
  70372. coefficients128_4 = _mm_setzero_si128();
  70373. coefficients128_8 = _mm_setzero_si128();
  70374. samples128_0 = _mm_setzero_si128();
  70375. samples128_4 = _mm_setzero_si128();
  70376. samples128_8 = _mm_setzero_si128();
  70377. #if 1
  70378. {
  70379. int runningOrder = order;
  70380. if (runningOrder >= 4) {
  70381. coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  70382. samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
  70383. runningOrder -= 4;
  70384. } else {
  70385. switch (runningOrder) {
  70386. 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;
  70387. 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;
  70388. case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
  70389. }
  70390. runningOrder = 0;
  70391. }
  70392. if (runningOrder >= 4) {
  70393. coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  70394. samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
  70395. runningOrder -= 4;
  70396. } else {
  70397. switch (runningOrder) {
  70398. 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;
  70399. 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;
  70400. case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
  70401. }
  70402. runningOrder = 0;
  70403. }
  70404. if (runningOrder == 4) {
  70405. coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  70406. samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
  70407. runningOrder -= 4;
  70408. } else {
  70409. switch (runningOrder) {
  70410. 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;
  70411. 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;
  70412. case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
  70413. }
  70414. runningOrder = 0;
  70415. }
  70416. coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  70417. coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  70418. coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  70419. }
  70420. #else
  70421. switch (order)
  70422. {
  70423. case 12: ((ma_int32*)&coefficients128_8)[0] = coefficients[11]; ((ma_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  70424. case 11: ((ma_int32*)&coefficients128_8)[1] = coefficients[10]; ((ma_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  70425. case 10: ((ma_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((ma_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  70426. case 9: ((ma_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((ma_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  70427. case 8: ((ma_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((ma_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  70428. case 7: ((ma_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((ma_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  70429. case 6: ((ma_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((ma_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  70430. case 5: ((ma_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((ma_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  70431. case 4: ((ma_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((ma_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  70432. case 3: ((ma_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((ma_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  70433. case 2: ((ma_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((ma_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  70434. case 1: ((ma_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((ma_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  70435. }
  70436. #endif
  70437. while (pDecodedSamples < pDecodedSamplesEnd) {
  70438. __m128i prediction128;
  70439. __m128i zeroCountPart128;
  70440. __m128i riceParamPart128;
  70441. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  70442. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  70443. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  70444. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  70445. return MA_FALSE;
  70446. }
  70447. zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  70448. riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  70449. riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  70450. riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  70451. riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(ma_dr_flac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01)));
  70452. if (order <= 4) {
  70453. for (i = 0; i < 4; i += 1) {
  70454. prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
  70455. prediction128 = ma_dr_flac__mm_hadd_epi32(prediction128);
  70456. prediction128 = _mm_srai_epi32(prediction128, shift);
  70457. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70458. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70459. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70460. }
  70461. } else if (order <= 8) {
  70462. for (i = 0; i < 4; i += 1) {
  70463. prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
  70464. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  70465. prediction128 = ma_dr_flac__mm_hadd_epi32(prediction128);
  70466. prediction128 = _mm_srai_epi32(prediction128, shift);
  70467. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70468. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  70469. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70470. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70471. }
  70472. } else {
  70473. for (i = 0; i < 4; i += 1) {
  70474. prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
  70475. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
  70476. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  70477. prediction128 = ma_dr_flac__mm_hadd_epi32(prediction128);
  70478. prediction128 = _mm_srai_epi32(prediction128, shift);
  70479. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70480. samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
  70481. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  70482. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70483. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70484. }
  70485. }
  70486. _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  70487. pDecodedSamples += 4;
  70488. }
  70489. i = (count & ~3);
  70490. while (i < (int)count) {
  70491. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  70492. return MA_FALSE;
  70493. }
  70494. riceParamParts0 &= riceParamMask;
  70495. riceParamParts0 |= (zeroCountParts0 << riceParam);
  70496. riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  70497. pDecodedSamples[0] = riceParamParts0 + ma_dr_flac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  70498. i += 1;
  70499. pDecodedSamples += 1;
  70500. }
  70501. return MA_TRUE;
  70502. }
  70503. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__sse41_64(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70504. {
  70505. int i;
  70506. ma_uint32 riceParamMask;
  70507. ma_int32* pDecodedSamples = pSamplesOut;
  70508. ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70509. ma_uint32 zeroCountParts0 = 0;
  70510. ma_uint32 zeroCountParts1 = 0;
  70511. ma_uint32 zeroCountParts2 = 0;
  70512. ma_uint32 zeroCountParts3 = 0;
  70513. ma_uint32 riceParamParts0 = 0;
  70514. ma_uint32 riceParamParts1 = 0;
  70515. ma_uint32 riceParamParts2 = 0;
  70516. ma_uint32 riceParamParts3 = 0;
  70517. __m128i coefficients128_0;
  70518. __m128i coefficients128_4;
  70519. __m128i coefficients128_8;
  70520. __m128i samples128_0;
  70521. __m128i samples128_4;
  70522. __m128i samples128_8;
  70523. __m128i prediction128;
  70524. __m128i riceParamMask128;
  70525. const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70526. MA_DR_FLAC_ASSERT(order <= 12);
  70527. riceParamMask = (ma_uint32)~((~0UL) << riceParam);
  70528. riceParamMask128 = _mm_set1_epi32(riceParamMask);
  70529. prediction128 = _mm_setzero_si128();
  70530. coefficients128_0 = _mm_setzero_si128();
  70531. coefficients128_4 = _mm_setzero_si128();
  70532. coefficients128_8 = _mm_setzero_si128();
  70533. samples128_0 = _mm_setzero_si128();
  70534. samples128_4 = _mm_setzero_si128();
  70535. samples128_8 = _mm_setzero_si128();
  70536. #if 1
  70537. {
  70538. int runningOrder = order;
  70539. if (runningOrder >= 4) {
  70540. coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  70541. samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
  70542. runningOrder -= 4;
  70543. } else {
  70544. switch (runningOrder) {
  70545. 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;
  70546. 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;
  70547. case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
  70548. }
  70549. runningOrder = 0;
  70550. }
  70551. if (runningOrder >= 4) {
  70552. coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  70553. samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
  70554. runningOrder -= 4;
  70555. } else {
  70556. switch (runningOrder) {
  70557. 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;
  70558. 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;
  70559. case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
  70560. }
  70561. runningOrder = 0;
  70562. }
  70563. if (runningOrder == 4) {
  70564. coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  70565. samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
  70566. runningOrder -= 4;
  70567. } else {
  70568. switch (runningOrder) {
  70569. 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;
  70570. 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;
  70571. case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
  70572. }
  70573. runningOrder = 0;
  70574. }
  70575. coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  70576. coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  70577. coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  70578. }
  70579. #else
  70580. switch (order)
  70581. {
  70582. case 12: ((ma_int32*)&coefficients128_8)[0] = coefficients[11]; ((ma_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  70583. case 11: ((ma_int32*)&coefficients128_8)[1] = coefficients[10]; ((ma_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  70584. case 10: ((ma_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((ma_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  70585. case 9: ((ma_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((ma_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  70586. case 8: ((ma_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((ma_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  70587. case 7: ((ma_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((ma_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  70588. case 6: ((ma_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((ma_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  70589. case 5: ((ma_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((ma_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  70590. case 4: ((ma_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((ma_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  70591. case 3: ((ma_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((ma_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  70592. case 2: ((ma_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((ma_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  70593. case 1: ((ma_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((ma_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  70594. }
  70595. #endif
  70596. while (pDecodedSamples < pDecodedSamplesEnd) {
  70597. __m128i zeroCountPart128;
  70598. __m128i riceParamPart128;
  70599. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  70600. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  70601. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  70602. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  70603. return MA_FALSE;
  70604. }
  70605. zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  70606. riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  70607. riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  70608. riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  70609. riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(ma_dr_flac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(1))), _mm_set1_epi32(1)));
  70610. for (i = 0; i < 4; i += 1) {
  70611. prediction128 = _mm_xor_si128(prediction128, prediction128);
  70612. switch (order)
  70613. {
  70614. case 12:
  70615. 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))));
  70616. case 10:
  70617. 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))));
  70618. case 8:
  70619. 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))));
  70620. case 6:
  70621. 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))));
  70622. case 4:
  70623. 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))));
  70624. case 2:
  70625. 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))));
  70626. }
  70627. prediction128 = ma_dr_flac__mm_hadd_epi64(prediction128);
  70628. prediction128 = ma_dr_flac__mm_srai_epi64(prediction128, shift);
  70629. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  70630. samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
  70631. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  70632. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  70633. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  70634. }
  70635. _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  70636. pDecodedSamples += 4;
  70637. }
  70638. i = (count & ~3);
  70639. while (i < (int)count) {
  70640. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  70641. return MA_FALSE;
  70642. }
  70643. riceParamParts0 &= riceParamMask;
  70644. riceParamParts0 |= (zeroCountParts0 << riceParam);
  70645. riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  70646. pDecodedSamples[0] = riceParamParts0 + ma_dr_flac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  70647. i += 1;
  70648. pDecodedSamples += 1;
  70649. }
  70650. return MA_TRUE;
  70651. }
  70652. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__sse41(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70653. {
  70654. MA_DR_FLAC_ASSERT(bs != NULL);
  70655. MA_DR_FLAC_ASSERT(pSamplesOut != NULL);
  70656. if (lpcOrder > 0 && lpcOrder <= 12) {
  70657. if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  70658. return ma_dr_flac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70659. } else {
  70660. return ma_dr_flac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  70661. }
  70662. } else {
  70663. return ma_dr_flac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  70664. }
  70665. }
  70666. #endif
  70667. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  70668. static MA_INLINE void ma_dr_flac__vst2q_s32(ma_int32* p, int32x4x2_t x)
  70669. {
  70670. vst1q_s32(p+0, x.val[0]);
  70671. vst1q_s32(p+4, x.val[1]);
  70672. }
  70673. static MA_INLINE void ma_dr_flac__vst2q_u32(ma_uint32* p, uint32x4x2_t x)
  70674. {
  70675. vst1q_u32(p+0, x.val[0]);
  70676. vst1q_u32(p+4, x.val[1]);
  70677. }
  70678. static MA_INLINE void ma_dr_flac__vst2q_f32(float* p, float32x4x2_t x)
  70679. {
  70680. vst1q_f32(p+0, x.val[0]);
  70681. vst1q_f32(p+4, x.val[1]);
  70682. }
  70683. static MA_INLINE void ma_dr_flac__vst2q_s16(ma_int16* p, int16x4x2_t x)
  70684. {
  70685. vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
  70686. }
  70687. static MA_INLINE void ma_dr_flac__vst2q_u16(ma_uint16* p, uint16x4x2_t x)
  70688. {
  70689. vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
  70690. }
  70691. static MA_INLINE int32x4_t ma_dr_flac__vdupq_n_s32x4(ma_int32 x3, ma_int32 x2, ma_int32 x1, ma_int32 x0)
  70692. {
  70693. ma_int32 x[4];
  70694. x[3] = x3;
  70695. x[2] = x2;
  70696. x[1] = x1;
  70697. x[0] = x0;
  70698. return vld1q_s32(x);
  70699. }
  70700. static MA_INLINE int32x4_t ma_dr_flac__valignrq_s32_1(int32x4_t a, int32x4_t b)
  70701. {
  70702. return vextq_s32(b, a, 1);
  70703. }
  70704. static MA_INLINE uint32x4_t ma_dr_flac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
  70705. {
  70706. return vextq_u32(b, a, 1);
  70707. }
  70708. static MA_INLINE int32x2_t ma_dr_flac__vhaddq_s32(int32x4_t x)
  70709. {
  70710. int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
  70711. return vpadd_s32(r, r);
  70712. }
  70713. static MA_INLINE int64x1_t ma_dr_flac__vhaddq_s64(int64x2_t x)
  70714. {
  70715. return vadd_s64(vget_high_s64(x), vget_low_s64(x));
  70716. }
  70717. static MA_INLINE int32x4_t ma_dr_flac__vrevq_s32(int32x4_t x)
  70718. {
  70719. return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
  70720. }
  70721. static MA_INLINE int32x4_t ma_dr_flac__vnotq_s32(int32x4_t x)
  70722. {
  70723. return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
  70724. }
  70725. static MA_INLINE uint32x4_t ma_dr_flac__vnotq_u32(uint32x4_t x)
  70726. {
  70727. return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
  70728. }
  70729. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__neon_32(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70730. {
  70731. int i;
  70732. ma_uint32 riceParamMask;
  70733. ma_int32* pDecodedSamples = pSamplesOut;
  70734. ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70735. ma_uint32 zeroCountParts[4];
  70736. ma_uint32 riceParamParts[4];
  70737. int32x4_t coefficients128_0;
  70738. int32x4_t coefficients128_4;
  70739. int32x4_t coefficients128_8;
  70740. int32x4_t samples128_0;
  70741. int32x4_t samples128_4;
  70742. int32x4_t samples128_8;
  70743. uint32x4_t riceParamMask128;
  70744. int32x4_t riceParam128;
  70745. int32x2_t shift64;
  70746. uint32x4_t one128;
  70747. const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70748. riceParamMask = (ma_uint32)~((~0UL) << riceParam);
  70749. riceParamMask128 = vdupq_n_u32(riceParamMask);
  70750. riceParam128 = vdupq_n_s32(riceParam);
  70751. shift64 = vdup_n_s32(-shift);
  70752. one128 = vdupq_n_u32(1);
  70753. {
  70754. int runningOrder = order;
  70755. ma_int32 tempC[4] = {0, 0, 0, 0};
  70756. ma_int32 tempS[4] = {0, 0, 0, 0};
  70757. if (runningOrder >= 4) {
  70758. coefficients128_0 = vld1q_s32(coefficients + 0);
  70759. samples128_0 = vld1q_s32(pSamplesOut - 4);
  70760. runningOrder -= 4;
  70761. } else {
  70762. switch (runningOrder) {
  70763. case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3];
  70764. case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2];
  70765. case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1];
  70766. }
  70767. coefficients128_0 = vld1q_s32(tempC);
  70768. samples128_0 = vld1q_s32(tempS);
  70769. runningOrder = 0;
  70770. }
  70771. if (runningOrder >= 4) {
  70772. coefficients128_4 = vld1q_s32(coefficients + 4);
  70773. samples128_4 = vld1q_s32(pSamplesOut - 8);
  70774. runningOrder -= 4;
  70775. } else {
  70776. switch (runningOrder) {
  70777. case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7];
  70778. case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6];
  70779. case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5];
  70780. }
  70781. coefficients128_4 = vld1q_s32(tempC);
  70782. samples128_4 = vld1q_s32(tempS);
  70783. runningOrder = 0;
  70784. }
  70785. if (runningOrder == 4) {
  70786. coefficients128_8 = vld1q_s32(coefficients + 8);
  70787. samples128_8 = vld1q_s32(pSamplesOut - 12);
  70788. runningOrder -= 4;
  70789. } else {
  70790. switch (runningOrder) {
  70791. case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11];
  70792. case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10];
  70793. case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9];
  70794. }
  70795. coefficients128_8 = vld1q_s32(tempC);
  70796. samples128_8 = vld1q_s32(tempS);
  70797. runningOrder = 0;
  70798. }
  70799. coefficients128_0 = ma_dr_flac__vrevq_s32(coefficients128_0);
  70800. coefficients128_4 = ma_dr_flac__vrevq_s32(coefficients128_4);
  70801. coefficients128_8 = ma_dr_flac__vrevq_s32(coefficients128_8);
  70802. }
  70803. while (pDecodedSamples < pDecodedSamplesEnd) {
  70804. int32x4_t prediction128;
  70805. int32x2_t prediction64;
  70806. uint32x4_t zeroCountPart128;
  70807. uint32x4_t riceParamPart128;
  70808. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  70809. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  70810. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  70811. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  70812. return MA_FALSE;
  70813. }
  70814. zeroCountPart128 = vld1q_u32(zeroCountParts);
  70815. riceParamPart128 = vld1q_u32(riceParamParts);
  70816. riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  70817. riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  70818. riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(ma_dr_flac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  70819. if (order <= 4) {
  70820. for (i = 0; i < 4; i += 1) {
  70821. prediction128 = vmulq_s32(coefficients128_0, samples128_0);
  70822. prediction64 = ma_dr_flac__vhaddq_s32(prediction128);
  70823. prediction64 = vshl_s32(prediction64, shift64);
  70824. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  70825. samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  70826. riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70827. }
  70828. } else if (order <= 8) {
  70829. for (i = 0; i < 4; i += 1) {
  70830. prediction128 = vmulq_s32(coefficients128_4, samples128_4);
  70831. prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  70832. prediction64 = ma_dr_flac__vhaddq_s32(prediction128);
  70833. prediction64 = vshl_s32(prediction64, shift64);
  70834. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  70835. samples128_4 = ma_dr_flac__valignrq_s32_1(samples128_0, samples128_4);
  70836. samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  70837. riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70838. }
  70839. } else {
  70840. for (i = 0; i < 4; i += 1) {
  70841. prediction128 = vmulq_s32(coefficients128_8, samples128_8);
  70842. prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
  70843. prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  70844. prediction64 = ma_dr_flac__vhaddq_s32(prediction128);
  70845. prediction64 = vshl_s32(prediction64, shift64);
  70846. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  70847. samples128_8 = ma_dr_flac__valignrq_s32_1(samples128_4, samples128_8);
  70848. samples128_4 = ma_dr_flac__valignrq_s32_1(samples128_0, samples128_4);
  70849. samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  70850. riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70851. }
  70852. }
  70853. vst1q_s32(pDecodedSamples, samples128_0);
  70854. pDecodedSamples += 4;
  70855. }
  70856. i = (count & ~3);
  70857. while (i < (int)count) {
  70858. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  70859. return MA_FALSE;
  70860. }
  70861. riceParamParts[0] &= riceParamMask;
  70862. riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  70863. riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  70864. pDecodedSamples[0] = riceParamParts[0] + ma_dr_flac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  70865. i += 1;
  70866. pDecodedSamples += 1;
  70867. }
  70868. return MA_TRUE;
  70869. }
  70870. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__neon_64(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam, ma_uint32 order, ma_int32 shift, const ma_int32* coefficients, ma_int32* pSamplesOut)
  70871. {
  70872. int i;
  70873. ma_uint32 riceParamMask;
  70874. ma_int32* pDecodedSamples = pSamplesOut;
  70875. ma_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  70876. ma_uint32 zeroCountParts[4];
  70877. ma_uint32 riceParamParts[4];
  70878. int32x4_t coefficients128_0;
  70879. int32x4_t coefficients128_4;
  70880. int32x4_t coefficients128_8;
  70881. int32x4_t samples128_0;
  70882. int32x4_t samples128_4;
  70883. int32x4_t samples128_8;
  70884. uint32x4_t riceParamMask128;
  70885. int32x4_t riceParam128;
  70886. int64x1_t shift64;
  70887. uint32x4_t one128;
  70888. int64x2_t prediction128 = { 0 };
  70889. uint32x4_t zeroCountPart128;
  70890. uint32x4_t riceParamPart128;
  70891. const ma_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  70892. riceParamMask = (ma_uint32)~((~0UL) << riceParam);
  70893. riceParamMask128 = vdupq_n_u32(riceParamMask);
  70894. riceParam128 = vdupq_n_s32(riceParam);
  70895. shift64 = vdup_n_s64(-shift);
  70896. one128 = vdupq_n_u32(1);
  70897. {
  70898. int runningOrder = order;
  70899. ma_int32 tempC[4] = {0, 0, 0, 0};
  70900. ma_int32 tempS[4] = {0, 0, 0, 0};
  70901. if (runningOrder >= 4) {
  70902. coefficients128_0 = vld1q_s32(coefficients + 0);
  70903. samples128_0 = vld1q_s32(pSamplesOut - 4);
  70904. runningOrder -= 4;
  70905. } else {
  70906. switch (runningOrder) {
  70907. case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3];
  70908. case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2];
  70909. case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1];
  70910. }
  70911. coefficients128_0 = vld1q_s32(tempC);
  70912. samples128_0 = vld1q_s32(tempS);
  70913. runningOrder = 0;
  70914. }
  70915. if (runningOrder >= 4) {
  70916. coefficients128_4 = vld1q_s32(coefficients + 4);
  70917. samples128_4 = vld1q_s32(pSamplesOut - 8);
  70918. runningOrder -= 4;
  70919. } else {
  70920. switch (runningOrder) {
  70921. case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7];
  70922. case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6];
  70923. case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5];
  70924. }
  70925. coefficients128_4 = vld1q_s32(tempC);
  70926. samples128_4 = vld1q_s32(tempS);
  70927. runningOrder = 0;
  70928. }
  70929. if (runningOrder == 4) {
  70930. coefficients128_8 = vld1q_s32(coefficients + 8);
  70931. samples128_8 = vld1q_s32(pSamplesOut - 12);
  70932. runningOrder -= 4;
  70933. } else {
  70934. switch (runningOrder) {
  70935. case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11];
  70936. case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10];
  70937. case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9];
  70938. }
  70939. coefficients128_8 = vld1q_s32(tempC);
  70940. samples128_8 = vld1q_s32(tempS);
  70941. runningOrder = 0;
  70942. }
  70943. coefficients128_0 = ma_dr_flac__vrevq_s32(coefficients128_0);
  70944. coefficients128_4 = ma_dr_flac__vrevq_s32(coefficients128_4);
  70945. coefficients128_8 = ma_dr_flac__vrevq_s32(coefficients128_8);
  70946. }
  70947. while (pDecodedSamples < pDecodedSamplesEnd) {
  70948. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  70949. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  70950. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  70951. !ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  70952. return MA_FALSE;
  70953. }
  70954. zeroCountPart128 = vld1q_u32(zeroCountParts);
  70955. riceParamPart128 = vld1q_u32(riceParamParts);
  70956. riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  70957. riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  70958. riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(ma_dr_flac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  70959. for (i = 0; i < 4; i += 1) {
  70960. int64x1_t prediction64;
  70961. prediction128 = veorq_s64(prediction128, prediction128);
  70962. switch (order)
  70963. {
  70964. case 12:
  70965. case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
  70966. case 10:
  70967. case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
  70968. case 8:
  70969. case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
  70970. case 6:
  70971. case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
  70972. case 4:
  70973. case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
  70974. case 2:
  70975. case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
  70976. }
  70977. prediction64 = ma_dr_flac__vhaddq_s64(prediction128);
  70978. prediction64 = vshl_s64(prediction64, shift64);
  70979. prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
  70980. samples128_8 = ma_dr_flac__valignrq_s32_1(samples128_4, samples128_8);
  70981. samples128_4 = ma_dr_flac__valignrq_s32_1(samples128_0, samples128_4);
  70982. samples128_0 = ma_dr_flac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
  70983. riceParamPart128 = ma_dr_flac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  70984. }
  70985. vst1q_s32(pDecodedSamples, samples128_0);
  70986. pDecodedSamples += 4;
  70987. }
  70988. i = (count & ~3);
  70989. while (i < (int)count) {
  70990. if (!ma_dr_flac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  70991. return MA_FALSE;
  70992. }
  70993. riceParamParts[0] &= riceParamMask;
  70994. riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  70995. riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  70996. pDecodedSamples[0] = riceParamParts[0] + ma_dr_flac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  70997. i += 1;
  70998. pDecodedSamples += 1;
  70999. }
  71000. return MA_TRUE;
  71001. }
  71002. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice__neon(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut)
  71003. {
  71004. MA_DR_FLAC_ASSERT(bs != NULL);
  71005. MA_DR_FLAC_ASSERT(pSamplesOut != NULL);
  71006. if (lpcOrder > 0 && lpcOrder <= 12) {
  71007. if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  71008. return ma_dr_flac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  71009. } else {
  71010. return ma_dr_flac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  71011. }
  71012. } else {
  71013. return ma_dr_flac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  71014. }
  71015. }
  71016. #endif
  71017. static ma_bool32 ma_dr_flac__decode_samples_with_residual__rice(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 riceParam, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut)
  71018. {
  71019. #if defined(MA_DR_FLAC_SUPPORT_SSE41)
  71020. if (ma_dr_flac__gIsSSE41Supported) {
  71021. return ma_dr_flac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  71022. } else
  71023. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  71024. if (ma_dr_flac__gIsNEONSupported) {
  71025. return ma_dr_flac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  71026. } else
  71027. #endif
  71028. {
  71029. #if 0
  71030. return ma_dr_flac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  71031. #else
  71032. return ma_dr_flac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  71033. #endif
  71034. }
  71035. }
  71036. static ma_bool32 ma_dr_flac__read_and_seek_residual__rice(ma_dr_flac_bs* bs, ma_uint32 count, ma_uint8 riceParam)
  71037. {
  71038. ma_uint32 i;
  71039. MA_DR_FLAC_ASSERT(bs != NULL);
  71040. for (i = 0; i < count; ++i) {
  71041. if (!ma_dr_flac__seek_rice_parts(bs, riceParam)) {
  71042. return MA_FALSE;
  71043. }
  71044. }
  71045. return MA_TRUE;
  71046. }
  71047. #if defined(__clang__)
  71048. __attribute__((no_sanitize("signed-integer-overflow")))
  71049. #endif
  71050. static ma_bool32 ma_dr_flac__decode_samples_with_residual__unencoded(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 count, ma_uint8 unencodedBitsPerSample, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pSamplesOut)
  71051. {
  71052. ma_uint32 i;
  71053. MA_DR_FLAC_ASSERT(bs != NULL);
  71054. MA_DR_FLAC_ASSERT(unencodedBitsPerSample <= 31);
  71055. MA_DR_FLAC_ASSERT(pSamplesOut != NULL);
  71056. for (i = 0; i < count; ++i) {
  71057. if (unencodedBitsPerSample > 0) {
  71058. if (!ma_dr_flac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
  71059. return MA_FALSE;
  71060. }
  71061. } else {
  71062. pSamplesOut[i] = 0;
  71063. }
  71064. if (ma_dr_flac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  71065. pSamplesOut[i] += ma_dr_flac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  71066. } else {
  71067. pSamplesOut[i] += ma_dr_flac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  71068. }
  71069. }
  71070. return MA_TRUE;
  71071. }
  71072. static ma_bool32 ma_dr_flac__decode_samples_with_residual(ma_dr_flac_bs* bs, ma_uint32 bitsPerSample, ma_uint32 blockSize, ma_uint32 lpcOrder, ma_int32 lpcShift, ma_uint32 lpcPrecision, const ma_int32* coefficients, ma_int32* pDecodedSamples)
  71073. {
  71074. ma_uint8 residualMethod;
  71075. ma_uint8 partitionOrder;
  71076. ma_uint32 samplesInPartition;
  71077. ma_uint32 partitionsRemaining;
  71078. MA_DR_FLAC_ASSERT(bs != NULL);
  71079. MA_DR_FLAC_ASSERT(blockSize != 0);
  71080. MA_DR_FLAC_ASSERT(pDecodedSamples != NULL);
  71081. if (!ma_dr_flac__read_uint8(bs, 2, &residualMethod)) {
  71082. return MA_FALSE;
  71083. }
  71084. if (residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71085. return MA_FALSE;
  71086. }
  71087. pDecodedSamples += lpcOrder;
  71088. if (!ma_dr_flac__read_uint8(bs, 4, &partitionOrder)) {
  71089. return MA_FALSE;
  71090. }
  71091. if (partitionOrder > 8) {
  71092. return MA_FALSE;
  71093. }
  71094. if ((blockSize / (1 << partitionOrder)) < lpcOrder) {
  71095. return MA_FALSE;
  71096. }
  71097. samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder;
  71098. partitionsRemaining = (1 << partitionOrder);
  71099. for (;;) {
  71100. ma_uint8 riceParam = 0;
  71101. if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  71102. if (!ma_dr_flac__read_uint8(bs, 4, &riceParam)) {
  71103. return MA_FALSE;
  71104. }
  71105. if (riceParam == 15) {
  71106. riceParam = 0xFF;
  71107. }
  71108. } else if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71109. if (!ma_dr_flac__read_uint8(bs, 5, &riceParam)) {
  71110. return MA_FALSE;
  71111. }
  71112. if (riceParam == 31) {
  71113. riceParam = 0xFF;
  71114. }
  71115. }
  71116. if (riceParam != 0xFF) {
  71117. if (!ma_dr_flac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  71118. return MA_FALSE;
  71119. }
  71120. } else {
  71121. ma_uint8 unencodedBitsPerSample = 0;
  71122. if (!ma_dr_flac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  71123. return MA_FALSE;
  71124. }
  71125. if (!ma_dr_flac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  71126. return MA_FALSE;
  71127. }
  71128. }
  71129. pDecodedSamples += samplesInPartition;
  71130. if (partitionsRemaining == 1) {
  71131. break;
  71132. }
  71133. partitionsRemaining -= 1;
  71134. if (partitionOrder != 0) {
  71135. samplesInPartition = blockSize / (1 << partitionOrder);
  71136. }
  71137. }
  71138. return MA_TRUE;
  71139. }
  71140. static ma_bool32 ma_dr_flac__read_and_seek_residual(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 order)
  71141. {
  71142. ma_uint8 residualMethod;
  71143. ma_uint8 partitionOrder;
  71144. ma_uint32 samplesInPartition;
  71145. ma_uint32 partitionsRemaining;
  71146. MA_DR_FLAC_ASSERT(bs != NULL);
  71147. MA_DR_FLAC_ASSERT(blockSize != 0);
  71148. if (!ma_dr_flac__read_uint8(bs, 2, &residualMethod)) {
  71149. return MA_FALSE;
  71150. }
  71151. if (residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71152. return MA_FALSE;
  71153. }
  71154. if (!ma_dr_flac__read_uint8(bs, 4, &partitionOrder)) {
  71155. return MA_FALSE;
  71156. }
  71157. if (partitionOrder > 8) {
  71158. return MA_FALSE;
  71159. }
  71160. if ((blockSize / (1 << partitionOrder)) <= order) {
  71161. return MA_FALSE;
  71162. }
  71163. samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
  71164. partitionsRemaining = (1 << partitionOrder);
  71165. for (;;)
  71166. {
  71167. ma_uint8 riceParam = 0;
  71168. if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  71169. if (!ma_dr_flac__read_uint8(bs, 4, &riceParam)) {
  71170. return MA_FALSE;
  71171. }
  71172. if (riceParam == 15) {
  71173. riceParam = 0xFF;
  71174. }
  71175. } else if (residualMethod == MA_DR_FLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  71176. if (!ma_dr_flac__read_uint8(bs, 5, &riceParam)) {
  71177. return MA_FALSE;
  71178. }
  71179. if (riceParam == 31) {
  71180. riceParam = 0xFF;
  71181. }
  71182. }
  71183. if (riceParam != 0xFF) {
  71184. if (!ma_dr_flac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
  71185. return MA_FALSE;
  71186. }
  71187. } else {
  71188. ma_uint8 unencodedBitsPerSample = 0;
  71189. if (!ma_dr_flac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  71190. return MA_FALSE;
  71191. }
  71192. if (!ma_dr_flac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
  71193. return MA_FALSE;
  71194. }
  71195. }
  71196. if (partitionsRemaining == 1) {
  71197. break;
  71198. }
  71199. partitionsRemaining -= 1;
  71200. samplesInPartition = blockSize / (1 << partitionOrder);
  71201. }
  71202. return MA_TRUE;
  71203. }
  71204. static ma_bool32 ma_dr_flac__decode_samples__constant(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 subframeBitsPerSample, ma_int32* pDecodedSamples)
  71205. {
  71206. ma_uint32 i;
  71207. ma_int32 sample;
  71208. if (!ma_dr_flac__read_int32(bs, subframeBitsPerSample, &sample)) {
  71209. return MA_FALSE;
  71210. }
  71211. for (i = 0; i < blockSize; ++i) {
  71212. pDecodedSamples[i] = sample;
  71213. }
  71214. return MA_TRUE;
  71215. }
  71216. static ma_bool32 ma_dr_flac__decode_samples__verbatim(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 subframeBitsPerSample, ma_int32* pDecodedSamples)
  71217. {
  71218. ma_uint32 i;
  71219. for (i = 0; i < blockSize; ++i) {
  71220. ma_int32 sample;
  71221. if (!ma_dr_flac__read_int32(bs, subframeBitsPerSample, &sample)) {
  71222. return MA_FALSE;
  71223. }
  71224. pDecodedSamples[i] = sample;
  71225. }
  71226. return MA_TRUE;
  71227. }
  71228. static ma_bool32 ma_dr_flac__decode_samples__fixed(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 subframeBitsPerSample, ma_uint8 lpcOrder, ma_int32* pDecodedSamples)
  71229. {
  71230. ma_uint32 i;
  71231. static ma_int32 lpcCoefficientsTable[5][4] = {
  71232. {0, 0, 0, 0},
  71233. {1, 0, 0, 0},
  71234. {2, -1, 0, 0},
  71235. {3, -3, 1, 0},
  71236. {4, -6, 4, -1}
  71237. };
  71238. for (i = 0; i < lpcOrder; ++i) {
  71239. ma_int32 sample;
  71240. if (!ma_dr_flac__read_int32(bs, subframeBitsPerSample, &sample)) {
  71241. return MA_FALSE;
  71242. }
  71243. pDecodedSamples[i] = sample;
  71244. }
  71245. if (!ma_dr_flac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
  71246. return MA_FALSE;
  71247. }
  71248. return MA_TRUE;
  71249. }
  71250. static ma_bool32 ma_dr_flac__decode_samples__lpc(ma_dr_flac_bs* bs, ma_uint32 blockSize, ma_uint32 bitsPerSample, ma_uint8 lpcOrder, ma_int32* pDecodedSamples)
  71251. {
  71252. ma_uint8 i;
  71253. ma_uint8 lpcPrecision;
  71254. ma_int8 lpcShift;
  71255. ma_int32 coefficients[32];
  71256. for (i = 0; i < lpcOrder; ++i) {
  71257. ma_int32 sample;
  71258. if (!ma_dr_flac__read_int32(bs, bitsPerSample, &sample)) {
  71259. return MA_FALSE;
  71260. }
  71261. pDecodedSamples[i] = sample;
  71262. }
  71263. if (!ma_dr_flac__read_uint8(bs, 4, &lpcPrecision)) {
  71264. return MA_FALSE;
  71265. }
  71266. if (lpcPrecision == 15) {
  71267. return MA_FALSE;
  71268. }
  71269. lpcPrecision += 1;
  71270. if (!ma_dr_flac__read_int8(bs, 5, &lpcShift)) {
  71271. return MA_FALSE;
  71272. }
  71273. if (lpcShift < 0) {
  71274. return MA_FALSE;
  71275. }
  71276. MA_DR_FLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
  71277. for (i = 0; i < lpcOrder; ++i) {
  71278. if (!ma_dr_flac__read_int32(bs, lpcPrecision, coefficients + i)) {
  71279. return MA_FALSE;
  71280. }
  71281. }
  71282. if (!ma_dr_flac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  71283. return MA_FALSE;
  71284. }
  71285. return MA_TRUE;
  71286. }
  71287. static ma_bool32 ma_dr_flac__read_next_flac_frame_header(ma_dr_flac_bs* bs, ma_uint8 streaminfoBitsPerSample, ma_dr_flac_frame_header* header)
  71288. {
  71289. const ma_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
  71290. const ma_uint8 bitsPerSampleTable[8] = {0, 8, 12, (ma_uint8)-1, 16, 20, 24, (ma_uint8)-1};
  71291. MA_DR_FLAC_ASSERT(bs != NULL);
  71292. MA_DR_FLAC_ASSERT(header != NULL);
  71293. for (;;) {
  71294. ma_uint8 crc8 = 0xCE;
  71295. ma_uint8 reserved = 0;
  71296. ma_uint8 blockingStrategy = 0;
  71297. ma_uint8 blockSize = 0;
  71298. ma_uint8 sampleRate = 0;
  71299. ma_uint8 channelAssignment = 0;
  71300. ma_uint8 bitsPerSample = 0;
  71301. ma_bool32 isVariableBlockSize;
  71302. if (!ma_dr_flac__find_and_seek_to_next_sync_code(bs)) {
  71303. return MA_FALSE;
  71304. }
  71305. if (!ma_dr_flac__read_uint8(bs, 1, &reserved)) {
  71306. return MA_FALSE;
  71307. }
  71308. if (reserved == 1) {
  71309. continue;
  71310. }
  71311. crc8 = ma_dr_flac_crc8(crc8, reserved, 1);
  71312. if (!ma_dr_flac__read_uint8(bs, 1, &blockingStrategy)) {
  71313. return MA_FALSE;
  71314. }
  71315. crc8 = ma_dr_flac_crc8(crc8, blockingStrategy, 1);
  71316. if (!ma_dr_flac__read_uint8(bs, 4, &blockSize)) {
  71317. return MA_FALSE;
  71318. }
  71319. if (blockSize == 0) {
  71320. continue;
  71321. }
  71322. crc8 = ma_dr_flac_crc8(crc8, blockSize, 4);
  71323. if (!ma_dr_flac__read_uint8(bs, 4, &sampleRate)) {
  71324. return MA_FALSE;
  71325. }
  71326. crc8 = ma_dr_flac_crc8(crc8, sampleRate, 4);
  71327. if (!ma_dr_flac__read_uint8(bs, 4, &channelAssignment)) {
  71328. return MA_FALSE;
  71329. }
  71330. if (channelAssignment > 10) {
  71331. continue;
  71332. }
  71333. crc8 = ma_dr_flac_crc8(crc8, channelAssignment, 4);
  71334. if (!ma_dr_flac__read_uint8(bs, 3, &bitsPerSample)) {
  71335. return MA_FALSE;
  71336. }
  71337. if (bitsPerSample == 3 || bitsPerSample == 7) {
  71338. continue;
  71339. }
  71340. crc8 = ma_dr_flac_crc8(crc8, bitsPerSample, 3);
  71341. if (!ma_dr_flac__read_uint8(bs, 1, &reserved)) {
  71342. return MA_FALSE;
  71343. }
  71344. if (reserved == 1) {
  71345. continue;
  71346. }
  71347. crc8 = ma_dr_flac_crc8(crc8, reserved, 1);
  71348. isVariableBlockSize = blockingStrategy == 1;
  71349. if (isVariableBlockSize) {
  71350. ma_uint64 pcmFrameNumber;
  71351. ma_result result = ma_dr_flac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
  71352. if (result != MA_SUCCESS) {
  71353. if (result == MA_AT_END) {
  71354. return MA_FALSE;
  71355. } else {
  71356. continue;
  71357. }
  71358. }
  71359. header->flacFrameNumber = 0;
  71360. header->pcmFrameNumber = pcmFrameNumber;
  71361. } else {
  71362. ma_uint64 flacFrameNumber = 0;
  71363. ma_result result = ma_dr_flac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
  71364. if (result != MA_SUCCESS) {
  71365. if (result == MA_AT_END) {
  71366. return MA_FALSE;
  71367. } else {
  71368. continue;
  71369. }
  71370. }
  71371. header->flacFrameNumber = (ma_uint32)flacFrameNumber;
  71372. header->pcmFrameNumber = 0;
  71373. }
  71374. MA_DR_FLAC_ASSERT(blockSize > 0);
  71375. if (blockSize == 1) {
  71376. header->blockSizeInPCMFrames = 192;
  71377. } else if (blockSize <= 5) {
  71378. MA_DR_FLAC_ASSERT(blockSize >= 2);
  71379. header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
  71380. } else if (blockSize == 6) {
  71381. if (!ma_dr_flac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
  71382. return MA_FALSE;
  71383. }
  71384. crc8 = ma_dr_flac_crc8(crc8, header->blockSizeInPCMFrames, 8);
  71385. header->blockSizeInPCMFrames += 1;
  71386. } else if (blockSize == 7) {
  71387. if (!ma_dr_flac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
  71388. return MA_FALSE;
  71389. }
  71390. crc8 = ma_dr_flac_crc8(crc8, header->blockSizeInPCMFrames, 16);
  71391. if (header->blockSizeInPCMFrames == 0xFFFF) {
  71392. return MA_FALSE;
  71393. }
  71394. header->blockSizeInPCMFrames += 1;
  71395. } else {
  71396. MA_DR_FLAC_ASSERT(blockSize >= 8);
  71397. header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
  71398. }
  71399. if (sampleRate <= 11) {
  71400. header->sampleRate = sampleRateTable[sampleRate];
  71401. } else if (sampleRate == 12) {
  71402. if (!ma_dr_flac__read_uint32(bs, 8, &header->sampleRate)) {
  71403. return MA_FALSE;
  71404. }
  71405. crc8 = ma_dr_flac_crc8(crc8, header->sampleRate, 8);
  71406. header->sampleRate *= 1000;
  71407. } else if (sampleRate == 13) {
  71408. if (!ma_dr_flac__read_uint32(bs, 16, &header->sampleRate)) {
  71409. return MA_FALSE;
  71410. }
  71411. crc8 = ma_dr_flac_crc8(crc8, header->sampleRate, 16);
  71412. } else if (sampleRate == 14) {
  71413. if (!ma_dr_flac__read_uint32(bs, 16, &header->sampleRate)) {
  71414. return MA_FALSE;
  71415. }
  71416. crc8 = ma_dr_flac_crc8(crc8, header->sampleRate, 16);
  71417. header->sampleRate *= 10;
  71418. } else {
  71419. continue;
  71420. }
  71421. header->channelAssignment = channelAssignment;
  71422. header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
  71423. if (header->bitsPerSample == 0) {
  71424. header->bitsPerSample = streaminfoBitsPerSample;
  71425. }
  71426. if (header->bitsPerSample != streaminfoBitsPerSample) {
  71427. return MA_FALSE;
  71428. }
  71429. if (!ma_dr_flac__read_uint8(bs, 8, &header->crc8)) {
  71430. return MA_FALSE;
  71431. }
  71432. #ifndef MA_DR_FLAC_NO_CRC
  71433. if (header->crc8 != crc8) {
  71434. continue;
  71435. }
  71436. #endif
  71437. return MA_TRUE;
  71438. }
  71439. }
  71440. static ma_bool32 ma_dr_flac__read_subframe_header(ma_dr_flac_bs* bs, ma_dr_flac_subframe* pSubframe)
  71441. {
  71442. ma_uint8 header;
  71443. int type;
  71444. if (!ma_dr_flac__read_uint8(bs, 8, &header)) {
  71445. return MA_FALSE;
  71446. }
  71447. if ((header & 0x80) != 0) {
  71448. return MA_FALSE;
  71449. }
  71450. type = (header & 0x7E) >> 1;
  71451. if (type == 0) {
  71452. pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_CONSTANT;
  71453. } else if (type == 1) {
  71454. pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_VERBATIM;
  71455. } else {
  71456. if ((type & 0x20) != 0) {
  71457. pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_LPC;
  71458. pSubframe->lpcOrder = (ma_uint8)(type & 0x1F) + 1;
  71459. } else if ((type & 0x08) != 0) {
  71460. pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_FIXED;
  71461. pSubframe->lpcOrder = (ma_uint8)(type & 0x07);
  71462. if (pSubframe->lpcOrder > 4) {
  71463. pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_RESERVED;
  71464. pSubframe->lpcOrder = 0;
  71465. }
  71466. } else {
  71467. pSubframe->subframeType = MA_DR_FLAC_SUBFRAME_RESERVED;
  71468. }
  71469. }
  71470. if (pSubframe->subframeType == MA_DR_FLAC_SUBFRAME_RESERVED) {
  71471. return MA_FALSE;
  71472. }
  71473. pSubframe->wastedBitsPerSample = 0;
  71474. if ((header & 0x01) == 1) {
  71475. unsigned int wastedBitsPerSample;
  71476. if (!ma_dr_flac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
  71477. return MA_FALSE;
  71478. }
  71479. pSubframe->wastedBitsPerSample = (ma_uint8)wastedBitsPerSample + 1;
  71480. }
  71481. return MA_TRUE;
  71482. }
  71483. static ma_bool32 ma_dr_flac__decode_subframe(ma_dr_flac_bs* bs, ma_dr_flac_frame* frame, int subframeIndex, ma_int32* pDecodedSamplesOut)
  71484. {
  71485. ma_dr_flac_subframe* pSubframe;
  71486. ma_uint32 subframeBitsPerSample;
  71487. MA_DR_FLAC_ASSERT(bs != NULL);
  71488. MA_DR_FLAC_ASSERT(frame != NULL);
  71489. pSubframe = frame->subframes + subframeIndex;
  71490. if (!ma_dr_flac__read_subframe_header(bs, pSubframe)) {
  71491. return MA_FALSE;
  71492. }
  71493. subframeBitsPerSample = frame->header.bitsPerSample;
  71494. if ((frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  71495. subframeBitsPerSample += 1;
  71496. } else if (frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  71497. subframeBitsPerSample += 1;
  71498. }
  71499. if (subframeBitsPerSample > 32) {
  71500. return MA_FALSE;
  71501. }
  71502. if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  71503. return MA_FALSE;
  71504. }
  71505. subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  71506. pSubframe->pSamplesS32 = pDecodedSamplesOut;
  71507. switch (pSubframe->subframeType)
  71508. {
  71509. case MA_DR_FLAC_SUBFRAME_CONSTANT:
  71510. {
  71511. ma_dr_flac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  71512. } break;
  71513. case MA_DR_FLAC_SUBFRAME_VERBATIM:
  71514. {
  71515. ma_dr_flac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  71516. } break;
  71517. case MA_DR_FLAC_SUBFRAME_FIXED:
  71518. {
  71519. ma_dr_flac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  71520. } break;
  71521. case MA_DR_FLAC_SUBFRAME_LPC:
  71522. {
  71523. ma_dr_flac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  71524. } break;
  71525. default: return MA_FALSE;
  71526. }
  71527. return MA_TRUE;
  71528. }
  71529. static ma_bool32 ma_dr_flac__seek_subframe(ma_dr_flac_bs* bs, ma_dr_flac_frame* frame, int subframeIndex)
  71530. {
  71531. ma_dr_flac_subframe* pSubframe;
  71532. ma_uint32 subframeBitsPerSample;
  71533. MA_DR_FLAC_ASSERT(bs != NULL);
  71534. MA_DR_FLAC_ASSERT(frame != NULL);
  71535. pSubframe = frame->subframes + subframeIndex;
  71536. if (!ma_dr_flac__read_subframe_header(bs, pSubframe)) {
  71537. return MA_FALSE;
  71538. }
  71539. subframeBitsPerSample = frame->header.bitsPerSample;
  71540. if ((frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  71541. subframeBitsPerSample += 1;
  71542. } else if (frame->header.channelAssignment == MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  71543. subframeBitsPerSample += 1;
  71544. }
  71545. if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  71546. return MA_FALSE;
  71547. }
  71548. subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  71549. pSubframe->pSamplesS32 = NULL;
  71550. switch (pSubframe->subframeType)
  71551. {
  71552. case MA_DR_FLAC_SUBFRAME_CONSTANT:
  71553. {
  71554. if (!ma_dr_flac__seek_bits(bs, subframeBitsPerSample)) {
  71555. return MA_FALSE;
  71556. }
  71557. } break;
  71558. case MA_DR_FLAC_SUBFRAME_VERBATIM:
  71559. {
  71560. unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
  71561. if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) {
  71562. return MA_FALSE;
  71563. }
  71564. } break;
  71565. case MA_DR_FLAC_SUBFRAME_FIXED:
  71566. {
  71567. unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  71568. if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) {
  71569. return MA_FALSE;
  71570. }
  71571. if (!ma_dr_flac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  71572. return MA_FALSE;
  71573. }
  71574. } break;
  71575. case MA_DR_FLAC_SUBFRAME_LPC:
  71576. {
  71577. ma_uint8 lpcPrecision;
  71578. unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  71579. if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) {
  71580. return MA_FALSE;
  71581. }
  71582. if (!ma_dr_flac__read_uint8(bs, 4, &lpcPrecision)) {
  71583. return MA_FALSE;
  71584. }
  71585. if (lpcPrecision == 15) {
  71586. return MA_FALSE;
  71587. }
  71588. lpcPrecision += 1;
  71589. bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5;
  71590. if (!ma_dr_flac__seek_bits(bs, bitsToSeek)) {
  71591. return MA_FALSE;
  71592. }
  71593. if (!ma_dr_flac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  71594. return MA_FALSE;
  71595. }
  71596. } break;
  71597. default: return MA_FALSE;
  71598. }
  71599. return MA_TRUE;
  71600. }
  71601. static MA_INLINE ma_uint8 ma_dr_flac__get_channel_count_from_channel_assignment(ma_int8 channelAssignment)
  71602. {
  71603. ma_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
  71604. MA_DR_FLAC_ASSERT(channelAssignment <= 10);
  71605. return lookup[channelAssignment];
  71606. }
  71607. static ma_result ma_dr_flac__decode_flac_frame(ma_dr_flac* pFlac)
  71608. {
  71609. int channelCount;
  71610. int i;
  71611. ma_uint8 paddingSizeInBits;
  71612. ma_uint16 desiredCRC16;
  71613. #ifndef MA_DR_FLAC_NO_CRC
  71614. ma_uint16 actualCRC16;
  71615. #endif
  71616. MA_DR_FLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
  71617. if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
  71618. return MA_ERROR;
  71619. }
  71620. channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  71621. if (channelCount != (int)pFlac->channels) {
  71622. return MA_ERROR;
  71623. }
  71624. for (i = 0; i < channelCount; ++i) {
  71625. if (!ma_dr_flac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
  71626. return MA_ERROR;
  71627. }
  71628. }
  71629. paddingSizeInBits = (ma_uint8)(MA_DR_FLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
  71630. if (paddingSizeInBits > 0) {
  71631. ma_uint8 padding = 0;
  71632. if (!ma_dr_flac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
  71633. return MA_AT_END;
  71634. }
  71635. }
  71636. #ifndef MA_DR_FLAC_NO_CRC
  71637. actualCRC16 = ma_dr_flac__flush_crc16(&pFlac->bs);
  71638. #endif
  71639. if (!ma_dr_flac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  71640. return MA_AT_END;
  71641. }
  71642. #ifndef MA_DR_FLAC_NO_CRC
  71643. if (actualCRC16 != desiredCRC16) {
  71644. return MA_CRC_MISMATCH;
  71645. }
  71646. #endif
  71647. pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  71648. return MA_SUCCESS;
  71649. }
  71650. static ma_result ma_dr_flac__seek_flac_frame(ma_dr_flac* pFlac)
  71651. {
  71652. int channelCount;
  71653. int i;
  71654. ma_uint16 desiredCRC16;
  71655. #ifndef MA_DR_FLAC_NO_CRC
  71656. ma_uint16 actualCRC16;
  71657. #endif
  71658. channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  71659. for (i = 0; i < channelCount; ++i) {
  71660. if (!ma_dr_flac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
  71661. return MA_ERROR;
  71662. }
  71663. }
  71664. if (!ma_dr_flac__seek_bits(&pFlac->bs, MA_DR_FLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
  71665. return MA_ERROR;
  71666. }
  71667. #ifndef MA_DR_FLAC_NO_CRC
  71668. actualCRC16 = ma_dr_flac__flush_crc16(&pFlac->bs);
  71669. #endif
  71670. if (!ma_dr_flac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  71671. return MA_AT_END;
  71672. }
  71673. #ifndef MA_DR_FLAC_NO_CRC
  71674. if (actualCRC16 != desiredCRC16) {
  71675. return MA_CRC_MISMATCH;
  71676. }
  71677. #endif
  71678. return MA_SUCCESS;
  71679. }
  71680. static ma_bool32 ma_dr_flac__read_and_decode_next_flac_frame(ma_dr_flac* pFlac)
  71681. {
  71682. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71683. for (;;) {
  71684. ma_result result;
  71685. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71686. return MA_FALSE;
  71687. }
  71688. result = ma_dr_flac__decode_flac_frame(pFlac);
  71689. if (result != MA_SUCCESS) {
  71690. if (result == MA_CRC_MISMATCH) {
  71691. continue;
  71692. } else {
  71693. return MA_FALSE;
  71694. }
  71695. }
  71696. return MA_TRUE;
  71697. }
  71698. }
  71699. static void ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(ma_dr_flac* pFlac, ma_uint64* pFirstPCMFrame, ma_uint64* pLastPCMFrame)
  71700. {
  71701. ma_uint64 firstPCMFrame;
  71702. ma_uint64 lastPCMFrame;
  71703. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71704. firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
  71705. if (firstPCMFrame == 0) {
  71706. firstPCMFrame = ((ma_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
  71707. }
  71708. lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  71709. if (lastPCMFrame > 0) {
  71710. lastPCMFrame -= 1;
  71711. }
  71712. if (pFirstPCMFrame) {
  71713. *pFirstPCMFrame = firstPCMFrame;
  71714. }
  71715. if (pLastPCMFrame) {
  71716. *pLastPCMFrame = lastPCMFrame;
  71717. }
  71718. }
  71719. static ma_bool32 ma_dr_flac__seek_to_first_frame(ma_dr_flac* pFlac)
  71720. {
  71721. ma_bool32 result;
  71722. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71723. result = ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
  71724. MA_DR_FLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  71725. pFlac->currentPCMFrame = 0;
  71726. return result;
  71727. }
  71728. static MA_INLINE ma_result ma_dr_flac__seek_to_next_flac_frame(ma_dr_flac* pFlac)
  71729. {
  71730. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71731. return ma_dr_flac__seek_flac_frame(pFlac);
  71732. }
  71733. static ma_uint64 ma_dr_flac__seek_forward_by_pcm_frames(ma_dr_flac* pFlac, ma_uint64 pcmFramesToSeek)
  71734. {
  71735. ma_uint64 pcmFramesRead = 0;
  71736. while (pcmFramesToSeek > 0) {
  71737. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  71738. if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) {
  71739. break;
  71740. }
  71741. } else {
  71742. if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
  71743. pcmFramesRead += pcmFramesToSeek;
  71744. pFlac->currentFLACFrame.pcmFramesRemaining -= (ma_uint32)pcmFramesToSeek;
  71745. pcmFramesToSeek = 0;
  71746. } else {
  71747. pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
  71748. pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
  71749. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  71750. }
  71751. }
  71752. }
  71753. pFlac->currentPCMFrame += pcmFramesRead;
  71754. return pcmFramesRead;
  71755. }
  71756. static ma_bool32 ma_dr_flac__seek_to_pcm_frame__brute_force(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex)
  71757. {
  71758. ma_bool32 isMidFrame = MA_FALSE;
  71759. ma_uint64 runningPCMFrameCount;
  71760. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71761. if (pcmFrameIndex >= pFlac->currentPCMFrame) {
  71762. runningPCMFrameCount = pFlac->currentPCMFrame;
  71763. if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  71764. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71765. return MA_FALSE;
  71766. }
  71767. } else {
  71768. isMidFrame = MA_TRUE;
  71769. }
  71770. } else {
  71771. runningPCMFrameCount = 0;
  71772. if (!ma_dr_flac__seek_to_first_frame(pFlac)) {
  71773. return MA_FALSE;
  71774. }
  71775. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71776. return MA_FALSE;
  71777. }
  71778. }
  71779. for (;;) {
  71780. ma_uint64 pcmFrameCountInThisFLACFrame;
  71781. ma_uint64 firstPCMFrameInFLACFrame = 0;
  71782. ma_uint64 lastPCMFrameInFLACFrame = 0;
  71783. ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  71784. pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  71785. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  71786. ma_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  71787. if (!isMidFrame) {
  71788. ma_result result = ma_dr_flac__decode_flac_frame(pFlac);
  71789. if (result == MA_SUCCESS) {
  71790. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71791. } else {
  71792. if (result == MA_CRC_MISMATCH) {
  71793. goto next_iteration;
  71794. } else {
  71795. return MA_FALSE;
  71796. }
  71797. }
  71798. } else {
  71799. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71800. }
  71801. } else {
  71802. if (!isMidFrame) {
  71803. ma_result result = ma_dr_flac__seek_to_next_flac_frame(pFlac);
  71804. if (result == MA_SUCCESS) {
  71805. runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  71806. } else {
  71807. if (result == MA_CRC_MISMATCH) {
  71808. goto next_iteration;
  71809. } else {
  71810. return MA_FALSE;
  71811. }
  71812. }
  71813. } else {
  71814. runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  71815. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  71816. isMidFrame = MA_FALSE;
  71817. }
  71818. if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  71819. return MA_TRUE;
  71820. }
  71821. }
  71822. next_iteration:
  71823. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71824. return MA_FALSE;
  71825. }
  71826. }
  71827. }
  71828. #if !defined(MA_DR_FLAC_NO_CRC)
  71829. #define MA_DR_FLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
  71830. static ma_bool32 ma_dr_flac__seek_to_approximate_flac_frame_to_byte(ma_dr_flac* pFlac, ma_uint64 targetByte, ma_uint64 rangeLo, ma_uint64 rangeHi, ma_uint64* pLastSuccessfulSeekOffset)
  71831. {
  71832. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71833. MA_DR_FLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
  71834. MA_DR_FLAC_ASSERT(targetByte >= rangeLo);
  71835. MA_DR_FLAC_ASSERT(targetByte <= rangeHi);
  71836. *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
  71837. for (;;) {
  71838. ma_uint64 lastTargetByte = targetByte;
  71839. if (!ma_dr_flac__seek_to_byte(&pFlac->bs, targetByte)) {
  71840. if (targetByte == 0) {
  71841. ma_dr_flac__seek_to_first_frame(pFlac);
  71842. return MA_FALSE;
  71843. }
  71844. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  71845. rangeHi = targetByte;
  71846. } else {
  71847. MA_DR_FLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  71848. #if 1
  71849. if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) {
  71850. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  71851. rangeHi = targetByte;
  71852. } else {
  71853. break;
  71854. }
  71855. #else
  71856. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71857. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  71858. rangeHi = targetByte;
  71859. } else {
  71860. break;
  71861. }
  71862. #endif
  71863. }
  71864. if(targetByte == lastTargetByte) {
  71865. return MA_FALSE;
  71866. }
  71867. }
  71868. ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  71869. MA_DR_FLAC_ASSERT(targetByte <= rangeHi);
  71870. *pLastSuccessfulSeekOffset = targetByte;
  71871. return MA_TRUE;
  71872. }
  71873. static ma_bool32 ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(ma_dr_flac* pFlac, ma_uint64 offset)
  71874. {
  71875. #if 0
  71876. if (ma_dr_flac__decode_flac_frame(pFlac) != MA_SUCCESS) {
  71877. if (ma_dr_flac__read_and_decode_next_flac_frame(pFlac) == MA_FALSE) {
  71878. return MA_FALSE;
  71879. }
  71880. }
  71881. #endif
  71882. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
  71883. }
  71884. static ma_bool32 ma_dr_flac__seek_to_pcm_frame__binary_search_internal(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex, ma_uint64 byteRangeLo, ma_uint64 byteRangeHi)
  71885. {
  71886. ma_uint64 targetByte;
  71887. ma_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
  71888. ma_uint64 pcmRangeHi = 0;
  71889. ma_uint64 lastSuccessfulSeekOffset = (ma_uint64)-1;
  71890. ma_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
  71891. ma_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  71892. targetByte = byteRangeLo + (ma_uint64)(((ma_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * MA_DR_FLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
  71893. if (targetByte > byteRangeHi) {
  71894. targetByte = byteRangeHi;
  71895. }
  71896. for (;;) {
  71897. if (ma_dr_flac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
  71898. ma_uint64 newPCMRangeLo;
  71899. ma_uint64 newPCMRangeHi;
  71900. ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
  71901. if (pcmRangeLo == newPCMRangeLo) {
  71902. if (!ma_dr_flac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
  71903. break;
  71904. }
  71905. if (ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  71906. return MA_TRUE;
  71907. } else {
  71908. break;
  71909. }
  71910. }
  71911. pcmRangeLo = newPCMRangeLo;
  71912. pcmRangeHi = newPCMRangeHi;
  71913. if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
  71914. if (ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
  71915. return MA_TRUE;
  71916. } else {
  71917. break;
  71918. }
  71919. } else {
  71920. const float approxCompressionRatio = (ma_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((ma_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  71921. if (pcmRangeLo > pcmFrameIndex) {
  71922. byteRangeHi = lastSuccessfulSeekOffset;
  71923. if (byteRangeLo > byteRangeHi) {
  71924. byteRangeLo = byteRangeHi;
  71925. }
  71926. targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
  71927. if (targetByte < byteRangeLo) {
  71928. targetByte = byteRangeLo;
  71929. }
  71930. } else {
  71931. if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
  71932. if (ma_dr_flac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  71933. return MA_TRUE;
  71934. } else {
  71935. break;
  71936. }
  71937. } else {
  71938. byteRangeLo = lastSuccessfulSeekOffset;
  71939. if (byteRangeHi < byteRangeLo) {
  71940. byteRangeHi = byteRangeLo;
  71941. }
  71942. targetByte = lastSuccessfulSeekOffset + (ma_uint64)(((ma_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
  71943. if (targetByte > byteRangeHi) {
  71944. targetByte = byteRangeHi;
  71945. }
  71946. if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
  71947. closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
  71948. }
  71949. }
  71950. }
  71951. }
  71952. } else {
  71953. break;
  71954. }
  71955. }
  71956. ma_dr_flac__seek_to_first_frame(pFlac);
  71957. return MA_FALSE;
  71958. }
  71959. static ma_bool32 ma_dr_flac__seek_to_pcm_frame__binary_search(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex)
  71960. {
  71961. ma_uint64 byteRangeLo;
  71962. ma_uint64 byteRangeHi;
  71963. ma_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  71964. if (ma_dr_flac__seek_to_first_frame(pFlac) == MA_FALSE) {
  71965. return MA_FALSE;
  71966. }
  71967. if (pcmFrameIndex < seekForwardThreshold) {
  71968. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
  71969. }
  71970. byteRangeLo = pFlac->firstFLACFramePosInBytes;
  71971. byteRangeHi = pFlac->firstFLACFramePosInBytes + (ma_uint64)((ma_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  71972. return ma_dr_flac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
  71973. }
  71974. #endif
  71975. static ma_bool32 ma_dr_flac__seek_to_pcm_frame__seek_table(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex)
  71976. {
  71977. ma_uint32 iClosestSeekpoint = 0;
  71978. ma_bool32 isMidFrame = MA_FALSE;
  71979. ma_uint64 runningPCMFrameCount;
  71980. ma_uint32 iSeekpoint;
  71981. MA_DR_FLAC_ASSERT(pFlac != NULL);
  71982. if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
  71983. return MA_FALSE;
  71984. }
  71985. if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) {
  71986. return MA_FALSE;
  71987. }
  71988. for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
  71989. if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
  71990. break;
  71991. }
  71992. iClosestSeekpoint = iSeekpoint;
  71993. }
  71994. if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
  71995. return MA_FALSE;
  71996. }
  71997. if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
  71998. return MA_FALSE;
  71999. }
  72000. #if !defined(MA_DR_FLAC_NO_CRC)
  72001. if (pFlac->totalPCMFrameCount > 0) {
  72002. ma_uint64 byteRangeLo;
  72003. ma_uint64 byteRangeHi;
  72004. byteRangeHi = pFlac->firstFLACFramePosInBytes + (ma_uint64)((ma_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  72005. byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
  72006. if (iClosestSeekpoint < pFlac->seekpointCount-1) {
  72007. ma_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
  72008. if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
  72009. return MA_FALSE;
  72010. }
  72011. if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((ma_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) {
  72012. byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1;
  72013. }
  72014. }
  72015. if (ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  72016. if (ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  72017. ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  72018. if (ma_dr_flac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
  72019. return MA_TRUE;
  72020. }
  72021. }
  72022. }
  72023. }
  72024. #endif
  72025. if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
  72026. runningPCMFrameCount = pFlac->currentPCMFrame;
  72027. if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  72028. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  72029. return MA_FALSE;
  72030. }
  72031. } else {
  72032. isMidFrame = MA_TRUE;
  72033. }
  72034. } else {
  72035. runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
  72036. if (!ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  72037. return MA_FALSE;
  72038. }
  72039. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  72040. return MA_FALSE;
  72041. }
  72042. }
  72043. for (;;) {
  72044. ma_uint64 pcmFrameCountInThisFLACFrame;
  72045. ma_uint64 firstPCMFrameInFLACFrame = 0;
  72046. ma_uint64 lastPCMFrameInFLACFrame = 0;
  72047. ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  72048. pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  72049. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  72050. ma_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  72051. if (!isMidFrame) {
  72052. ma_result result = ma_dr_flac__decode_flac_frame(pFlac);
  72053. if (result == MA_SUCCESS) {
  72054. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  72055. } else {
  72056. if (result == MA_CRC_MISMATCH) {
  72057. goto next_iteration;
  72058. } else {
  72059. return MA_FALSE;
  72060. }
  72061. }
  72062. } else {
  72063. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  72064. }
  72065. } else {
  72066. if (!isMidFrame) {
  72067. ma_result result = ma_dr_flac__seek_to_next_flac_frame(pFlac);
  72068. if (result == MA_SUCCESS) {
  72069. runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  72070. } else {
  72071. if (result == MA_CRC_MISMATCH) {
  72072. goto next_iteration;
  72073. } else {
  72074. return MA_FALSE;
  72075. }
  72076. }
  72077. } else {
  72078. runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  72079. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  72080. isMidFrame = MA_FALSE;
  72081. }
  72082. if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  72083. return MA_TRUE;
  72084. }
  72085. }
  72086. next_iteration:
  72087. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  72088. return MA_FALSE;
  72089. }
  72090. }
  72091. }
  72092. #ifndef MA_DR_FLAC_NO_OGG
  72093. typedef struct
  72094. {
  72095. ma_uint8 capturePattern[4];
  72096. ma_uint8 structureVersion;
  72097. ma_uint8 headerType;
  72098. ma_uint64 granulePosition;
  72099. ma_uint32 serialNumber;
  72100. ma_uint32 sequenceNumber;
  72101. ma_uint32 checksum;
  72102. ma_uint8 segmentCount;
  72103. ma_uint8 segmentTable[255];
  72104. } ma_dr_flac_ogg_page_header;
  72105. #endif
  72106. typedef struct
  72107. {
  72108. ma_dr_flac_read_proc onRead;
  72109. ma_dr_flac_seek_proc onSeek;
  72110. ma_dr_flac_meta_proc onMeta;
  72111. ma_dr_flac_container container;
  72112. void* pUserData;
  72113. void* pUserDataMD;
  72114. ma_uint32 sampleRate;
  72115. ma_uint8 channels;
  72116. ma_uint8 bitsPerSample;
  72117. ma_uint64 totalPCMFrameCount;
  72118. ma_uint16 maxBlockSizeInPCMFrames;
  72119. ma_uint64 runningFilePos;
  72120. ma_bool32 hasStreamInfoBlock;
  72121. ma_bool32 hasMetadataBlocks;
  72122. ma_dr_flac_bs bs;
  72123. ma_dr_flac_frame_header firstFrameHeader;
  72124. #ifndef MA_DR_FLAC_NO_OGG
  72125. ma_uint32 oggSerial;
  72126. ma_uint64 oggFirstBytePos;
  72127. ma_dr_flac_ogg_page_header oggBosHeader;
  72128. #endif
  72129. } ma_dr_flac_init_info;
  72130. static MA_INLINE void ma_dr_flac__decode_block_header(ma_uint32 blockHeader, ma_uint8* isLastBlock, ma_uint8* blockType, ma_uint32* blockSize)
  72131. {
  72132. blockHeader = ma_dr_flac__be2host_32(blockHeader);
  72133. *isLastBlock = (ma_uint8)((blockHeader & 0x80000000UL) >> 31);
  72134. *blockType = (ma_uint8)((blockHeader & 0x7F000000UL) >> 24);
  72135. *blockSize = (blockHeader & 0x00FFFFFFUL);
  72136. }
  72137. static MA_INLINE ma_bool32 ma_dr_flac__read_and_decode_block_header(ma_dr_flac_read_proc onRead, void* pUserData, ma_uint8* isLastBlock, ma_uint8* blockType, ma_uint32* blockSize)
  72138. {
  72139. ma_uint32 blockHeader;
  72140. *blockSize = 0;
  72141. if (onRead(pUserData, &blockHeader, 4) != 4) {
  72142. return MA_FALSE;
  72143. }
  72144. ma_dr_flac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
  72145. return MA_TRUE;
  72146. }
  72147. static ma_bool32 ma_dr_flac__read_streaminfo(ma_dr_flac_read_proc onRead, void* pUserData, ma_dr_flac_streaminfo* pStreamInfo)
  72148. {
  72149. ma_uint32 blockSizes;
  72150. ma_uint64 frameSizes = 0;
  72151. ma_uint64 importantProps;
  72152. ma_uint8 md5[16];
  72153. if (onRead(pUserData, &blockSizes, 4) != 4) {
  72154. return MA_FALSE;
  72155. }
  72156. if (onRead(pUserData, &frameSizes, 6) != 6) {
  72157. return MA_FALSE;
  72158. }
  72159. if (onRead(pUserData, &importantProps, 8) != 8) {
  72160. return MA_FALSE;
  72161. }
  72162. if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
  72163. return MA_FALSE;
  72164. }
  72165. blockSizes = ma_dr_flac__be2host_32(blockSizes);
  72166. frameSizes = ma_dr_flac__be2host_64(frameSizes);
  72167. importantProps = ma_dr_flac__be2host_64(importantProps);
  72168. pStreamInfo->minBlockSizeInPCMFrames = (ma_uint16)((blockSizes & 0xFFFF0000) >> 16);
  72169. pStreamInfo->maxBlockSizeInPCMFrames = (ma_uint16) (blockSizes & 0x0000FFFF);
  72170. pStreamInfo->minFrameSizeInPCMFrames = (ma_uint32)((frameSizes & (((ma_uint64)0x00FFFFFF << 16) << 24)) >> 40);
  72171. pStreamInfo->maxFrameSizeInPCMFrames = (ma_uint32)((frameSizes & (((ma_uint64)0x00FFFFFF << 16) << 0)) >> 16);
  72172. pStreamInfo->sampleRate = (ma_uint32)((importantProps & (((ma_uint64)0x000FFFFF << 16) << 28)) >> 44);
  72173. pStreamInfo->channels = (ma_uint8 )((importantProps & (((ma_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
  72174. pStreamInfo->bitsPerSample = (ma_uint8 )((importantProps & (((ma_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
  72175. pStreamInfo->totalPCMFrameCount = ((importantProps & ((((ma_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
  72176. MA_DR_FLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
  72177. return MA_TRUE;
  72178. }
  72179. static void* ma_dr_flac__malloc_default(size_t sz, void* pUserData)
  72180. {
  72181. (void)pUserData;
  72182. return MA_DR_FLAC_MALLOC(sz);
  72183. }
  72184. static void* ma_dr_flac__realloc_default(void* p, size_t sz, void* pUserData)
  72185. {
  72186. (void)pUserData;
  72187. return MA_DR_FLAC_REALLOC(p, sz);
  72188. }
  72189. static void ma_dr_flac__free_default(void* p, void* pUserData)
  72190. {
  72191. (void)pUserData;
  72192. MA_DR_FLAC_FREE(p);
  72193. }
  72194. static void* ma_dr_flac__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  72195. {
  72196. if (pAllocationCallbacks == NULL) {
  72197. return NULL;
  72198. }
  72199. if (pAllocationCallbacks->onMalloc != NULL) {
  72200. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  72201. }
  72202. if (pAllocationCallbacks->onRealloc != NULL) {
  72203. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  72204. }
  72205. return NULL;
  72206. }
  72207. static void* ma_dr_flac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks)
  72208. {
  72209. if (pAllocationCallbacks == NULL) {
  72210. return NULL;
  72211. }
  72212. if (pAllocationCallbacks->onRealloc != NULL) {
  72213. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  72214. }
  72215. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  72216. void* p2;
  72217. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  72218. if (p2 == NULL) {
  72219. return NULL;
  72220. }
  72221. if (p != NULL) {
  72222. MA_DR_FLAC_COPY_MEMORY(p2, p, szOld);
  72223. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  72224. }
  72225. return p2;
  72226. }
  72227. return NULL;
  72228. }
  72229. static void ma_dr_flac__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  72230. {
  72231. if (p == NULL || pAllocationCallbacks == NULL) {
  72232. return;
  72233. }
  72234. if (pAllocationCallbacks->onFree != NULL) {
  72235. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  72236. }
  72237. }
  72238. static ma_bool32 ma_dr_flac__read_and_decode_metadata(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, void* pUserDataMD, ma_uint64* pFirstFramePos, ma_uint64* pSeektablePos, ma_uint32* pSeekpointCount, ma_allocation_callbacks* pAllocationCallbacks)
  72239. {
  72240. ma_uint64 runningFilePos = 42;
  72241. ma_uint64 seektablePos = 0;
  72242. ma_uint32 seektableSize = 0;
  72243. for (;;) {
  72244. ma_dr_flac_metadata metadata;
  72245. ma_uint8 isLastBlock = 0;
  72246. ma_uint8 blockType = 0;
  72247. ma_uint32 blockSize;
  72248. if (ma_dr_flac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == MA_FALSE) {
  72249. return MA_FALSE;
  72250. }
  72251. runningFilePos += 4;
  72252. metadata.type = blockType;
  72253. metadata.pRawData = NULL;
  72254. metadata.rawDataSize = 0;
  72255. switch (blockType)
  72256. {
  72257. case MA_DR_FLAC_METADATA_BLOCK_TYPE_APPLICATION:
  72258. {
  72259. if (blockSize < 4) {
  72260. return MA_FALSE;
  72261. }
  72262. if (onMeta) {
  72263. void* pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72264. if (pRawData == NULL) {
  72265. return MA_FALSE;
  72266. }
  72267. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72268. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72269. return MA_FALSE;
  72270. }
  72271. metadata.pRawData = pRawData;
  72272. metadata.rawDataSize = blockSize;
  72273. metadata.data.application.id = ma_dr_flac__be2host_32(*(ma_uint32*)pRawData);
  72274. metadata.data.application.pData = (const void*)((ma_uint8*)pRawData + sizeof(ma_uint32));
  72275. metadata.data.application.dataSize = blockSize - sizeof(ma_uint32);
  72276. onMeta(pUserDataMD, &metadata);
  72277. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72278. }
  72279. } break;
  72280. case MA_DR_FLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
  72281. {
  72282. seektablePos = runningFilePos;
  72283. seektableSize = blockSize;
  72284. if (onMeta) {
  72285. ma_uint32 seekpointCount;
  72286. ma_uint32 iSeekpoint;
  72287. void* pRawData;
  72288. seekpointCount = blockSize/MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES;
  72289. pRawData = ma_dr_flac__malloc_from_callbacks(seekpointCount * sizeof(ma_dr_flac_seekpoint), pAllocationCallbacks);
  72290. if (pRawData == NULL) {
  72291. return MA_FALSE;
  72292. }
  72293. for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) {
  72294. ma_dr_flac_seekpoint* pSeekpoint = (ma_dr_flac_seekpoint*)pRawData + iSeekpoint;
  72295. if (onRead(pUserData, pSeekpoint, MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) != MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) {
  72296. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72297. return MA_FALSE;
  72298. }
  72299. pSeekpoint->firstPCMFrame = ma_dr_flac__be2host_64(pSeekpoint->firstPCMFrame);
  72300. pSeekpoint->flacFrameOffset = ma_dr_flac__be2host_64(pSeekpoint->flacFrameOffset);
  72301. pSeekpoint->pcmFrameCount = ma_dr_flac__be2host_16(pSeekpoint->pcmFrameCount);
  72302. }
  72303. metadata.pRawData = pRawData;
  72304. metadata.rawDataSize = blockSize;
  72305. metadata.data.seektable.seekpointCount = seekpointCount;
  72306. metadata.data.seektable.pSeekpoints = (const ma_dr_flac_seekpoint*)pRawData;
  72307. onMeta(pUserDataMD, &metadata);
  72308. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72309. }
  72310. } break;
  72311. case MA_DR_FLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
  72312. {
  72313. if (blockSize < 8) {
  72314. return MA_FALSE;
  72315. }
  72316. if (onMeta) {
  72317. void* pRawData;
  72318. const char* pRunningData;
  72319. const char* pRunningDataEnd;
  72320. ma_uint32 i;
  72321. pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72322. if (pRawData == NULL) {
  72323. return MA_FALSE;
  72324. }
  72325. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72326. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72327. return MA_FALSE;
  72328. }
  72329. metadata.pRawData = pRawData;
  72330. metadata.rawDataSize = blockSize;
  72331. pRunningData = (const char*)pRawData;
  72332. pRunningDataEnd = (const char*)pRawData + blockSize;
  72333. metadata.data.vorbis_comment.vendorLength = ma_dr_flac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72334. if ((pRunningDataEnd - pRunningData) - 4 < (ma_int64)metadata.data.vorbis_comment.vendorLength) {
  72335. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72336. return MA_FALSE;
  72337. }
  72338. metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
  72339. metadata.data.vorbis_comment.commentCount = ma_dr_flac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72340. if ((pRunningDataEnd - pRunningData) / sizeof(ma_uint32) < metadata.data.vorbis_comment.commentCount) {
  72341. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72342. return MA_FALSE;
  72343. }
  72344. metadata.data.vorbis_comment.pComments = pRunningData;
  72345. for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
  72346. ma_uint32 commentLength;
  72347. if (pRunningDataEnd - pRunningData < 4) {
  72348. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72349. return MA_FALSE;
  72350. }
  72351. commentLength = ma_dr_flac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72352. if (pRunningDataEnd - pRunningData < (ma_int64)commentLength) {
  72353. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72354. return MA_FALSE;
  72355. }
  72356. pRunningData += commentLength;
  72357. }
  72358. onMeta(pUserDataMD, &metadata);
  72359. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72360. }
  72361. } break;
  72362. case MA_DR_FLAC_METADATA_BLOCK_TYPE_CUESHEET:
  72363. {
  72364. if (blockSize < 396) {
  72365. return MA_FALSE;
  72366. }
  72367. if (onMeta) {
  72368. void* pRawData;
  72369. const char* pRunningData;
  72370. const char* pRunningDataEnd;
  72371. size_t bufferSize;
  72372. ma_uint8 iTrack;
  72373. ma_uint8 iIndex;
  72374. void* pTrackData;
  72375. pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72376. if (pRawData == NULL) {
  72377. return MA_FALSE;
  72378. }
  72379. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72380. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72381. return MA_FALSE;
  72382. }
  72383. metadata.pRawData = pRawData;
  72384. metadata.rawDataSize = blockSize;
  72385. pRunningData = (const char*)pRawData;
  72386. pRunningDataEnd = (const char*)pRawData + blockSize;
  72387. MA_DR_FLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
  72388. metadata.data.cuesheet.leadInSampleCount = ma_dr_flac__be2host_64(*(const ma_uint64*)pRunningData); pRunningData += 8;
  72389. metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
  72390. metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
  72391. metadata.data.cuesheet.pTrackData = NULL;
  72392. {
  72393. const char* pRunningDataSaved = pRunningData;
  72394. bufferSize = metadata.data.cuesheet.trackCount * MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES;
  72395. for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  72396. ma_uint8 indexCount;
  72397. ma_uint32 indexPointSize;
  72398. if (pRunningDataEnd - pRunningData < MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES) {
  72399. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72400. return MA_FALSE;
  72401. }
  72402. pRunningData += 35;
  72403. indexCount = pRunningData[0];
  72404. pRunningData += 1;
  72405. bufferSize += indexCount * sizeof(ma_dr_flac_cuesheet_track_index);
  72406. indexPointSize = indexCount * MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
  72407. if (pRunningDataEnd - pRunningData < (ma_int64)indexPointSize) {
  72408. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72409. return MA_FALSE;
  72410. }
  72411. pRunningData += indexPointSize;
  72412. }
  72413. pRunningData = pRunningDataSaved;
  72414. }
  72415. {
  72416. char* pRunningTrackData;
  72417. pTrackData = ma_dr_flac__malloc_from_callbacks(bufferSize, pAllocationCallbacks);
  72418. if (pTrackData == NULL) {
  72419. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72420. return MA_FALSE;
  72421. }
  72422. pRunningTrackData = (char*)pTrackData;
  72423. for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  72424. ma_uint8 indexCount;
  72425. MA_DR_FLAC_COPY_MEMORY(pRunningTrackData, pRunningData, MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES);
  72426. pRunningData += MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
  72427. pRunningTrackData += MA_DR_FLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
  72428. indexCount = pRunningData[0];
  72429. pRunningData += 1;
  72430. pRunningTrackData += 1;
  72431. for (iIndex = 0; iIndex < indexCount; ++iIndex) {
  72432. ma_dr_flac_cuesheet_track_index* pTrackIndex = (ma_dr_flac_cuesheet_track_index*)pRunningTrackData;
  72433. MA_DR_FLAC_COPY_MEMORY(pRunningTrackData, pRunningData, MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES);
  72434. pRunningData += MA_DR_FLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
  72435. pRunningTrackData += sizeof(ma_dr_flac_cuesheet_track_index);
  72436. pTrackIndex->offset = ma_dr_flac__be2host_64(pTrackIndex->offset);
  72437. }
  72438. }
  72439. metadata.data.cuesheet.pTrackData = pTrackData;
  72440. }
  72441. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72442. pRawData = NULL;
  72443. onMeta(pUserDataMD, &metadata);
  72444. ma_dr_flac__free_from_callbacks(pTrackData, pAllocationCallbacks);
  72445. pTrackData = NULL;
  72446. }
  72447. } break;
  72448. case MA_DR_FLAC_METADATA_BLOCK_TYPE_PICTURE:
  72449. {
  72450. if (blockSize < 32) {
  72451. return MA_FALSE;
  72452. }
  72453. if (onMeta) {
  72454. void* pRawData;
  72455. const char* pRunningData;
  72456. const char* pRunningDataEnd;
  72457. pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72458. if (pRawData == NULL) {
  72459. return MA_FALSE;
  72460. }
  72461. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72462. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72463. return MA_FALSE;
  72464. }
  72465. metadata.pRawData = pRawData;
  72466. metadata.rawDataSize = blockSize;
  72467. pRunningData = (const char*)pRawData;
  72468. pRunningDataEnd = (const char*)pRawData + blockSize;
  72469. metadata.data.picture.type = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72470. metadata.data.picture.mimeLength = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72471. if ((pRunningDataEnd - pRunningData) - 24 < (ma_int64)metadata.data.picture.mimeLength) {
  72472. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72473. return MA_FALSE;
  72474. }
  72475. metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength;
  72476. metadata.data.picture.descriptionLength = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72477. if ((pRunningDataEnd - pRunningData) - 20 < (ma_int64)metadata.data.picture.descriptionLength) {
  72478. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72479. return MA_FALSE;
  72480. }
  72481. metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength;
  72482. metadata.data.picture.width = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72483. metadata.data.picture.height = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72484. metadata.data.picture.colorDepth = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72485. metadata.data.picture.indexColorCount = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72486. metadata.data.picture.pictureDataSize = ma_dr_flac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  72487. metadata.data.picture.pPictureData = (const ma_uint8*)pRunningData;
  72488. if (pRunningDataEnd - pRunningData < (ma_int64)metadata.data.picture.pictureDataSize) {
  72489. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72490. return MA_FALSE;
  72491. }
  72492. onMeta(pUserDataMD, &metadata);
  72493. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72494. }
  72495. } break;
  72496. case MA_DR_FLAC_METADATA_BLOCK_TYPE_PADDING:
  72497. {
  72498. if (onMeta) {
  72499. metadata.data.padding.unused = 0;
  72500. if (!onSeek(pUserData, blockSize, ma_dr_flac_seek_origin_current)) {
  72501. isLastBlock = MA_TRUE;
  72502. } else {
  72503. onMeta(pUserDataMD, &metadata);
  72504. }
  72505. }
  72506. } break;
  72507. case MA_DR_FLAC_METADATA_BLOCK_TYPE_INVALID:
  72508. {
  72509. if (onMeta) {
  72510. if (!onSeek(pUserData, blockSize, ma_dr_flac_seek_origin_current)) {
  72511. isLastBlock = MA_TRUE;
  72512. }
  72513. }
  72514. } break;
  72515. default:
  72516. {
  72517. if (onMeta) {
  72518. void* pRawData = ma_dr_flac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  72519. if (pRawData == NULL) {
  72520. return MA_FALSE;
  72521. }
  72522. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  72523. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72524. return MA_FALSE;
  72525. }
  72526. metadata.pRawData = pRawData;
  72527. metadata.rawDataSize = blockSize;
  72528. onMeta(pUserDataMD, &metadata);
  72529. ma_dr_flac__free_from_callbacks(pRawData, pAllocationCallbacks);
  72530. }
  72531. } break;
  72532. }
  72533. if (onMeta == NULL && blockSize > 0) {
  72534. if (!onSeek(pUserData, blockSize, ma_dr_flac_seek_origin_current)) {
  72535. isLastBlock = MA_TRUE;
  72536. }
  72537. }
  72538. runningFilePos += blockSize;
  72539. if (isLastBlock) {
  72540. break;
  72541. }
  72542. }
  72543. *pSeektablePos = seektablePos;
  72544. *pSeekpointCount = seektableSize / MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES;
  72545. *pFirstFramePos = runningFilePos;
  72546. return MA_TRUE;
  72547. }
  72548. static ma_bool32 ma_dr_flac__init_private__native(ma_dr_flac_init_info* pInit, ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, void* pUserDataMD, ma_bool32 relaxed)
  72549. {
  72550. ma_uint8 isLastBlock;
  72551. ma_uint8 blockType;
  72552. ma_uint32 blockSize;
  72553. (void)onSeek;
  72554. pInit->container = ma_dr_flac_container_native;
  72555. if (!ma_dr_flac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  72556. return MA_FALSE;
  72557. }
  72558. if (blockType != MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  72559. if (!relaxed) {
  72560. return MA_FALSE;
  72561. } else {
  72562. pInit->hasStreamInfoBlock = MA_FALSE;
  72563. pInit->hasMetadataBlocks = MA_FALSE;
  72564. if (!ma_dr_flac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
  72565. return MA_FALSE;
  72566. }
  72567. if (pInit->firstFrameHeader.bitsPerSample == 0) {
  72568. return MA_FALSE;
  72569. }
  72570. pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
  72571. pInit->channels = ma_dr_flac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
  72572. pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
  72573. pInit->maxBlockSizeInPCMFrames = 65535;
  72574. return MA_TRUE;
  72575. }
  72576. } else {
  72577. ma_dr_flac_streaminfo streaminfo;
  72578. if (!ma_dr_flac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  72579. return MA_FALSE;
  72580. }
  72581. pInit->hasStreamInfoBlock = MA_TRUE;
  72582. pInit->sampleRate = streaminfo.sampleRate;
  72583. pInit->channels = streaminfo.channels;
  72584. pInit->bitsPerSample = streaminfo.bitsPerSample;
  72585. pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
  72586. pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  72587. pInit->hasMetadataBlocks = !isLastBlock;
  72588. if (onMeta) {
  72589. ma_dr_flac_metadata metadata;
  72590. metadata.type = MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  72591. metadata.pRawData = NULL;
  72592. metadata.rawDataSize = 0;
  72593. metadata.data.streaminfo = streaminfo;
  72594. onMeta(pUserDataMD, &metadata);
  72595. }
  72596. return MA_TRUE;
  72597. }
  72598. }
  72599. #ifndef MA_DR_FLAC_NO_OGG
  72600. #define MA_DR_FLAC_OGG_MAX_PAGE_SIZE 65307
  72601. #define MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199
  72602. typedef enum
  72603. {
  72604. ma_dr_flac_ogg_recover_on_crc_mismatch,
  72605. ma_dr_flac_ogg_fail_on_crc_mismatch
  72606. } ma_dr_flac_ogg_crc_mismatch_recovery;
  72607. #ifndef MA_DR_FLAC_NO_CRC
  72608. static ma_uint32 ma_dr_flac__crc32_table[] = {
  72609. 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
  72610. 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
  72611. 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
  72612. 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
  72613. 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
  72614. 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
  72615. 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
  72616. 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
  72617. 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
  72618. 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
  72619. 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
  72620. 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
  72621. 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
  72622. 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
  72623. 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
  72624. 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
  72625. 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
  72626. 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
  72627. 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
  72628. 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
  72629. 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
  72630. 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
  72631. 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
  72632. 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
  72633. 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
  72634. 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
  72635. 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
  72636. 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
  72637. 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
  72638. 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
  72639. 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
  72640. 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
  72641. 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
  72642. 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
  72643. 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
  72644. 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
  72645. 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
  72646. 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
  72647. 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
  72648. 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
  72649. 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
  72650. 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
  72651. 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
  72652. 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
  72653. 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
  72654. 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
  72655. 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
  72656. 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
  72657. 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
  72658. 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
  72659. 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
  72660. 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
  72661. 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
  72662. 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
  72663. 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
  72664. 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
  72665. 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
  72666. 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
  72667. 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
  72668. 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
  72669. 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
  72670. 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
  72671. 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
  72672. 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
  72673. };
  72674. #endif
  72675. static MA_INLINE ma_uint32 ma_dr_flac_crc32_byte(ma_uint32 crc32, ma_uint8 data)
  72676. {
  72677. #ifndef MA_DR_FLAC_NO_CRC
  72678. return (crc32 << 8) ^ ma_dr_flac__crc32_table[(ma_uint8)((crc32 >> 24) & 0xFF) ^ data];
  72679. #else
  72680. (void)data;
  72681. return crc32;
  72682. #endif
  72683. }
  72684. #if 0
  72685. static MA_INLINE ma_uint32 ma_dr_flac_crc32_uint32(ma_uint32 crc32, ma_uint32 data)
  72686. {
  72687. crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 24) & 0xFF));
  72688. crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 16) & 0xFF));
  72689. crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 8) & 0xFF));
  72690. crc32 = ma_dr_flac_crc32_byte(crc32, (ma_uint8)((data >> 0) & 0xFF));
  72691. return crc32;
  72692. }
  72693. static MA_INLINE ma_uint32 ma_dr_flac_crc32_uint64(ma_uint32 crc32, ma_uint64 data)
  72694. {
  72695. crc32 = ma_dr_flac_crc32_uint32(crc32, (ma_uint32)((data >> 32) & 0xFFFFFFFF));
  72696. crc32 = ma_dr_flac_crc32_uint32(crc32, (ma_uint32)((data >> 0) & 0xFFFFFFFF));
  72697. return crc32;
  72698. }
  72699. #endif
  72700. static MA_INLINE ma_uint32 ma_dr_flac_crc32_buffer(ma_uint32 crc32, ma_uint8* pData, ma_uint32 dataSize)
  72701. {
  72702. ma_uint32 i;
  72703. for (i = 0; i < dataSize; ++i) {
  72704. crc32 = ma_dr_flac_crc32_byte(crc32, pData[i]);
  72705. }
  72706. return crc32;
  72707. }
  72708. static MA_INLINE ma_bool32 ma_dr_flac_ogg__is_capture_pattern(ma_uint8 pattern[4])
  72709. {
  72710. return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
  72711. }
  72712. static MA_INLINE ma_uint32 ma_dr_flac_ogg__get_page_header_size(ma_dr_flac_ogg_page_header* pHeader)
  72713. {
  72714. return 27 + pHeader->segmentCount;
  72715. }
  72716. static MA_INLINE ma_uint32 ma_dr_flac_ogg__get_page_body_size(ma_dr_flac_ogg_page_header* pHeader)
  72717. {
  72718. ma_uint32 pageBodySize = 0;
  72719. int i;
  72720. for (i = 0; i < pHeader->segmentCount; ++i) {
  72721. pageBodySize += pHeader->segmentTable[i];
  72722. }
  72723. return pageBodySize;
  72724. }
  72725. static ma_result ma_dr_flac_ogg__read_page_header_after_capture_pattern(ma_dr_flac_read_proc onRead, void* pUserData, ma_dr_flac_ogg_page_header* pHeader, ma_uint32* pBytesRead, ma_uint32* pCRC32)
  72726. {
  72727. ma_uint8 data[23];
  72728. ma_uint32 i;
  72729. MA_DR_FLAC_ASSERT(*pCRC32 == MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32);
  72730. if (onRead(pUserData, data, 23) != 23) {
  72731. return MA_AT_END;
  72732. }
  72733. *pBytesRead += 23;
  72734. pHeader->capturePattern[0] = 'O';
  72735. pHeader->capturePattern[1] = 'g';
  72736. pHeader->capturePattern[2] = 'g';
  72737. pHeader->capturePattern[3] = 'S';
  72738. pHeader->structureVersion = data[0];
  72739. pHeader->headerType = data[1];
  72740. MA_DR_FLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
  72741. MA_DR_FLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4);
  72742. MA_DR_FLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4);
  72743. MA_DR_FLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4);
  72744. pHeader->segmentCount = data[22];
  72745. data[18] = 0;
  72746. data[19] = 0;
  72747. data[20] = 0;
  72748. data[21] = 0;
  72749. for (i = 0; i < 23; ++i) {
  72750. *pCRC32 = ma_dr_flac_crc32_byte(*pCRC32, data[i]);
  72751. }
  72752. if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
  72753. return MA_AT_END;
  72754. }
  72755. *pBytesRead += pHeader->segmentCount;
  72756. for (i = 0; i < pHeader->segmentCount; ++i) {
  72757. *pCRC32 = ma_dr_flac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
  72758. }
  72759. return MA_SUCCESS;
  72760. }
  72761. static ma_result ma_dr_flac_ogg__read_page_header(ma_dr_flac_read_proc onRead, void* pUserData, ma_dr_flac_ogg_page_header* pHeader, ma_uint32* pBytesRead, ma_uint32* pCRC32)
  72762. {
  72763. ma_uint8 id[4];
  72764. *pBytesRead = 0;
  72765. if (onRead(pUserData, id, 4) != 4) {
  72766. return MA_AT_END;
  72767. }
  72768. *pBytesRead += 4;
  72769. for (;;) {
  72770. if (ma_dr_flac_ogg__is_capture_pattern(id)) {
  72771. ma_result result;
  72772. *pCRC32 = MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32;
  72773. result = ma_dr_flac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
  72774. if (result == MA_SUCCESS) {
  72775. return MA_SUCCESS;
  72776. } else {
  72777. if (result == MA_CRC_MISMATCH) {
  72778. continue;
  72779. } else {
  72780. return result;
  72781. }
  72782. }
  72783. } else {
  72784. id[0] = id[1];
  72785. id[1] = id[2];
  72786. id[2] = id[3];
  72787. if (onRead(pUserData, &id[3], 1) != 1) {
  72788. return MA_AT_END;
  72789. }
  72790. *pBytesRead += 1;
  72791. }
  72792. }
  72793. }
  72794. typedef struct
  72795. {
  72796. ma_dr_flac_read_proc onRead;
  72797. ma_dr_flac_seek_proc onSeek;
  72798. void* pUserData;
  72799. ma_uint64 currentBytePos;
  72800. ma_uint64 firstBytePos;
  72801. ma_uint32 serialNumber;
  72802. ma_dr_flac_ogg_page_header bosPageHeader;
  72803. ma_dr_flac_ogg_page_header currentPageHeader;
  72804. ma_uint32 bytesRemainingInPage;
  72805. ma_uint32 pageDataSize;
  72806. ma_uint8 pageData[MA_DR_FLAC_OGG_MAX_PAGE_SIZE];
  72807. } ma_dr_flac_oggbs;
  72808. static size_t ma_dr_flac_oggbs__read_physical(ma_dr_flac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
  72809. {
  72810. size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
  72811. oggbs->currentBytePos += bytesActuallyRead;
  72812. return bytesActuallyRead;
  72813. }
  72814. static ma_bool32 ma_dr_flac_oggbs__seek_physical(ma_dr_flac_oggbs* oggbs, ma_uint64 offset, ma_dr_flac_seek_origin origin)
  72815. {
  72816. if (origin == ma_dr_flac_seek_origin_start) {
  72817. if (offset <= 0x7FFFFFFF) {
  72818. if (!oggbs->onSeek(oggbs->pUserData, (int)offset, ma_dr_flac_seek_origin_start)) {
  72819. return MA_FALSE;
  72820. }
  72821. oggbs->currentBytePos = offset;
  72822. return MA_TRUE;
  72823. } else {
  72824. if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_start)) {
  72825. return MA_FALSE;
  72826. }
  72827. oggbs->currentBytePos = offset;
  72828. return ma_dr_flac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, ma_dr_flac_seek_origin_current);
  72829. }
  72830. } else {
  72831. while (offset > 0x7FFFFFFF) {
  72832. if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, ma_dr_flac_seek_origin_current)) {
  72833. return MA_FALSE;
  72834. }
  72835. oggbs->currentBytePos += 0x7FFFFFFF;
  72836. offset -= 0x7FFFFFFF;
  72837. }
  72838. if (!oggbs->onSeek(oggbs->pUserData, (int)offset, ma_dr_flac_seek_origin_current)) {
  72839. return MA_FALSE;
  72840. }
  72841. oggbs->currentBytePos += offset;
  72842. return MA_TRUE;
  72843. }
  72844. }
  72845. static ma_bool32 ma_dr_flac_oggbs__goto_next_page(ma_dr_flac_oggbs* oggbs, ma_dr_flac_ogg_crc_mismatch_recovery recoveryMethod)
  72846. {
  72847. ma_dr_flac_ogg_page_header header;
  72848. for (;;) {
  72849. ma_uint32 crc32 = 0;
  72850. ma_uint32 bytesRead;
  72851. ma_uint32 pageBodySize;
  72852. #ifndef MA_DR_FLAC_NO_CRC
  72853. ma_uint32 actualCRC32;
  72854. #endif
  72855. if (ma_dr_flac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != MA_SUCCESS) {
  72856. return MA_FALSE;
  72857. }
  72858. oggbs->currentBytePos += bytesRead;
  72859. pageBodySize = ma_dr_flac_ogg__get_page_body_size(&header);
  72860. if (pageBodySize > MA_DR_FLAC_OGG_MAX_PAGE_SIZE) {
  72861. continue;
  72862. }
  72863. if (header.serialNumber != oggbs->serialNumber) {
  72864. if (pageBodySize > 0 && !ma_dr_flac_oggbs__seek_physical(oggbs, pageBodySize, ma_dr_flac_seek_origin_current)) {
  72865. return MA_FALSE;
  72866. }
  72867. continue;
  72868. }
  72869. if (ma_dr_flac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
  72870. return MA_FALSE;
  72871. }
  72872. oggbs->pageDataSize = pageBodySize;
  72873. #ifndef MA_DR_FLAC_NO_CRC
  72874. actualCRC32 = ma_dr_flac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
  72875. if (actualCRC32 != header.checksum) {
  72876. if (recoveryMethod == ma_dr_flac_ogg_recover_on_crc_mismatch) {
  72877. continue;
  72878. } else {
  72879. ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch);
  72880. return MA_FALSE;
  72881. }
  72882. }
  72883. #else
  72884. (void)recoveryMethod;
  72885. #endif
  72886. oggbs->currentPageHeader = header;
  72887. oggbs->bytesRemainingInPage = pageBodySize;
  72888. return MA_TRUE;
  72889. }
  72890. }
  72891. #if 0
  72892. static ma_uint8 ma_dr_flac_oggbs__get_current_segment_index(ma_dr_flac_oggbs* oggbs, ma_uint8* pBytesRemainingInSeg)
  72893. {
  72894. ma_uint32 bytesConsumedInPage = ma_dr_flac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
  72895. ma_uint8 iSeg = 0;
  72896. ma_uint32 iByte = 0;
  72897. while (iByte < bytesConsumedInPage) {
  72898. ma_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  72899. if (iByte + segmentSize > bytesConsumedInPage) {
  72900. break;
  72901. } else {
  72902. iSeg += 1;
  72903. iByte += segmentSize;
  72904. }
  72905. }
  72906. *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (ma_uint8)(bytesConsumedInPage - iByte);
  72907. return iSeg;
  72908. }
  72909. static ma_bool32 ma_dr_flac_oggbs__seek_to_next_packet(ma_dr_flac_oggbs* oggbs)
  72910. {
  72911. for (;;) {
  72912. ma_bool32 atEndOfPage = MA_FALSE;
  72913. ma_uint8 bytesRemainingInSeg;
  72914. ma_uint8 iFirstSeg = ma_dr_flac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
  72915. ma_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
  72916. for (ma_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
  72917. ma_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  72918. if (segmentSize < 255) {
  72919. if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
  72920. atEndOfPage = MA_TRUE;
  72921. }
  72922. break;
  72923. }
  72924. bytesToEndOfPacketOrPage += segmentSize;
  72925. }
  72926. ma_dr_flac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, ma_dr_flac_seek_origin_current);
  72927. oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
  72928. if (atEndOfPage) {
  72929. if (!ma_dr_flac_oggbs__goto_next_page(oggbs)) {
  72930. return MA_FALSE;
  72931. }
  72932. if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  72933. return MA_TRUE;
  72934. }
  72935. } else {
  72936. return MA_TRUE;
  72937. }
  72938. }
  72939. }
  72940. static ma_bool32 ma_dr_flac_oggbs__seek_to_next_frame(ma_dr_flac_oggbs* oggbs)
  72941. {
  72942. return ma_dr_flac_oggbs__seek_to_next_packet(oggbs);
  72943. }
  72944. #endif
  72945. static size_t ma_dr_flac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
  72946. {
  72947. ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pUserData;
  72948. ma_uint8* pRunningBufferOut = (ma_uint8*)bufferOut;
  72949. size_t bytesRead = 0;
  72950. MA_DR_FLAC_ASSERT(oggbs != NULL);
  72951. MA_DR_FLAC_ASSERT(pRunningBufferOut != NULL);
  72952. while (bytesRead < bytesToRead) {
  72953. size_t bytesRemainingToRead = bytesToRead - bytesRead;
  72954. if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
  72955. MA_DR_FLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
  72956. bytesRead += bytesRemainingToRead;
  72957. oggbs->bytesRemainingInPage -= (ma_uint32)bytesRemainingToRead;
  72958. break;
  72959. }
  72960. if (oggbs->bytesRemainingInPage > 0) {
  72961. MA_DR_FLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
  72962. bytesRead += oggbs->bytesRemainingInPage;
  72963. pRunningBufferOut += oggbs->bytesRemainingInPage;
  72964. oggbs->bytesRemainingInPage = 0;
  72965. }
  72966. MA_DR_FLAC_ASSERT(bytesRemainingToRead > 0);
  72967. if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch)) {
  72968. break;
  72969. }
  72970. }
  72971. return bytesRead;
  72972. }
  72973. static ma_bool32 ma_dr_flac__on_seek_ogg(void* pUserData, int offset, ma_dr_flac_seek_origin origin)
  72974. {
  72975. ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pUserData;
  72976. int bytesSeeked = 0;
  72977. MA_DR_FLAC_ASSERT(oggbs != NULL);
  72978. MA_DR_FLAC_ASSERT(offset >= 0);
  72979. if (origin == ma_dr_flac_seek_origin_start) {
  72980. if (!ma_dr_flac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, ma_dr_flac_seek_origin_start)) {
  72981. return MA_FALSE;
  72982. }
  72983. if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_fail_on_crc_mismatch)) {
  72984. return MA_FALSE;
  72985. }
  72986. return ma_dr_flac__on_seek_ogg(pUserData, offset, ma_dr_flac_seek_origin_current);
  72987. }
  72988. MA_DR_FLAC_ASSERT(origin == ma_dr_flac_seek_origin_current);
  72989. while (bytesSeeked < offset) {
  72990. int bytesRemainingToSeek = offset - bytesSeeked;
  72991. MA_DR_FLAC_ASSERT(bytesRemainingToSeek >= 0);
  72992. if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
  72993. bytesSeeked += bytesRemainingToSeek;
  72994. (void)bytesSeeked;
  72995. oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
  72996. break;
  72997. }
  72998. if (oggbs->bytesRemainingInPage > 0) {
  72999. bytesSeeked += (int)oggbs->bytesRemainingInPage;
  73000. oggbs->bytesRemainingInPage = 0;
  73001. }
  73002. MA_DR_FLAC_ASSERT(bytesRemainingToSeek > 0);
  73003. if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_fail_on_crc_mismatch)) {
  73004. return MA_FALSE;
  73005. }
  73006. }
  73007. return MA_TRUE;
  73008. }
  73009. static ma_bool32 ma_dr_flac_ogg__seek_to_pcm_frame(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex)
  73010. {
  73011. ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs;
  73012. ma_uint64 originalBytePos;
  73013. ma_uint64 runningGranulePosition;
  73014. ma_uint64 runningFrameBytePos;
  73015. ma_uint64 runningPCMFrameCount;
  73016. MA_DR_FLAC_ASSERT(oggbs != NULL);
  73017. originalBytePos = oggbs->currentBytePos;
  73018. if (!ma_dr_flac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
  73019. return MA_FALSE;
  73020. }
  73021. oggbs->bytesRemainingInPage = 0;
  73022. runningGranulePosition = 0;
  73023. for (;;) {
  73024. if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch)) {
  73025. ma_dr_flac_oggbs__seek_physical(oggbs, originalBytePos, ma_dr_flac_seek_origin_start);
  73026. return MA_FALSE;
  73027. }
  73028. runningFrameBytePos = oggbs->currentBytePos - ma_dr_flac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
  73029. if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
  73030. break;
  73031. }
  73032. if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  73033. if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
  73034. ma_uint8 firstBytesInPage[2];
  73035. firstBytesInPage[0] = oggbs->pageData[0];
  73036. firstBytesInPage[1] = oggbs->pageData[1];
  73037. if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) {
  73038. runningGranulePosition = oggbs->currentPageHeader.granulePosition;
  73039. }
  73040. continue;
  73041. }
  73042. }
  73043. }
  73044. if (!ma_dr_flac_oggbs__seek_physical(oggbs, runningFrameBytePos, ma_dr_flac_seek_origin_start)) {
  73045. return MA_FALSE;
  73046. }
  73047. if (!ma_dr_flac_oggbs__goto_next_page(oggbs, ma_dr_flac_ogg_recover_on_crc_mismatch)) {
  73048. return MA_FALSE;
  73049. }
  73050. runningPCMFrameCount = runningGranulePosition;
  73051. for (;;) {
  73052. ma_uint64 firstPCMFrameInFLACFrame = 0;
  73053. ma_uint64 lastPCMFrameInFLACFrame = 0;
  73054. ma_uint64 pcmFrameCountInThisFrame;
  73055. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  73056. return MA_FALSE;
  73057. }
  73058. ma_dr_flac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  73059. pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  73060. if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
  73061. ma_result result = ma_dr_flac__decode_flac_frame(pFlac);
  73062. if (result == MA_SUCCESS) {
  73063. pFlac->currentPCMFrame = pcmFrameIndex;
  73064. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  73065. return MA_TRUE;
  73066. } else {
  73067. return MA_FALSE;
  73068. }
  73069. }
  73070. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
  73071. ma_result result = ma_dr_flac__decode_flac_frame(pFlac);
  73072. if (result == MA_SUCCESS) {
  73073. ma_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount);
  73074. if (pcmFramesToDecode == 0) {
  73075. return MA_TRUE;
  73076. }
  73077. pFlac->currentPCMFrame = runningPCMFrameCount;
  73078. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  73079. } else {
  73080. if (result == MA_CRC_MISMATCH) {
  73081. continue;
  73082. } else {
  73083. return MA_FALSE;
  73084. }
  73085. }
  73086. } else {
  73087. ma_result result = ma_dr_flac__seek_to_next_flac_frame(pFlac);
  73088. if (result == MA_SUCCESS) {
  73089. runningPCMFrameCount += pcmFrameCountInThisFrame;
  73090. } else {
  73091. if (result == MA_CRC_MISMATCH) {
  73092. continue;
  73093. } else {
  73094. return MA_FALSE;
  73095. }
  73096. }
  73097. }
  73098. }
  73099. }
  73100. static ma_bool32 ma_dr_flac__init_private__ogg(ma_dr_flac_init_info* pInit, ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, void* pUserDataMD, ma_bool32 relaxed)
  73101. {
  73102. ma_dr_flac_ogg_page_header header;
  73103. ma_uint32 crc32 = MA_DR_FLAC_OGG_CAPTURE_PATTERN_CRC32;
  73104. ma_uint32 bytesRead = 0;
  73105. (void)relaxed;
  73106. pInit->container = ma_dr_flac_container_ogg;
  73107. pInit->oggFirstBytePos = 0;
  73108. if (ma_dr_flac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != MA_SUCCESS) {
  73109. return MA_FALSE;
  73110. }
  73111. pInit->runningFilePos += bytesRead;
  73112. for (;;) {
  73113. int pageBodySize;
  73114. if ((header.headerType & 0x02) == 0) {
  73115. return MA_FALSE;
  73116. }
  73117. pageBodySize = ma_dr_flac_ogg__get_page_body_size(&header);
  73118. if (pageBodySize == 51) {
  73119. ma_uint32 bytesRemainingInPage = pageBodySize;
  73120. ma_uint8 packetType;
  73121. if (onRead(pUserData, &packetType, 1) != 1) {
  73122. return MA_FALSE;
  73123. }
  73124. bytesRemainingInPage -= 1;
  73125. if (packetType == 0x7F) {
  73126. ma_uint8 sig[4];
  73127. if (onRead(pUserData, sig, 4) != 4) {
  73128. return MA_FALSE;
  73129. }
  73130. bytesRemainingInPage -= 4;
  73131. if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
  73132. ma_uint8 mappingVersion[2];
  73133. if (onRead(pUserData, mappingVersion, 2) != 2) {
  73134. return MA_FALSE;
  73135. }
  73136. if (mappingVersion[0] != 1) {
  73137. return MA_FALSE;
  73138. }
  73139. if (!onSeek(pUserData, 2, ma_dr_flac_seek_origin_current)) {
  73140. return MA_FALSE;
  73141. }
  73142. if (onRead(pUserData, sig, 4) != 4) {
  73143. return MA_FALSE;
  73144. }
  73145. if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
  73146. ma_dr_flac_streaminfo streaminfo;
  73147. ma_uint8 isLastBlock;
  73148. ma_uint8 blockType;
  73149. ma_uint32 blockSize;
  73150. if (!ma_dr_flac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  73151. return MA_FALSE;
  73152. }
  73153. if (blockType != MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  73154. return MA_FALSE;
  73155. }
  73156. if (ma_dr_flac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  73157. pInit->hasStreamInfoBlock = MA_TRUE;
  73158. pInit->sampleRate = streaminfo.sampleRate;
  73159. pInit->channels = streaminfo.channels;
  73160. pInit->bitsPerSample = streaminfo.bitsPerSample;
  73161. pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
  73162. pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  73163. pInit->hasMetadataBlocks = !isLastBlock;
  73164. if (onMeta) {
  73165. ma_dr_flac_metadata metadata;
  73166. metadata.type = MA_DR_FLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  73167. metadata.pRawData = NULL;
  73168. metadata.rawDataSize = 0;
  73169. metadata.data.streaminfo = streaminfo;
  73170. onMeta(pUserDataMD, &metadata);
  73171. }
  73172. pInit->runningFilePos += pageBodySize;
  73173. pInit->oggFirstBytePos = pInit->runningFilePos - 79;
  73174. pInit->oggSerial = header.serialNumber;
  73175. pInit->oggBosHeader = header;
  73176. break;
  73177. } else {
  73178. return MA_FALSE;
  73179. }
  73180. } else {
  73181. return MA_FALSE;
  73182. }
  73183. } else {
  73184. if (!onSeek(pUserData, bytesRemainingInPage, ma_dr_flac_seek_origin_current)) {
  73185. return MA_FALSE;
  73186. }
  73187. }
  73188. } else {
  73189. if (!onSeek(pUserData, bytesRemainingInPage, ma_dr_flac_seek_origin_current)) {
  73190. return MA_FALSE;
  73191. }
  73192. }
  73193. } else {
  73194. if (!onSeek(pUserData, pageBodySize, ma_dr_flac_seek_origin_current)) {
  73195. return MA_FALSE;
  73196. }
  73197. }
  73198. pInit->runningFilePos += pageBodySize;
  73199. if (ma_dr_flac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != MA_SUCCESS) {
  73200. return MA_FALSE;
  73201. }
  73202. pInit->runningFilePos += bytesRead;
  73203. }
  73204. pInit->hasMetadataBlocks = MA_TRUE;
  73205. return MA_TRUE;
  73206. }
  73207. #endif
  73208. static ma_bool32 ma_dr_flac__init_private(ma_dr_flac_init_info* pInit, ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, void* pUserDataMD)
  73209. {
  73210. ma_bool32 relaxed;
  73211. ma_uint8 id[4];
  73212. if (pInit == NULL || onRead == NULL || onSeek == NULL) {
  73213. return MA_FALSE;
  73214. }
  73215. MA_DR_FLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
  73216. pInit->onRead = onRead;
  73217. pInit->onSeek = onSeek;
  73218. pInit->onMeta = onMeta;
  73219. pInit->container = container;
  73220. pInit->pUserData = pUserData;
  73221. pInit->pUserDataMD = pUserDataMD;
  73222. pInit->bs.onRead = onRead;
  73223. pInit->bs.onSeek = onSeek;
  73224. pInit->bs.pUserData = pUserData;
  73225. ma_dr_flac__reset_cache(&pInit->bs);
  73226. relaxed = container != ma_dr_flac_container_unknown;
  73227. for (;;) {
  73228. if (onRead(pUserData, id, 4) != 4) {
  73229. return MA_FALSE;
  73230. }
  73231. pInit->runningFilePos += 4;
  73232. if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
  73233. ma_uint8 header[6];
  73234. ma_uint8 flags;
  73235. ma_uint32 headerSize;
  73236. if (onRead(pUserData, header, 6) != 6) {
  73237. return MA_FALSE;
  73238. }
  73239. pInit->runningFilePos += 6;
  73240. flags = header[1];
  73241. MA_DR_FLAC_COPY_MEMORY(&headerSize, header+2, 4);
  73242. headerSize = ma_dr_flac__unsynchsafe_32(ma_dr_flac__be2host_32(headerSize));
  73243. if (flags & 0x10) {
  73244. headerSize += 10;
  73245. }
  73246. if (!onSeek(pUserData, headerSize, ma_dr_flac_seek_origin_current)) {
  73247. return MA_FALSE;
  73248. }
  73249. pInit->runningFilePos += headerSize;
  73250. } else {
  73251. break;
  73252. }
  73253. }
  73254. if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
  73255. return ma_dr_flac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73256. }
  73257. #ifndef MA_DR_FLAC_NO_OGG
  73258. if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
  73259. return ma_dr_flac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73260. }
  73261. #endif
  73262. if (relaxed) {
  73263. if (container == ma_dr_flac_container_native) {
  73264. return ma_dr_flac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73265. }
  73266. #ifndef MA_DR_FLAC_NO_OGG
  73267. if (container == ma_dr_flac_container_ogg) {
  73268. return ma_dr_flac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  73269. }
  73270. #endif
  73271. }
  73272. return MA_FALSE;
  73273. }
  73274. static void ma_dr_flac__init_from_info(ma_dr_flac* pFlac, const ma_dr_flac_init_info* pInit)
  73275. {
  73276. MA_DR_FLAC_ASSERT(pFlac != NULL);
  73277. MA_DR_FLAC_ASSERT(pInit != NULL);
  73278. MA_DR_FLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
  73279. pFlac->bs = pInit->bs;
  73280. pFlac->onMeta = pInit->onMeta;
  73281. pFlac->pUserDataMD = pInit->pUserDataMD;
  73282. pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
  73283. pFlac->sampleRate = pInit->sampleRate;
  73284. pFlac->channels = (ma_uint8)pInit->channels;
  73285. pFlac->bitsPerSample = (ma_uint8)pInit->bitsPerSample;
  73286. pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount;
  73287. pFlac->container = pInit->container;
  73288. }
  73289. static ma_dr_flac* ma_dr_flac_open_with_metadata_private(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, void* pUserDataMD, const ma_allocation_callbacks* pAllocationCallbacks)
  73290. {
  73291. ma_dr_flac_init_info init;
  73292. ma_uint32 allocationSize;
  73293. ma_uint32 wholeSIMDVectorCountPerChannel;
  73294. ma_uint32 decodedSamplesAllocationSize;
  73295. #ifndef MA_DR_FLAC_NO_OGG
  73296. ma_dr_flac_oggbs* pOggbs = NULL;
  73297. #endif
  73298. ma_uint64 firstFramePos;
  73299. ma_uint64 seektablePos;
  73300. ma_uint32 seekpointCount;
  73301. ma_allocation_callbacks allocationCallbacks;
  73302. ma_dr_flac* pFlac;
  73303. ma_dr_flac__init_cpu_caps();
  73304. if (!ma_dr_flac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) {
  73305. return NULL;
  73306. }
  73307. if (pAllocationCallbacks != NULL) {
  73308. allocationCallbacks = *pAllocationCallbacks;
  73309. if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
  73310. return NULL;
  73311. }
  73312. } else {
  73313. allocationCallbacks.pUserData = NULL;
  73314. allocationCallbacks.onMalloc = ma_dr_flac__malloc_default;
  73315. allocationCallbacks.onRealloc = ma_dr_flac__realloc_default;
  73316. allocationCallbacks.onFree = ma_dr_flac__free_default;
  73317. }
  73318. allocationSize = sizeof(ma_dr_flac);
  73319. if ((init.maxBlockSizeInPCMFrames % (MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE / sizeof(ma_int32))) == 0) {
  73320. wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE / sizeof(ma_int32)));
  73321. } else {
  73322. wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE / sizeof(ma_int32))) + 1;
  73323. }
  73324. decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
  73325. allocationSize += decodedSamplesAllocationSize;
  73326. allocationSize += MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE;
  73327. #ifndef MA_DR_FLAC_NO_OGG
  73328. if (init.container == ma_dr_flac_container_ogg) {
  73329. allocationSize += sizeof(ma_dr_flac_oggbs);
  73330. pOggbs = (ma_dr_flac_oggbs*)ma_dr_flac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks);
  73331. if (pOggbs == NULL) {
  73332. return NULL;
  73333. }
  73334. MA_DR_FLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs));
  73335. pOggbs->onRead = onRead;
  73336. pOggbs->onSeek = onSeek;
  73337. pOggbs->pUserData = pUserData;
  73338. pOggbs->currentBytePos = init.oggFirstBytePos;
  73339. pOggbs->firstBytePos = init.oggFirstBytePos;
  73340. pOggbs->serialNumber = init.oggSerial;
  73341. pOggbs->bosPageHeader = init.oggBosHeader;
  73342. pOggbs->bytesRemainingInPage = 0;
  73343. }
  73344. #endif
  73345. firstFramePos = 42;
  73346. seektablePos = 0;
  73347. seekpointCount = 0;
  73348. if (init.hasMetadataBlocks) {
  73349. ma_dr_flac_read_proc onReadOverride = onRead;
  73350. ma_dr_flac_seek_proc onSeekOverride = onSeek;
  73351. void* pUserDataOverride = pUserData;
  73352. #ifndef MA_DR_FLAC_NO_OGG
  73353. if (init.container == ma_dr_flac_container_ogg) {
  73354. onReadOverride = ma_dr_flac__on_read_ogg;
  73355. onSeekOverride = ma_dr_flac__on_seek_ogg;
  73356. pUserDataOverride = (void*)pOggbs;
  73357. }
  73358. #endif
  73359. if (!ma_dr_flac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) {
  73360. #ifndef MA_DR_FLAC_NO_OGG
  73361. ma_dr_flac__free_from_callbacks(pOggbs, &allocationCallbacks);
  73362. #endif
  73363. return NULL;
  73364. }
  73365. allocationSize += seekpointCount * sizeof(ma_dr_flac_seekpoint);
  73366. }
  73367. pFlac = (ma_dr_flac*)ma_dr_flac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
  73368. if (pFlac == NULL) {
  73369. #ifndef MA_DR_FLAC_NO_OGG
  73370. ma_dr_flac__free_from_callbacks(pOggbs, &allocationCallbacks);
  73371. #endif
  73372. return NULL;
  73373. }
  73374. ma_dr_flac__init_from_info(pFlac, &init);
  73375. pFlac->allocationCallbacks = allocationCallbacks;
  73376. pFlac->pDecodedSamples = (ma_int32*)ma_dr_flac_align((size_t)pFlac->pExtraData, MA_DR_FLAC_MAX_SIMD_VECTOR_SIZE);
  73377. #ifndef MA_DR_FLAC_NO_OGG
  73378. if (init.container == ma_dr_flac_container_ogg) {
  73379. ma_dr_flac_oggbs* pInternalOggbs = (ma_dr_flac_oggbs*)((ma_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(ma_dr_flac_seekpoint)));
  73380. MA_DR_FLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs));
  73381. ma_dr_flac__free_from_callbacks(pOggbs, &allocationCallbacks);
  73382. pOggbs = NULL;
  73383. pFlac->bs.onRead = ma_dr_flac__on_read_ogg;
  73384. pFlac->bs.onSeek = ma_dr_flac__on_seek_ogg;
  73385. pFlac->bs.pUserData = (void*)pInternalOggbs;
  73386. pFlac->_oggbs = (void*)pInternalOggbs;
  73387. }
  73388. #endif
  73389. pFlac->firstFLACFramePosInBytes = firstFramePos;
  73390. #ifndef MA_DR_FLAC_NO_OGG
  73391. if (init.container == ma_dr_flac_container_ogg)
  73392. {
  73393. pFlac->pSeekpoints = NULL;
  73394. pFlac->seekpointCount = 0;
  73395. }
  73396. else
  73397. #endif
  73398. {
  73399. if (seektablePos != 0) {
  73400. pFlac->seekpointCount = seekpointCount;
  73401. pFlac->pSeekpoints = (ma_dr_flac_seekpoint*)((ma_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
  73402. MA_DR_FLAC_ASSERT(pFlac->bs.onSeek != NULL);
  73403. MA_DR_FLAC_ASSERT(pFlac->bs.onRead != NULL);
  73404. if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, ma_dr_flac_seek_origin_start)) {
  73405. ma_uint32 iSeekpoint;
  73406. for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) {
  73407. if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) == MA_DR_FLAC_SEEKPOINT_SIZE_IN_BYTES) {
  73408. pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = ma_dr_flac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
  73409. pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = ma_dr_flac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
  73410. pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = ma_dr_flac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
  73411. } else {
  73412. pFlac->pSeekpoints = NULL;
  73413. pFlac->seekpointCount = 0;
  73414. break;
  73415. }
  73416. }
  73417. if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, ma_dr_flac_seek_origin_start)) {
  73418. ma_dr_flac__free_from_callbacks(pFlac, &allocationCallbacks);
  73419. return NULL;
  73420. }
  73421. } else {
  73422. pFlac->pSeekpoints = NULL;
  73423. pFlac->seekpointCount = 0;
  73424. }
  73425. }
  73426. }
  73427. if (!init.hasStreamInfoBlock) {
  73428. pFlac->currentFLACFrame.header = init.firstFrameHeader;
  73429. for (;;) {
  73430. ma_result result = ma_dr_flac__decode_flac_frame(pFlac);
  73431. if (result == MA_SUCCESS) {
  73432. break;
  73433. } else {
  73434. if (result == MA_CRC_MISMATCH) {
  73435. if (!ma_dr_flac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  73436. ma_dr_flac__free_from_callbacks(pFlac, &allocationCallbacks);
  73437. return NULL;
  73438. }
  73439. continue;
  73440. } else {
  73441. ma_dr_flac__free_from_callbacks(pFlac, &allocationCallbacks);
  73442. return NULL;
  73443. }
  73444. }
  73445. }
  73446. }
  73447. return pFlac;
  73448. }
  73449. #ifndef MA_DR_FLAC_NO_STDIO
  73450. #include <stdio.h>
  73451. #ifndef MA_DR_FLAC_NO_WCHAR
  73452. #include <wchar.h>
  73453. #endif
  73454. static size_t ma_dr_flac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
  73455. {
  73456. return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
  73457. }
  73458. static ma_bool32 ma_dr_flac__on_seek_stdio(void* pUserData, int offset, ma_dr_flac_seek_origin origin)
  73459. {
  73460. MA_DR_FLAC_ASSERT(offset >= 0);
  73461. return fseek((FILE*)pUserData, offset, (origin == ma_dr_flac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  73462. }
  73463. MA_API ma_dr_flac* ma_dr_flac_open_file(const char* pFileName, const ma_allocation_callbacks* pAllocationCallbacks)
  73464. {
  73465. ma_dr_flac* pFlac;
  73466. FILE* pFile;
  73467. if (ma_fopen(&pFile, pFileName, "rb") != MA_SUCCESS) {
  73468. return NULL;
  73469. }
  73470. pFlac = ma_dr_flac_open(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  73471. if (pFlac == NULL) {
  73472. fclose(pFile);
  73473. return NULL;
  73474. }
  73475. return pFlac;
  73476. }
  73477. #ifndef MA_DR_FLAC_NO_WCHAR
  73478. MA_API ma_dr_flac* ma_dr_flac_open_file_w(const wchar_t* pFileName, const ma_allocation_callbacks* pAllocationCallbacks)
  73479. {
  73480. ma_dr_flac* pFlac;
  73481. FILE* pFile;
  73482. if (ma_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != MA_SUCCESS) {
  73483. return NULL;
  73484. }
  73485. pFlac = ma_dr_flac_open(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  73486. if (pFlac == NULL) {
  73487. fclose(pFile);
  73488. return NULL;
  73489. }
  73490. return pFlac;
  73491. }
  73492. #endif
  73493. MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata(const char* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73494. {
  73495. ma_dr_flac* pFlac;
  73496. FILE* pFile;
  73497. if (ma_fopen(&pFile, pFileName, "rb") != MA_SUCCESS) {
  73498. return NULL;
  73499. }
  73500. pFlac = ma_dr_flac_open_with_metadata_private(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, onMeta, ma_dr_flac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  73501. if (pFlac == NULL) {
  73502. fclose(pFile);
  73503. return pFlac;
  73504. }
  73505. return pFlac;
  73506. }
  73507. #ifndef MA_DR_FLAC_NO_WCHAR
  73508. MA_API ma_dr_flac* ma_dr_flac_open_file_with_metadata_w(const wchar_t* pFileName, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73509. {
  73510. ma_dr_flac* pFlac;
  73511. FILE* pFile;
  73512. if (ma_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != MA_SUCCESS) {
  73513. return NULL;
  73514. }
  73515. pFlac = ma_dr_flac_open_with_metadata_private(ma_dr_flac__on_read_stdio, ma_dr_flac__on_seek_stdio, onMeta, ma_dr_flac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  73516. if (pFlac == NULL) {
  73517. fclose(pFile);
  73518. return pFlac;
  73519. }
  73520. return pFlac;
  73521. }
  73522. #endif
  73523. #endif
  73524. static size_t ma_dr_flac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
  73525. {
  73526. ma_dr_flac__memory_stream* memoryStream = (ma_dr_flac__memory_stream*)pUserData;
  73527. size_t bytesRemaining;
  73528. MA_DR_FLAC_ASSERT(memoryStream != NULL);
  73529. MA_DR_FLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
  73530. bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
  73531. if (bytesToRead > bytesRemaining) {
  73532. bytesToRead = bytesRemaining;
  73533. }
  73534. if (bytesToRead > 0) {
  73535. MA_DR_FLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
  73536. memoryStream->currentReadPos += bytesToRead;
  73537. }
  73538. return bytesToRead;
  73539. }
  73540. static ma_bool32 ma_dr_flac__on_seek_memory(void* pUserData, int offset, ma_dr_flac_seek_origin origin)
  73541. {
  73542. ma_dr_flac__memory_stream* memoryStream = (ma_dr_flac__memory_stream*)pUserData;
  73543. MA_DR_FLAC_ASSERT(memoryStream != NULL);
  73544. MA_DR_FLAC_ASSERT(offset >= 0);
  73545. if (offset > (ma_int64)memoryStream->dataSize) {
  73546. return MA_FALSE;
  73547. }
  73548. if (origin == ma_dr_flac_seek_origin_current) {
  73549. if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) {
  73550. memoryStream->currentReadPos += offset;
  73551. } else {
  73552. return MA_FALSE;
  73553. }
  73554. } else {
  73555. if ((ma_uint32)offset <= memoryStream->dataSize) {
  73556. memoryStream->currentReadPos = offset;
  73557. } else {
  73558. return MA_FALSE;
  73559. }
  73560. }
  73561. return MA_TRUE;
  73562. }
  73563. MA_API ma_dr_flac* ma_dr_flac_open_memory(const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks)
  73564. {
  73565. ma_dr_flac__memory_stream memoryStream;
  73566. ma_dr_flac* pFlac;
  73567. memoryStream.data = (const ma_uint8*)pData;
  73568. memoryStream.dataSize = dataSize;
  73569. memoryStream.currentReadPos = 0;
  73570. pFlac = ma_dr_flac_open(ma_dr_flac__on_read_memory, ma_dr_flac__on_seek_memory, &memoryStream, pAllocationCallbacks);
  73571. if (pFlac == NULL) {
  73572. return NULL;
  73573. }
  73574. pFlac->memoryStream = memoryStream;
  73575. #ifndef MA_DR_FLAC_NO_OGG
  73576. if (pFlac->container == ma_dr_flac_container_ogg)
  73577. {
  73578. ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs;
  73579. oggbs->pUserData = &pFlac->memoryStream;
  73580. }
  73581. else
  73582. #endif
  73583. {
  73584. pFlac->bs.pUserData = &pFlac->memoryStream;
  73585. }
  73586. return pFlac;
  73587. }
  73588. MA_API ma_dr_flac* ma_dr_flac_open_memory_with_metadata(const void* pData, size_t dataSize, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73589. {
  73590. ma_dr_flac__memory_stream memoryStream;
  73591. ma_dr_flac* pFlac;
  73592. memoryStream.data = (const ma_uint8*)pData;
  73593. memoryStream.dataSize = dataSize;
  73594. memoryStream.currentReadPos = 0;
  73595. pFlac = ma_dr_flac_open_with_metadata_private(ma_dr_flac__on_read_memory, ma_dr_flac__on_seek_memory, onMeta, ma_dr_flac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
  73596. if (pFlac == NULL) {
  73597. return NULL;
  73598. }
  73599. pFlac->memoryStream = memoryStream;
  73600. #ifndef MA_DR_FLAC_NO_OGG
  73601. if (pFlac->container == ma_dr_flac_container_ogg)
  73602. {
  73603. ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs;
  73604. oggbs->pUserData = &pFlac->memoryStream;
  73605. }
  73606. else
  73607. #endif
  73608. {
  73609. pFlac->bs.pUserData = &pFlac->memoryStream;
  73610. }
  73611. return pFlac;
  73612. }
  73613. MA_API ma_dr_flac* ma_dr_flac_open(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73614. {
  73615. return ma_dr_flac_open_with_metadata_private(onRead, onSeek, NULL, ma_dr_flac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  73616. }
  73617. MA_API ma_dr_flac* ma_dr_flac_open_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73618. {
  73619. return ma_dr_flac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks);
  73620. }
  73621. MA_API ma_dr_flac* ma_dr_flac_open_with_metadata(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73622. {
  73623. return ma_dr_flac_open_with_metadata_private(onRead, onSeek, onMeta, ma_dr_flac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  73624. }
  73625. MA_API ma_dr_flac* ma_dr_flac_open_with_metadata_relaxed(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, ma_dr_flac_meta_proc onMeta, ma_dr_flac_container container, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  73626. {
  73627. return ma_dr_flac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
  73628. }
  73629. MA_API void ma_dr_flac_close(ma_dr_flac* pFlac)
  73630. {
  73631. if (pFlac == NULL) {
  73632. return;
  73633. }
  73634. #ifndef MA_DR_FLAC_NO_STDIO
  73635. if (pFlac->bs.onRead == ma_dr_flac__on_read_stdio) {
  73636. fclose((FILE*)pFlac->bs.pUserData);
  73637. }
  73638. #ifndef MA_DR_FLAC_NO_OGG
  73639. if (pFlac->container == ma_dr_flac_container_ogg) {
  73640. ma_dr_flac_oggbs* oggbs = (ma_dr_flac_oggbs*)pFlac->_oggbs;
  73641. MA_DR_FLAC_ASSERT(pFlac->bs.onRead == ma_dr_flac__on_read_ogg);
  73642. if (oggbs->onRead == ma_dr_flac__on_read_stdio) {
  73643. fclose((FILE*)oggbs->pUserData);
  73644. }
  73645. }
  73646. #endif
  73647. #endif
  73648. ma_dr_flac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
  73649. }
  73650. #if 0
  73651. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73652. {
  73653. ma_uint64 i;
  73654. for (i = 0; i < frameCount; ++i) {
  73655. ma_uint32 left = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73656. ma_uint32 side = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73657. ma_uint32 right = left - side;
  73658. pOutputSamples[i*2+0] = (ma_int32)left;
  73659. pOutputSamples[i*2+1] = (ma_int32)right;
  73660. }
  73661. }
  73662. #endif
  73663. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73664. {
  73665. ma_uint64 i;
  73666. ma_uint64 frameCount4 = frameCount >> 2;
  73667. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73668. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73669. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73670. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73671. for (i = 0; i < frameCount4; ++i) {
  73672. ma_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  73673. ma_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  73674. ma_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  73675. ma_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  73676. ma_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  73677. ma_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  73678. ma_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  73679. ma_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  73680. ma_uint32 right0 = left0 - side0;
  73681. ma_uint32 right1 = left1 - side1;
  73682. ma_uint32 right2 = left2 - side2;
  73683. ma_uint32 right3 = left3 - side3;
  73684. pOutputSamples[i*8+0] = (ma_int32)left0;
  73685. pOutputSamples[i*8+1] = (ma_int32)right0;
  73686. pOutputSamples[i*8+2] = (ma_int32)left1;
  73687. pOutputSamples[i*8+3] = (ma_int32)right1;
  73688. pOutputSamples[i*8+4] = (ma_int32)left2;
  73689. pOutputSamples[i*8+5] = (ma_int32)right2;
  73690. pOutputSamples[i*8+6] = (ma_int32)left3;
  73691. pOutputSamples[i*8+7] = (ma_int32)right3;
  73692. }
  73693. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73694. ma_uint32 left = pInputSamples0U32[i] << shift0;
  73695. ma_uint32 side = pInputSamples1U32[i] << shift1;
  73696. ma_uint32 right = left - side;
  73697. pOutputSamples[i*2+0] = (ma_int32)left;
  73698. pOutputSamples[i*2+1] = (ma_int32)right;
  73699. }
  73700. }
  73701. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  73702. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73703. {
  73704. ma_uint64 i;
  73705. ma_uint64 frameCount4 = frameCount >> 2;
  73706. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73707. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73708. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73709. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73710. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73711. for (i = 0; i < frameCount4; ++i) {
  73712. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73713. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73714. __m128i right = _mm_sub_epi32(left, side);
  73715. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  73716. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  73717. }
  73718. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73719. ma_uint32 left = pInputSamples0U32[i] << shift0;
  73720. ma_uint32 side = pInputSamples1U32[i] << shift1;
  73721. ma_uint32 right = left - side;
  73722. pOutputSamples[i*2+0] = (ma_int32)left;
  73723. pOutputSamples[i*2+1] = (ma_int32)right;
  73724. }
  73725. }
  73726. #endif
  73727. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  73728. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73729. {
  73730. ma_uint64 i;
  73731. ma_uint64 frameCount4 = frameCount >> 2;
  73732. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73733. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73734. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73735. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73736. int32x4_t shift0_4;
  73737. int32x4_t shift1_4;
  73738. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73739. shift0_4 = vdupq_n_s32(shift0);
  73740. shift1_4 = vdupq_n_s32(shift1);
  73741. for (i = 0; i < frameCount4; ++i) {
  73742. uint32x4_t left;
  73743. uint32x4_t side;
  73744. uint32x4_t right;
  73745. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  73746. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  73747. right = vsubq_u32(left, side);
  73748. ma_dr_flac__vst2q_u32((ma_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  73749. }
  73750. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73751. ma_uint32 left = pInputSamples0U32[i] << shift0;
  73752. ma_uint32 side = pInputSamples1U32[i] << shift1;
  73753. ma_uint32 right = left - side;
  73754. pOutputSamples[i*2+0] = (ma_int32)left;
  73755. pOutputSamples[i*2+1] = (ma_int32)right;
  73756. }
  73757. }
  73758. #endif
  73759. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_left_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73760. {
  73761. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  73762. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73763. ma_dr_flac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73764. } else
  73765. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  73766. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73767. ma_dr_flac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73768. } else
  73769. #endif
  73770. {
  73771. #if 0
  73772. ma_dr_flac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73773. #else
  73774. ma_dr_flac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73775. #endif
  73776. }
  73777. }
  73778. #if 0
  73779. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73780. {
  73781. ma_uint64 i;
  73782. for (i = 0; i < frameCount; ++i) {
  73783. ma_uint32 side = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73784. ma_uint32 right = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73785. ma_uint32 left = right + side;
  73786. pOutputSamples[i*2+0] = (ma_int32)left;
  73787. pOutputSamples[i*2+1] = (ma_int32)right;
  73788. }
  73789. }
  73790. #endif
  73791. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73792. {
  73793. ma_uint64 i;
  73794. ma_uint64 frameCount4 = frameCount >> 2;
  73795. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73796. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73797. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73798. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73799. for (i = 0; i < frameCount4; ++i) {
  73800. ma_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  73801. ma_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  73802. ma_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  73803. ma_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  73804. ma_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  73805. ma_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  73806. ma_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  73807. ma_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  73808. ma_uint32 left0 = right0 + side0;
  73809. ma_uint32 left1 = right1 + side1;
  73810. ma_uint32 left2 = right2 + side2;
  73811. ma_uint32 left3 = right3 + side3;
  73812. pOutputSamples[i*8+0] = (ma_int32)left0;
  73813. pOutputSamples[i*8+1] = (ma_int32)right0;
  73814. pOutputSamples[i*8+2] = (ma_int32)left1;
  73815. pOutputSamples[i*8+3] = (ma_int32)right1;
  73816. pOutputSamples[i*8+4] = (ma_int32)left2;
  73817. pOutputSamples[i*8+5] = (ma_int32)right2;
  73818. pOutputSamples[i*8+6] = (ma_int32)left3;
  73819. pOutputSamples[i*8+7] = (ma_int32)right3;
  73820. }
  73821. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73822. ma_uint32 side = pInputSamples0U32[i] << shift0;
  73823. ma_uint32 right = pInputSamples1U32[i] << shift1;
  73824. ma_uint32 left = right + side;
  73825. pOutputSamples[i*2+0] = (ma_int32)left;
  73826. pOutputSamples[i*2+1] = (ma_int32)right;
  73827. }
  73828. }
  73829. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  73830. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73831. {
  73832. ma_uint64 i;
  73833. ma_uint64 frameCount4 = frameCount >> 2;
  73834. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73835. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73836. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73837. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73838. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73839. for (i = 0; i < frameCount4; ++i) {
  73840. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73841. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73842. __m128i left = _mm_add_epi32(right, side);
  73843. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  73844. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  73845. }
  73846. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73847. ma_uint32 side = pInputSamples0U32[i] << shift0;
  73848. ma_uint32 right = pInputSamples1U32[i] << shift1;
  73849. ma_uint32 left = right + side;
  73850. pOutputSamples[i*2+0] = (ma_int32)left;
  73851. pOutputSamples[i*2+1] = (ma_int32)right;
  73852. }
  73853. }
  73854. #endif
  73855. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  73856. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73857. {
  73858. ma_uint64 i;
  73859. ma_uint64 frameCount4 = frameCount >> 2;
  73860. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73861. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73862. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73863. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73864. int32x4_t shift0_4;
  73865. int32x4_t shift1_4;
  73866. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73867. shift0_4 = vdupq_n_s32(shift0);
  73868. shift1_4 = vdupq_n_s32(shift1);
  73869. for (i = 0; i < frameCount4; ++i) {
  73870. uint32x4_t side;
  73871. uint32x4_t right;
  73872. uint32x4_t left;
  73873. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  73874. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  73875. left = vaddq_u32(right, side);
  73876. ma_dr_flac__vst2q_u32((ma_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  73877. }
  73878. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73879. ma_uint32 side = pInputSamples0U32[i] << shift0;
  73880. ma_uint32 right = pInputSamples1U32[i] << shift1;
  73881. ma_uint32 left = right + side;
  73882. pOutputSamples[i*2+0] = (ma_int32)left;
  73883. pOutputSamples[i*2+1] = (ma_int32)right;
  73884. }
  73885. }
  73886. #endif
  73887. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_right_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73888. {
  73889. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  73890. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73891. ma_dr_flac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73892. } else
  73893. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  73894. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73895. ma_dr_flac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73896. } else
  73897. #endif
  73898. {
  73899. #if 0
  73900. ma_dr_flac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73901. #else
  73902. ma_dr_flac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73903. #endif
  73904. }
  73905. }
  73906. #if 0
  73907. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73908. {
  73909. for (ma_uint64 i = 0; i < frameCount; ++i) {
  73910. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73911. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73912. mid = (mid << 1) | (side & 0x01);
  73913. pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample);
  73914. pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample);
  73915. }
  73916. }
  73917. #endif
  73918. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  73919. {
  73920. ma_uint64 i;
  73921. ma_uint64 frameCount4 = frameCount >> 2;
  73922. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  73923. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  73924. ma_int32 shift = unusedBitsPerSample;
  73925. if (shift > 0) {
  73926. shift -= 1;
  73927. for (i = 0; i < frameCount4; ++i) {
  73928. ma_uint32 temp0L;
  73929. ma_uint32 temp1L;
  73930. ma_uint32 temp2L;
  73931. ma_uint32 temp3L;
  73932. ma_uint32 temp0R;
  73933. ma_uint32 temp1R;
  73934. ma_uint32 temp2R;
  73935. ma_uint32 temp3R;
  73936. ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73937. ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73938. ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73939. ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73940. ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73941. ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73942. ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73943. ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73944. mid0 = (mid0 << 1) | (side0 & 0x01);
  73945. mid1 = (mid1 << 1) | (side1 & 0x01);
  73946. mid2 = (mid2 << 1) | (side2 & 0x01);
  73947. mid3 = (mid3 << 1) | (side3 & 0x01);
  73948. temp0L = (mid0 + side0) << shift;
  73949. temp1L = (mid1 + side1) << shift;
  73950. temp2L = (mid2 + side2) << shift;
  73951. temp3L = (mid3 + side3) << shift;
  73952. temp0R = (mid0 - side0) << shift;
  73953. temp1R = (mid1 - side1) << shift;
  73954. temp2R = (mid2 - side2) << shift;
  73955. temp3R = (mid3 - side3) << shift;
  73956. pOutputSamples[i*8+0] = (ma_int32)temp0L;
  73957. pOutputSamples[i*8+1] = (ma_int32)temp0R;
  73958. pOutputSamples[i*8+2] = (ma_int32)temp1L;
  73959. pOutputSamples[i*8+3] = (ma_int32)temp1R;
  73960. pOutputSamples[i*8+4] = (ma_int32)temp2L;
  73961. pOutputSamples[i*8+5] = (ma_int32)temp2R;
  73962. pOutputSamples[i*8+6] = (ma_int32)temp3L;
  73963. pOutputSamples[i*8+7] = (ma_int32)temp3R;
  73964. }
  73965. } else {
  73966. for (i = 0; i < frameCount4; ++i) {
  73967. ma_uint32 temp0L;
  73968. ma_uint32 temp1L;
  73969. ma_uint32 temp2L;
  73970. ma_uint32 temp3L;
  73971. ma_uint32 temp0R;
  73972. ma_uint32 temp1R;
  73973. ma_uint32 temp2R;
  73974. ma_uint32 temp3R;
  73975. ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73976. ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73977. ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73978. ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73979. ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73980. ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73981. ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73982. ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73983. mid0 = (mid0 << 1) | (side0 & 0x01);
  73984. mid1 = (mid1 << 1) | (side1 & 0x01);
  73985. mid2 = (mid2 << 1) | (side2 & 0x01);
  73986. mid3 = (mid3 << 1) | (side3 & 0x01);
  73987. temp0L = (ma_uint32)((ma_int32)(mid0 + side0) >> 1);
  73988. temp1L = (ma_uint32)((ma_int32)(mid1 + side1) >> 1);
  73989. temp2L = (ma_uint32)((ma_int32)(mid2 + side2) >> 1);
  73990. temp3L = (ma_uint32)((ma_int32)(mid3 + side3) >> 1);
  73991. temp0R = (ma_uint32)((ma_int32)(mid0 - side0) >> 1);
  73992. temp1R = (ma_uint32)((ma_int32)(mid1 - side1) >> 1);
  73993. temp2R = (ma_uint32)((ma_int32)(mid2 - side2) >> 1);
  73994. temp3R = (ma_uint32)((ma_int32)(mid3 - side3) >> 1);
  73995. pOutputSamples[i*8+0] = (ma_int32)temp0L;
  73996. pOutputSamples[i*8+1] = (ma_int32)temp0R;
  73997. pOutputSamples[i*8+2] = (ma_int32)temp1L;
  73998. pOutputSamples[i*8+3] = (ma_int32)temp1R;
  73999. pOutputSamples[i*8+4] = (ma_int32)temp2L;
  74000. pOutputSamples[i*8+5] = (ma_int32)temp2R;
  74001. pOutputSamples[i*8+6] = (ma_int32)temp3L;
  74002. pOutputSamples[i*8+7] = (ma_int32)temp3R;
  74003. }
  74004. }
  74005. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74006. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74007. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74008. mid = (mid << 1) | (side & 0x01);
  74009. pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample);
  74010. pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample);
  74011. }
  74012. }
  74013. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74014. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74015. {
  74016. ma_uint64 i;
  74017. ma_uint64 frameCount4 = frameCount >> 2;
  74018. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74019. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74020. ma_int32 shift = unusedBitsPerSample;
  74021. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74022. if (shift == 0) {
  74023. for (i = 0; i < frameCount4; ++i) {
  74024. __m128i mid;
  74025. __m128i side;
  74026. __m128i left;
  74027. __m128i right;
  74028. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74029. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74030. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74031. left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  74032. right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  74033. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74034. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74035. }
  74036. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74037. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74038. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74039. mid = (mid << 1) | (side & 0x01);
  74040. pOutputSamples[i*2+0] = (ma_int32)(mid + side) >> 1;
  74041. pOutputSamples[i*2+1] = (ma_int32)(mid - side) >> 1;
  74042. }
  74043. } else {
  74044. shift -= 1;
  74045. for (i = 0; i < frameCount4; ++i) {
  74046. __m128i mid;
  74047. __m128i side;
  74048. __m128i left;
  74049. __m128i right;
  74050. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74051. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74052. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74053. left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  74054. right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  74055. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74056. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74057. }
  74058. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74059. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74060. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74061. mid = (mid << 1) | (side & 0x01);
  74062. pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift);
  74063. pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift);
  74064. }
  74065. }
  74066. }
  74067. #endif
  74068. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  74069. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74070. {
  74071. ma_uint64 i;
  74072. ma_uint64 frameCount4 = frameCount >> 2;
  74073. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74074. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74075. ma_int32 shift = unusedBitsPerSample;
  74076. int32x4_t wbpsShift0_4;
  74077. int32x4_t wbpsShift1_4;
  74078. uint32x4_t one4;
  74079. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74080. wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74081. wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74082. one4 = vdupq_n_u32(1);
  74083. if (shift == 0) {
  74084. for (i = 0; i < frameCount4; ++i) {
  74085. uint32x4_t mid;
  74086. uint32x4_t side;
  74087. int32x4_t left;
  74088. int32x4_t right;
  74089. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  74090. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  74091. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  74092. left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  74093. right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  74094. ma_dr_flac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  74095. }
  74096. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74097. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74098. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74099. mid = (mid << 1) | (side & 0x01);
  74100. pOutputSamples[i*2+0] = (ma_int32)(mid + side) >> 1;
  74101. pOutputSamples[i*2+1] = (ma_int32)(mid - side) >> 1;
  74102. }
  74103. } else {
  74104. int32x4_t shift4;
  74105. shift -= 1;
  74106. shift4 = vdupq_n_s32(shift);
  74107. for (i = 0; i < frameCount4; ++i) {
  74108. uint32x4_t mid;
  74109. uint32x4_t side;
  74110. int32x4_t left;
  74111. int32x4_t right;
  74112. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  74113. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  74114. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  74115. left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  74116. right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  74117. ma_dr_flac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  74118. }
  74119. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74120. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74121. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74122. mid = (mid << 1) | (side & 0x01);
  74123. pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift);
  74124. pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift);
  74125. }
  74126. }
  74127. }
  74128. #endif
  74129. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_mid_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74130. {
  74131. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74132. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74133. ma_dr_flac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74134. } else
  74135. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  74136. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74137. ma_dr_flac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74138. } else
  74139. #endif
  74140. {
  74141. #if 0
  74142. ma_dr_flac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74143. #else
  74144. ma_dr_flac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74145. #endif
  74146. }
  74147. }
  74148. #if 0
  74149. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74150. {
  74151. for (ma_uint64 i = 0; i < frameCount; ++i) {
  74152. pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
  74153. pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
  74154. }
  74155. }
  74156. #endif
  74157. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74158. {
  74159. ma_uint64 i;
  74160. ma_uint64 frameCount4 = frameCount >> 2;
  74161. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74162. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74163. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74164. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74165. for (i = 0; i < frameCount4; ++i) {
  74166. ma_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  74167. ma_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  74168. ma_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  74169. ma_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  74170. ma_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  74171. ma_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  74172. ma_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  74173. ma_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  74174. pOutputSamples[i*8+0] = (ma_int32)tempL0;
  74175. pOutputSamples[i*8+1] = (ma_int32)tempR0;
  74176. pOutputSamples[i*8+2] = (ma_int32)tempL1;
  74177. pOutputSamples[i*8+3] = (ma_int32)tempR1;
  74178. pOutputSamples[i*8+4] = (ma_int32)tempL2;
  74179. pOutputSamples[i*8+5] = (ma_int32)tempR2;
  74180. pOutputSamples[i*8+6] = (ma_int32)tempL3;
  74181. pOutputSamples[i*8+7] = (ma_int32)tempR3;
  74182. }
  74183. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74184. pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0);
  74185. pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1);
  74186. }
  74187. }
  74188. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74189. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74190. {
  74191. ma_uint64 i;
  74192. ma_uint64 frameCount4 = frameCount >> 2;
  74193. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74194. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74195. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74196. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74197. for (i = 0; i < frameCount4; ++i) {
  74198. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74199. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74200. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  74201. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  74202. }
  74203. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74204. pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0);
  74205. pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1);
  74206. }
  74207. }
  74208. #endif
  74209. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  74210. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74211. {
  74212. ma_uint64 i;
  74213. ma_uint64 frameCount4 = frameCount >> 2;
  74214. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74215. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74216. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74217. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74218. int32x4_t shift4_0 = vdupq_n_s32(shift0);
  74219. int32x4_t shift4_1 = vdupq_n_s32(shift1);
  74220. for (i = 0; i < frameCount4; ++i) {
  74221. int32x4_t left;
  74222. int32x4_t right;
  74223. left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
  74224. right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
  74225. ma_dr_flac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  74226. }
  74227. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74228. pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0);
  74229. pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1);
  74230. }
  74231. }
  74232. #endif
  74233. static MA_INLINE void ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int32* pOutputSamples)
  74234. {
  74235. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74236. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74237. ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74238. } else
  74239. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  74240. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74241. ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74242. } else
  74243. #endif
  74244. {
  74245. #if 0
  74246. ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74247. #else
  74248. ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74249. #endif
  74250. }
  74251. }
  74252. MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s32(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int32* pBufferOut)
  74253. {
  74254. ma_uint64 framesRead;
  74255. ma_uint32 unusedBitsPerSample;
  74256. if (pFlac == NULL || framesToRead == 0) {
  74257. return 0;
  74258. }
  74259. if (pBufferOut == NULL) {
  74260. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  74261. }
  74262. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 32);
  74263. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  74264. framesRead = 0;
  74265. while (framesToRead > 0) {
  74266. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  74267. if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) {
  74268. break;
  74269. }
  74270. } else {
  74271. unsigned int channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  74272. ma_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  74273. ma_uint64 frameCountThisIteration = framesToRead;
  74274. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  74275. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  74276. }
  74277. if (channelCount == 2) {
  74278. const ma_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  74279. const ma_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  74280. switch (pFlac->currentFLACFrame.header.channelAssignment)
  74281. {
  74282. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  74283. {
  74284. ma_dr_flac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74285. } break;
  74286. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  74287. {
  74288. ma_dr_flac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74289. } break;
  74290. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  74291. {
  74292. ma_dr_flac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74293. } break;
  74294. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  74295. default:
  74296. {
  74297. ma_dr_flac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74298. } break;
  74299. }
  74300. } else {
  74301. ma_uint64 i;
  74302. for (i = 0; i < frameCountThisIteration; ++i) {
  74303. unsigned int j;
  74304. for (j = 0; j < channelCount; ++j) {
  74305. pBufferOut[(i*channelCount)+j] = (ma_int32)((ma_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  74306. }
  74307. }
  74308. }
  74309. framesRead += frameCountThisIteration;
  74310. pBufferOut += frameCountThisIteration * channelCount;
  74311. framesToRead -= frameCountThisIteration;
  74312. pFlac->currentPCMFrame += frameCountThisIteration;
  74313. pFlac->currentFLACFrame.pcmFramesRemaining -= (ma_uint32)frameCountThisIteration;
  74314. }
  74315. }
  74316. return framesRead;
  74317. }
  74318. #if 0
  74319. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74320. {
  74321. ma_uint64 i;
  74322. for (i = 0; i < frameCount; ++i) {
  74323. ma_uint32 left = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74324. ma_uint32 side = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74325. ma_uint32 right = left - side;
  74326. left >>= 16;
  74327. right >>= 16;
  74328. pOutputSamples[i*2+0] = (ma_int16)left;
  74329. pOutputSamples[i*2+1] = (ma_int16)right;
  74330. }
  74331. }
  74332. #endif
  74333. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74334. {
  74335. ma_uint64 i;
  74336. ma_uint64 frameCount4 = frameCount >> 2;
  74337. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74338. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74339. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74340. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74341. for (i = 0; i < frameCount4; ++i) {
  74342. ma_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  74343. ma_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  74344. ma_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  74345. ma_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  74346. ma_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  74347. ma_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  74348. ma_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  74349. ma_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  74350. ma_uint32 right0 = left0 - side0;
  74351. ma_uint32 right1 = left1 - side1;
  74352. ma_uint32 right2 = left2 - side2;
  74353. ma_uint32 right3 = left3 - side3;
  74354. left0 >>= 16;
  74355. left1 >>= 16;
  74356. left2 >>= 16;
  74357. left3 >>= 16;
  74358. right0 >>= 16;
  74359. right1 >>= 16;
  74360. right2 >>= 16;
  74361. right3 >>= 16;
  74362. pOutputSamples[i*8+0] = (ma_int16)left0;
  74363. pOutputSamples[i*8+1] = (ma_int16)right0;
  74364. pOutputSamples[i*8+2] = (ma_int16)left1;
  74365. pOutputSamples[i*8+3] = (ma_int16)right1;
  74366. pOutputSamples[i*8+4] = (ma_int16)left2;
  74367. pOutputSamples[i*8+5] = (ma_int16)right2;
  74368. pOutputSamples[i*8+6] = (ma_int16)left3;
  74369. pOutputSamples[i*8+7] = (ma_int16)right3;
  74370. }
  74371. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74372. ma_uint32 left = pInputSamples0U32[i] << shift0;
  74373. ma_uint32 side = pInputSamples1U32[i] << shift1;
  74374. ma_uint32 right = left - side;
  74375. left >>= 16;
  74376. right >>= 16;
  74377. pOutputSamples[i*2+0] = (ma_int16)left;
  74378. pOutputSamples[i*2+1] = (ma_int16)right;
  74379. }
  74380. }
  74381. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74382. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74383. {
  74384. ma_uint64 i;
  74385. ma_uint64 frameCount4 = frameCount >> 2;
  74386. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74387. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74388. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74389. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74390. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74391. for (i = 0; i < frameCount4; ++i) {
  74392. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74393. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74394. __m128i right = _mm_sub_epi32(left, side);
  74395. left = _mm_srai_epi32(left, 16);
  74396. right = _mm_srai_epi32(right, 16);
  74397. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right));
  74398. }
  74399. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74400. ma_uint32 left = pInputSamples0U32[i] << shift0;
  74401. ma_uint32 side = pInputSamples1U32[i] << shift1;
  74402. ma_uint32 right = left - side;
  74403. left >>= 16;
  74404. right >>= 16;
  74405. pOutputSamples[i*2+0] = (ma_int16)left;
  74406. pOutputSamples[i*2+1] = (ma_int16)right;
  74407. }
  74408. }
  74409. #endif
  74410. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  74411. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74412. {
  74413. ma_uint64 i;
  74414. ma_uint64 frameCount4 = frameCount >> 2;
  74415. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74416. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74417. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74418. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74419. int32x4_t shift0_4;
  74420. int32x4_t shift1_4;
  74421. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74422. shift0_4 = vdupq_n_s32(shift0);
  74423. shift1_4 = vdupq_n_s32(shift1);
  74424. for (i = 0; i < frameCount4; ++i) {
  74425. uint32x4_t left;
  74426. uint32x4_t side;
  74427. uint32x4_t right;
  74428. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  74429. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  74430. right = vsubq_u32(left, side);
  74431. left = vshrq_n_u32(left, 16);
  74432. right = vshrq_n_u32(right, 16);
  74433. ma_dr_flac__vst2q_u16((ma_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  74434. }
  74435. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74436. ma_uint32 left = pInputSamples0U32[i] << shift0;
  74437. ma_uint32 side = pInputSamples1U32[i] << shift1;
  74438. ma_uint32 right = left - side;
  74439. left >>= 16;
  74440. right >>= 16;
  74441. pOutputSamples[i*2+0] = (ma_int16)left;
  74442. pOutputSamples[i*2+1] = (ma_int16)right;
  74443. }
  74444. }
  74445. #endif
  74446. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_left_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74447. {
  74448. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74449. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74450. ma_dr_flac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74451. } else
  74452. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  74453. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74454. ma_dr_flac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74455. } else
  74456. #endif
  74457. {
  74458. #if 0
  74459. ma_dr_flac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74460. #else
  74461. ma_dr_flac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74462. #endif
  74463. }
  74464. }
  74465. #if 0
  74466. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74467. {
  74468. ma_uint64 i;
  74469. for (i = 0; i < frameCount; ++i) {
  74470. ma_uint32 side = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74471. ma_uint32 right = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74472. ma_uint32 left = right + side;
  74473. left >>= 16;
  74474. right >>= 16;
  74475. pOutputSamples[i*2+0] = (ma_int16)left;
  74476. pOutputSamples[i*2+1] = (ma_int16)right;
  74477. }
  74478. }
  74479. #endif
  74480. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74481. {
  74482. ma_uint64 i;
  74483. ma_uint64 frameCount4 = frameCount >> 2;
  74484. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74485. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74486. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74487. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74488. for (i = 0; i < frameCount4; ++i) {
  74489. ma_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  74490. ma_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  74491. ma_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  74492. ma_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  74493. ma_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  74494. ma_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  74495. ma_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  74496. ma_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  74497. ma_uint32 left0 = right0 + side0;
  74498. ma_uint32 left1 = right1 + side1;
  74499. ma_uint32 left2 = right2 + side2;
  74500. ma_uint32 left3 = right3 + side3;
  74501. left0 >>= 16;
  74502. left1 >>= 16;
  74503. left2 >>= 16;
  74504. left3 >>= 16;
  74505. right0 >>= 16;
  74506. right1 >>= 16;
  74507. right2 >>= 16;
  74508. right3 >>= 16;
  74509. pOutputSamples[i*8+0] = (ma_int16)left0;
  74510. pOutputSamples[i*8+1] = (ma_int16)right0;
  74511. pOutputSamples[i*8+2] = (ma_int16)left1;
  74512. pOutputSamples[i*8+3] = (ma_int16)right1;
  74513. pOutputSamples[i*8+4] = (ma_int16)left2;
  74514. pOutputSamples[i*8+5] = (ma_int16)right2;
  74515. pOutputSamples[i*8+6] = (ma_int16)left3;
  74516. pOutputSamples[i*8+7] = (ma_int16)right3;
  74517. }
  74518. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74519. ma_uint32 side = pInputSamples0U32[i] << shift0;
  74520. ma_uint32 right = pInputSamples1U32[i] << shift1;
  74521. ma_uint32 left = right + side;
  74522. left >>= 16;
  74523. right >>= 16;
  74524. pOutputSamples[i*2+0] = (ma_int16)left;
  74525. pOutputSamples[i*2+1] = (ma_int16)right;
  74526. }
  74527. }
  74528. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74529. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74530. {
  74531. ma_uint64 i;
  74532. ma_uint64 frameCount4 = frameCount >> 2;
  74533. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74534. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74535. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74536. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74537. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74538. for (i = 0; i < frameCount4; ++i) {
  74539. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74540. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74541. __m128i left = _mm_add_epi32(right, side);
  74542. left = _mm_srai_epi32(left, 16);
  74543. right = _mm_srai_epi32(right, 16);
  74544. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right));
  74545. }
  74546. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74547. ma_uint32 side = pInputSamples0U32[i] << shift0;
  74548. ma_uint32 right = pInputSamples1U32[i] << shift1;
  74549. ma_uint32 left = right + side;
  74550. left >>= 16;
  74551. right >>= 16;
  74552. pOutputSamples[i*2+0] = (ma_int16)left;
  74553. pOutputSamples[i*2+1] = (ma_int16)right;
  74554. }
  74555. }
  74556. #endif
  74557. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  74558. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74559. {
  74560. ma_uint64 i;
  74561. ma_uint64 frameCount4 = frameCount >> 2;
  74562. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74563. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74564. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74565. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74566. int32x4_t shift0_4;
  74567. int32x4_t shift1_4;
  74568. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74569. shift0_4 = vdupq_n_s32(shift0);
  74570. shift1_4 = vdupq_n_s32(shift1);
  74571. for (i = 0; i < frameCount4; ++i) {
  74572. uint32x4_t side;
  74573. uint32x4_t right;
  74574. uint32x4_t left;
  74575. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  74576. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  74577. left = vaddq_u32(right, side);
  74578. left = vshrq_n_u32(left, 16);
  74579. right = vshrq_n_u32(right, 16);
  74580. ma_dr_flac__vst2q_u16((ma_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  74581. }
  74582. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74583. ma_uint32 side = pInputSamples0U32[i] << shift0;
  74584. ma_uint32 right = pInputSamples1U32[i] << shift1;
  74585. ma_uint32 left = right + side;
  74586. left >>= 16;
  74587. right >>= 16;
  74588. pOutputSamples[i*2+0] = (ma_int16)left;
  74589. pOutputSamples[i*2+1] = (ma_int16)right;
  74590. }
  74591. }
  74592. #endif
  74593. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_right_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74594. {
  74595. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74596. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74597. ma_dr_flac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74598. } else
  74599. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  74600. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74601. ma_dr_flac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74602. } else
  74603. #endif
  74604. {
  74605. #if 0
  74606. ma_dr_flac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74607. #else
  74608. ma_dr_flac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74609. #endif
  74610. }
  74611. }
  74612. #if 0
  74613. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74614. {
  74615. for (ma_uint64 i = 0; i < frameCount; ++i) {
  74616. ma_uint32 mid = (ma_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74617. ma_uint32 side = (ma_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74618. mid = (mid << 1) | (side & 0x01);
  74619. pOutputSamples[i*2+0] = (ma_int16)(((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  74620. pOutputSamples[i*2+1] = (ma_int16)(((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  74621. }
  74622. }
  74623. #endif
  74624. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74625. {
  74626. ma_uint64 i;
  74627. ma_uint64 frameCount4 = frameCount >> 2;
  74628. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74629. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74630. ma_uint32 shift = unusedBitsPerSample;
  74631. if (shift > 0) {
  74632. shift -= 1;
  74633. for (i = 0; i < frameCount4; ++i) {
  74634. ma_uint32 temp0L;
  74635. ma_uint32 temp1L;
  74636. ma_uint32 temp2L;
  74637. ma_uint32 temp3L;
  74638. ma_uint32 temp0R;
  74639. ma_uint32 temp1R;
  74640. ma_uint32 temp2R;
  74641. ma_uint32 temp3R;
  74642. ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74643. ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74644. ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74645. ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74646. ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74647. ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74648. ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74649. ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74650. mid0 = (mid0 << 1) | (side0 & 0x01);
  74651. mid1 = (mid1 << 1) | (side1 & 0x01);
  74652. mid2 = (mid2 << 1) | (side2 & 0x01);
  74653. mid3 = (mid3 << 1) | (side3 & 0x01);
  74654. temp0L = (mid0 + side0) << shift;
  74655. temp1L = (mid1 + side1) << shift;
  74656. temp2L = (mid2 + side2) << shift;
  74657. temp3L = (mid3 + side3) << shift;
  74658. temp0R = (mid0 - side0) << shift;
  74659. temp1R = (mid1 - side1) << shift;
  74660. temp2R = (mid2 - side2) << shift;
  74661. temp3R = (mid3 - side3) << shift;
  74662. temp0L >>= 16;
  74663. temp1L >>= 16;
  74664. temp2L >>= 16;
  74665. temp3L >>= 16;
  74666. temp0R >>= 16;
  74667. temp1R >>= 16;
  74668. temp2R >>= 16;
  74669. temp3R >>= 16;
  74670. pOutputSamples[i*8+0] = (ma_int16)temp0L;
  74671. pOutputSamples[i*8+1] = (ma_int16)temp0R;
  74672. pOutputSamples[i*8+2] = (ma_int16)temp1L;
  74673. pOutputSamples[i*8+3] = (ma_int16)temp1R;
  74674. pOutputSamples[i*8+4] = (ma_int16)temp2L;
  74675. pOutputSamples[i*8+5] = (ma_int16)temp2R;
  74676. pOutputSamples[i*8+6] = (ma_int16)temp3L;
  74677. pOutputSamples[i*8+7] = (ma_int16)temp3R;
  74678. }
  74679. } else {
  74680. for (i = 0; i < frameCount4; ++i) {
  74681. ma_uint32 temp0L;
  74682. ma_uint32 temp1L;
  74683. ma_uint32 temp2L;
  74684. ma_uint32 temp3L;
  74685. ma_uint32 temp0R;
  74686. ma_uint32 temp1R;
  74687. ma_uint32 temp2R;
  74688. ma_uint32 temp3R;
  74689. ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74690. ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74691. ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74692. ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74693. ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74694. ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74695. ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74696. ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74697. mid0 = (mid0 << 1) | (side0 & 0x01);
  74698. mid1 = (mid1 << 1) | (side1 & 0x01);
  74699. mid2 = (mid2 << 1) | (side2 & 0x01);
  74700. mid3 = (mid3 << 1) | (side3 & 0x01);
  74701. temp0L = ((ma_int32)(mid0 + side0) >> 1);
  74702. temp1L = ((ma_int32)(mid1 + side1) >> 1);
  74703. temp2L = ((ma_int32)(mid2 + side2) >> 1);
  74704. temp3L = ((ma_int32)(mid3 + side3) >> 1);
  74705. temp0R = ((ma_int32)(mid0 - side0) >> 1);
  74706. temp1R = ((ma_int32)(mid1 - side1) >> 1);
  74707. temp2R = ((ma_int32)(mid2 - side2) >> 1);
  74708. temp3R = ((ma_int32)(mid3 - side3) >> 1);
  74709. temp0L >>= 16;
  74710. temp1L >>= 16;
  74711. temp2L >>= 16;
  74712. temp3L >>= 16;
  74713. temp0R >>= 16;
  74714. temp1R >>= 16;
  74715. temp2R >>= 16;
  74716. temp3R >>= 16;
  74717. pOutputSamples[i*8+0] = (ma_int16)temp0L;
  74718. pOutputSamples[i*8+1] = (ma_int16)temp0R;
  74719. pOutputSamples[i*8+2] = (ma_int16)temp1L;
  74720. pOutputSamples[i*8+3] = (ma_int16)temp1R;
  74721. pOutputSamples[i*8+4] = (ma_int16)temp2L;
  74722. pOutputSamples[i*8+5] = (ma_int16)temp2R;
  74723. pOutputSamples[i*8+6] = (ma_int16)temp3L;
  74724. pOutputSamples[i*8+7] = (ma_int16)temp3R;
  74725. }
  74726. }
  74727. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74728. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74729. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74730. mid = (mid << 1) | (side & 0x01);
  74731. pOutputSamples[i*2+0] = (ma_int16)(((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  74732. pOutputSamples[i*2+1] = (ma_int16)(((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  74733. }
  74734. }
  74735. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74736. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74737. {
  74738. ma_uint64 i;
  74739. ma_uint64 frameCount4 = frameCount >> 2;
  74740. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74741. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74742. ma_uint32 shift = unusedBitsPerSample;
  74743. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74744. if (shift == 0) {
  74745. for (i = 0; i < frameCount4; ++i) {
  74746. __m128i mid;
  74747. __m128i side;
  74748. __m128i left;
  74749. __m128i right;
  74750. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74751. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74752. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74753. left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  74754. right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  74755. left = _mm_srai_epi32(left, 16);
  74756. right = _mm_srai_epi32(right, 16);
  74757. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right));
  74758. }
  74759. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74760. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74761. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74762. mid = (mid << 1) | (side & 0x01);
  74763. pOutputSamples[i*2+0] = (ma_int16)(((ma_int32)(mid + side) >> 1) >> 16);
  74764. pOutputSamples[i*2+1] = (ma_int16)(((ma_int32)(mid - side) >> 1) >> 16);
  74765. }
  74766. } else {
  74767. shift -= 1;
  74768. for (i = 0; i < frameCount4; ++i) {
  74769. __m128i mid;
  74770. __m128i side;
  74771. __m128i left;
  74772. __m128i right;
  74773. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74774. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74775. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74776. left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  74777. right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  74778. left = _mm_srai_epi32(left, 16);
  74779. right = _mm_srai_epi32(right, 16);
  74780. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right));
  74781. }
  74782. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74783. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74784. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74785. mid = (mid << 1) | (side & 0x01);
  74786. pOutputSamples[i*2+0] = (ma_int16)(((mid + side) << shift) >> 16);
  74787. pOutputSamples[i*2+1] = (ma_int16)(((mid - side) << shift) >> 16);
  74788. }
  74789. }
  74790. }
  74791. #endif
  74792. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  74793. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74794. {
  74795. ma_uint64 i;
  74796. ma_uint64 frameCount4 = frameCount >> 2;
  74797. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74798. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74799. ma_uint32 shift = unusedBitsPerSample;
  74800. int32x4_t wbpsShift0_4;
  74801. int32x4_t wbpsShift1_4;
  74802. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74803. wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74804. wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74805. if (shift == 0) {
  74806. for (i = 0; i < frameCount4; ++i) {
  74807. uint32x4_t mid;
  74808. uint32x4_t side;
  74809. int32x4_t left;
  74810. int32x4_t right;
  74811. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  74812. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  74813. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  74814. left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  74815. right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  74816. left = vshrq_n_s32(left, 16);
  74817. right = vshrq_n_s32(right, 16);
  74818. ma_dr_flac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  74819. }
  74820. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74821. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74822. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74823. mid = (mid << 1) | (side & 0x01);
  74824. pOutputSamples[i*2+0] = (ma_int16)(((ma_int32)(mid + side) >> 1) >> 16);
  74825. pOutputSamples[i*2+1] = (ma_int16)(((ma_int32)(mid - side) >> 1) >> 16);
  74826. }
  74827. } else {
  74828. int32x4_t shift4;
  74829. shift -= 1;
  74830. shift4 = vdupq_n_s32(shift);
  74831. for (i = 0; i < frameCount4; ++i) {
  74832. uint32x4_t mid;
  74833. uint32x4_t side;
  74834. int32x4_t left;
  74835. int32x4_t right;
  74836. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  74837. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  74838. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  74839. left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  74840. right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  74841. left = vshrq_n_s32(left, 16);
  74842. right = vshrq_n_s32(right, 16);
  74843. ma_dr_flac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  74844. }
  74845. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74846. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74847. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74848. mid = (mid << 1) | (side & 0x01);
  74849. pOutputSamples[i*2+0] = (ma_int16)(((mid + side) << shift) >> 16);
  74850. pOutputSamples[i*2+1] = (ma_int16)(((mid - side) << shift) >> 16);
  74851. }
  74852. }
  74853. }
  74854. #endif
  74855. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_mid_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74856. {
  74857. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74858. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74859. ma_dr_flac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74860. } else
  74861. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  74862. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74863. ma_dr_flac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74864. } else
  74865. #endif
  74866. {
  74867. #if 0
  74868. ma_dr_flac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74869. #else
  74870. ma_dr_flac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74871. #endif
  74872. }
  74873. }
  74874. #if 0
  74875. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74876. {
  74877. for (ma_uint64 i = 0; i < frameCount; ++i) {
  74878. pOutputSamples[i*2+0] = (ma_int16)((ma_int32)((ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
  74879. pOutputSamples[i*2+1] = (ma_int16)((ma_int32)((ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
  74880. }
  74881. }
  74882. #endif
  74883. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74884. {
  74885. ma_uint64 i;
  74886. ma_uint64 frameCount4 = frameCount >> 2;
  74887. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74888. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74889. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74890. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74891. for (i = 0; i < frameCount4; ++i) {
  74892. ma_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  74893. ma_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  74894. ma_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  74895. ma_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  74896. ma_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  74897. ma_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  74898. ma_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  74899. ma_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  74900. tempL0 >>= 16;
  74901. tempL1 >>= 16;
  74902. tempL2 >>= 16;
  74903. tempL3 >>= 16;
  74904. tempR0 >>= 16;
  74905. tempR1 >>= 16;
  74906. tempR2 >>= 16;
  74907. tempR3 >>= 16;
  74908. pOutputSamples[i*8+0] = (ma_int16)tempL0;
  74909. pOutputSamples[i*8+1] = (ma_int16)tempR0;
  74910. pOutputSamples[i*8+2] = (ma_int16)tempL1;
  74911. pOutputSamples[i*8+3] = (ma_int16)tempR1;
  74912. pOutputSamples[i*8+4] = (ma_int16)tempL2;
  74913. pOutputSamples[i*8+5] = (ma_int16)tempR2;
  74914. pOutputSamples[i*8+6] = (ma_int16)tempL3;
  74915. pOutputSamples[i*8+7] = (ma_int16)tempR3;
  74916. }
  74917. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74918. pOutputSamples[i*2+0] = (ma_int16)((pInputSamples0U32[i] << shift0) >> 16);
  74919. pOutputSamples[i*2+1] = (ma_int16)((pInputSamples1U32[i] << shift1) >> 16);
  74920. }
  74921. }
  74922. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74923. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74924. {
  74925. ma_uint64 i;
  74926. ma_uint64 frameCount4 = frameCount >> 2;
  74927. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74928. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74929. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74930. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74931. for (i = 0; i < frameCount4; ++i) {
  74932. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74933. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74934. left = _mm_srai_epi32(left, 16);
  74935. right = _mm_srai_epi32(right, 16);
  74936. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), ma_dr_flac__mm_packs_interleaved_epi32(left, right));
  74937. }
  74938. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74939. pOutputSamples[i*2+0] = (ma_int16)((pInputSamples0U32[i] << shift0) >> 16);
  74940. pOutputSamples[i*2+1] = (ma_int16)((pInputSamples1U32[i] << shift1) >> 16);
  74941. }
  74942. }
  74943. #endif
  74944. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  74945. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74946. {
  74947. ma_uint64 i;
  74948. ma_uint64 frameCount4 = frameCount >> 2;
  74949. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  74950. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  74951. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74952. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74953. int32x4_t shift0_4 = vdupq_n_s32(shift0);
  74954. int32x4_t shift1_4 = vdupq_n_s32(shift1);
  74955. for (i = 0; i < frameCount4; ++i) {
  74956. int32x4_t left;
  74957. int32x4_t right;
  74958. left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  74959. right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  74960. left = vshrq_n_s32(left, 16);
  74961. right = vshrq_n_s32(right, 16);
  74962. ma_dr_flac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  74963. }
  74964. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74965. pOutputSamples[i*2+0] = (ma_int16)((pInputSamples0U32[i] << shift0) >> 16);
  74966. pOutputSamples[i*2+1] = (ma_int16)((pInputSamples1U32[i] << shift1) >> 16);
  74967. }
  74968. }
  74969. #endif
  74970. static MA_INLINE void ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, ma_int16* pOutputSamples)
  74971. {
  74972. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  74973. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74974. ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74975. } else
  74976. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  74977. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74978. ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74979. } else
  74980. #endif
  74981. {
  74982. #if 0
  74983. ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74984. #else
  74985. ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74986. #endif
  74987. }
  74988. }
  74989. MA_API ma_uint64 ma_dr_flac_read_pcm_frames_s16(ma_dr_flac* pFlac, ma_uint64 framesToRead, ma_int16* pBufferOut)
  74990. {
  74991. ma_uint64 framesRead;
  74992. ma_uint32 unusedBitsPerSample;
  74993. if (pFlac == NULL || framesToRead == 0) {
  74994. return 0;
  74995. }
  74996. if (pBufferOut == NULL) {
  74997. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  74998. }
  74999. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 32);
  75000. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  75001. framesRead = 0;
  75002. while (framesToRead > 0) {
  75003. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  75004. if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) {
  75005. break;
  75006. }
  75007. } else {
  75008. unsigned int channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  75009. ma_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  75010. ma_uint64 frameCountThisIteration = framesToRead;
  75011. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  75012. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  75013. }
  75014. if (channelCount == 2) {
  75015. const ma_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  75016. const ma_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  75017. switch (pFlac->currentFLACFrame.header.channelAssignment)
  75018. {
  75019. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  75020. {
  75021. ma_dr_flac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75022. } break;
  75023. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  75024. {
  75025. ma_dr_flac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75026. } break;
  75027. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  75028. {
  75029. ma_dr_flac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75030. } break;
  75031. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  75032. default:
  75033. {
  75034. ma_dr_flac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75035. } break;
  75036. }
  75037. } else {
  75038. ma_uint64 i;
  75039. for (i = 0; i < frameCountThisIteration; ++i) {
  75040. unsigned int j;
  75041. for (j = 0; j < channelCount; ++j) {
  75042. ma_int32 sampleS32 = (ma_int32)((ma_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  75043. pBufferOut[(i*channelCount)+j] = (ma_int16)(sampleS32 >> 16);
  75044. }
  75045. }
  75046. }
  75047. framesRead += frameCountThisIteration;
  75048. pBufferOut += frameCountThisIteration * channelCount;
  75049. framesToRead -= frameCountThisIteration;
  75050. pFlac->currentPCMFrame += frameCountThisIteration;
  75051. pFlac->currentFLACFrame.pcmFramesRemaining -= (ma_uint32)frameCountThisIteration;
  75052. }
  75053. }
  75054. return framesRead;
  75055. }
  75056. #if 0
  75057. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75058. {
  75059. ma_uint64 i;
  75060. for (i = 0; i < frameCount; ++i) {
  75061. ma_uint32 left = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75062. ma_uint32 side = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75063. ma_uint32 right = left - side;
  75064. pOutputSamples[i*2+0] = (float)((ma_int32)left / 2147483648.0);
  75065. pOutputSamples[i*2+1] = (float)((ma_int32)right / 2147483648.0);
  75066. }
  75067. }
  75068. #endif
  75069. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75070. {
  75071. ma_uint64 i;
  75072. ma_uint64 frameCount4 = frameCount >> 2;
  75073. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75074. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75075. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75076. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75077. float factor = 1 / 2147483648.0;
  75078. for (i = 0; i < frameCount4; ++i) {
  75079. ma_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  75080. ma_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  75081. ma_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  75082. ma_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  75083. ma_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  75084. ma_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  75085. ma_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  75086. ma_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  75087. ma_uint32 right0 = left0 - side0;
  75088. ma_uint32 right1 = left1 - side1;
  75089. ma_uint32 right2 = left2 - side2;
  75090. ma_uint32 right3 = left3 - side3;
  75091. pOutputSamples[i*8+0] = (ma_int32)left0 * factor;
  75092. pOutputSamples[i*8+1] = (ma_int32)right0 * factor;
  75093. pOutputSamples[i*8+2] = (ma_int32)left1 * factor;
  75094. pOutputSamples[i*8+3] = (ma_int32)right1 * factor;
  75095. pOutputSamples[i*8+4] = (ma_int32)left2 * factor;
  75096. pOutputSamples[i*8+5] = (ma_int32)right2 * factor;
  75097. pOutputSamples[i*8+6] = (ma_int32)left3 * factor;
  75098. pOutputSamples[i*8+7] = (ma_int32)right3 * factor;
  75099. }
  75100. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75101. ma_uint32 left = pInputSamples0U32[i] << shift0;
  75102. ma_uint32 side = pInputSamples1U32[i] << shift1;
  75103. ma_uint32 right = left - side;
  75104. pOutputSamples[i*2+0] = (ma_int32)left * factor;
  75105. pOutputSamples[i*2+1] = (ma_int32)right * factor;
  75106. }
  75107. }
  75108. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75109. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75110. {
  75111. ma_uint64 i;
  75112. ma_uint64 frameCount4 = frameCount >> 2;
  75113. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75114. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75115. ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75116. ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75117. __m128 factor;
  75118. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75119. factor = _mm_set1_ps(1.0f / 8388608.0f);
  75120. for (i = 0; i < frameCount4; ++i) {
  75121. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  75122. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  75123. __m128i right = _mm_sub_epi32(left, side);
  75124. __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
  75125. __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  75126. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75127. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75128. }
  75129. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75130. ma_uint32 left = pInputSamples0U32[i] << shift0;
  75131. ma_uint32 side = pInputSamples1U32[i] << shift1;
  75132. ma_uint32 right = left - side;
  75133. pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f;
  75134. pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f;
  75135. }
  75136. }
  75137. #endif
  75138. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  75139. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75140. {
  75141. ma_uint64 i;
  75142. ma_uint64 frameCount4 = frameCount >> 2;
  75143. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75144. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75145. ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75146. ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75147. float32x4_t factor4;
  75148. int32x4_t shift0_4;
  75149. int32x4_t shift1_4;
  75150. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75151. factor4 = vdupq_n_f32(1.0f / 8388608.0f);
  75152. shift0_4 = vdupq_n_s32(shift0);
  75153. shift1_4 = vdupq_n_s32(shift1);
  75154. for (i = 0; i < frameCount4; ++i) {
  75155. uint32x4_t left;
  75156. uint32x4_t side;
  75157. uint32x4_t right;
  75158. float32x4_t leftf;
  75159. float32x4_t rightf;
  75160. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  75161. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  75162. right = vsubq_u32(left, side);
  75163. leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
  75164. rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  75165. ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75166. }
  75167. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75168. ma_uint32 left = pInputSamples0U32[i] << shift0;
  75169. ma_uint32 side = pInputSamples1U32[i] << shift1;
  75170. ma_uint32 right = left - side;
  75171. pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f;
  75172. pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f;
  75173. }
  75174. }
  75175. #endif
  75176. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_left_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75177. {
  75178. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75179. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75180. ma_dr_flac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75181. } else
  75182. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  75183. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75184. ma_dr_flac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75185. } else
  75186. #endif
  75187. {
  75188. #if 0
  75189. ma_dr_flac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75190. #else
  75191. ma_dr_flac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75192. #endif
  75193. }
  75194. }
  75195. #if 0
  75196. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75197. {
  75198. ma_uint64 i;
  75199. for (i = 0; i < frameCount; ++i) {
  75200. ma_uint32 side = (ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75201. ma_uint32 right = (ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75202. ma_uint32 left = right + side;
  75203. pOutputSamples[i*2+0] = (float)((ma_int32)left / 2147483648.0);
  75204. pOutputSamples[i*2+1] = (float)((ma_int32)right / 2147483648.0);
  75205. }
  75206. }
  75207. #endif
  75208. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75209. {
  75210. ma_uint64 i;
  75211. ma_uint64 frameCount4 = frameCount >> 2;
  75212. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75213. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75214. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75215. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75216. float factor = 1 / 2147483648.0;
  75217. for (i = 0; i < frameCount4; ++i) {
  75218. ma_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  75219. ma_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  75220. ma_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  75221. ma_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  75222. ma_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  75223. ma_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  75224. ma_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  75225. ma_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  75226. ma_uint32 left0 = right0 + side0;
  75227. ma_uint32 left1 = right1 + side1;
  75228. ma_uint32 left2 = right2 + side2;
  75229. ma_uint32 left3 = right3 + side3;
  75230. pOutputSamples[i*8+0] = (ma_int32)left0 * factor;
  75231. pOutputSamples[i*8+1] = (ma_int32)right0 * factor;
  75232. pOutputSamples[i*8+2] = (ma_int32)left1 * factor;
  75233. pOutputSamples[i*8+3] = (ma_int32)right1 * factor;
  75234. pOutputSamples[i*8+4] = (ma_int32)left2 * factor;
  75235. pOutputSamples[i*8+5] = (ma_int32)right2 * factor;
  75236. pOutputSamples[i*8+6] = (ma_int32)left3 * factor;
  75237. pOutputSamples[i*8+7] = (ma_int32)right3 * factor;
  75238. }
  75239. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75240. ma_uint32 side = pInputSamples0U32[i] << shift0;
  75241. ma_uint32 right = pInputSamples1U32[i] << shift1;
  75242. ma_uint32 left = right + side;
  75243. pOutputSamples[i*2+0] = (ma_int32)left * factor;
  75244. pOutputSamples[i*2+1] = (ma_int32)right * factor;
  75245. }
  75246. }
  75247. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75248. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75249. {
  75250. ma_uint64 i;
  75251. ma_uint64 frameCount4 = frameCount >> 2;
  75252. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75253. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75254. ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75255. ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75256. __m128 factor;
  75257. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75258. factor = _mm_set1_ps(1.0f / 8388608.0f);
  75259. for (i = 0; i < frameCount4; ++i) {
  75260. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  75261. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  75262. __m128i left = _mm_add_epi32(right, side);
  75263. __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
  75264. __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  75265. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75266. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75267. }
  75268. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75269. ma_uint32 side = pInputSamples0U32[i] << shift0;
  75270. ma_uint32 right = pInputSamples1U32[i] << shift1;
  75271. ma_uint32 left = right + side;
  75272. pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f;
  75273. pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f;
  75274. }
  75275. }
  75276. #endif
  75277. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  75278. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75279. {
  75280. ma_uint64 i;
  75281. ma_uint64 frameCount4 = frameCount >> 2;
  75282. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75283. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75284. ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75285. ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75286. float32x4_t factor4;
  75287. int32x4_t shift0_4;
  75288. int32x4_t shift1_4;
  75289. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75290. factor4 = vdupq_n_f32(1.0f / 8388608.0f);
  75291. shift0_4 = vdupq_n_s32(shift0);
  75292. shift1_4 = vdupq_n_s32(shift1);
  75293. for (i = 0; i < frameCount4; ++i) {
  75294. uint32x4_t side;
  75295. uint32x4_t right;
  75296. uint32x4_t left;
  75297. float32x4_t leftf;
  75298. float32x4_t rightf;
  75299. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  75300. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  75301. left = vaddq_u32(right, side);
  75302. leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
  75303. rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  75304. ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75305. }
  75306. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75307. ma_uint32 side = pInputSamples0U32[i] << shift0;
  75308. ma_uint32 right = pInputSamples1U32[i] << shift1;
  75309. ma_uint32 left = right + side;
  75310. pOutputSamples[i*2+0] = (ma_int32)left / 8388608.0f;
  75311. pOutputSamples[i*2+1] = (ma_int32)right / 8388608.0f;
  75312. }
  75313. }
  75314. #endif
  75315. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_right_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75316. {
  75317. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75318. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75319. ma_dr_flac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75320. } else
  75321. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  75322. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75323. ma_dr_flac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75324. } else
  75325. #endif
  75326. {
  75327. #if 0
  75328. ma_dr_flac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75329. #else
  75330. ma_dr_flac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75331. #endif
  75332. }
  75333. }
  75334. #if 0
  75335. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75336. {
  75337. for (ma_uint64 i = 0; i < frameCount; ++i) {
  75338. ma_uint32 mid = (ma_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75339. ma_uint32 side = (ma_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75340. mid = (mid << 1) | (side & 0x01);
  75341. pOutputSamples[i*2+0] = (float)((((ma_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  75342. pOutputSamples[i*2+1] = (float)((((ma_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  75343. }
  75344. }
  75345. #endif
  75346. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75347. {
  75348. ma_uint64 i;
  75349. ma_uint64 frameCount4 = frameCount >> 2;
  75350. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75351. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75352. ma_uint32 shift = unusedBitsPerSample;
  75353. float factor = 1 / 2147483648.0;
  75354. if (shift > 0) {
  75355. shift -= 1;
  75356. for (i = 0; i < frameCount4; ++i) {
  75357. ma_uint32 temp0L;
  75358. ma_uint32 temp1L;
  75359. ma_uint32 temp2L;
  75360. ma_uint32 temp3L;
  75361. ma_uint32 temp0R;
  75362. ma_uint32 temp1R;
  75363. ma_uint32 temp2R;
  75364. ma_uint32 temp3R;
  75365. ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75366. ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75367. ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75368. ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75369. ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75370. ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75371. ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75372. ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75373. mid0 = (mid0 << 1) | (side0 & 0x01);
  75374. mid1 = (mid1 << 1) | (side1 & 0x01);
  75375. mid2 = (mid2 << 1) | (side2 & 0x01);
  75376. mid3 = (mid3 << 1) | (side3 & 0x01);
  75377. temp0L = (mid0 + side0) << shift;
  75378. temp1L = (mid1 + side1) << shift;
  75379. temp2L = (mid2 + side2) << shift;
  75380. temp3L = (mid3 + side3) << shift;
  75381. temp0R = (mid0 - side0) << shift;
  75382. temp1R = (mid1 - side1) << shift;
  75383. temp2R = (mid2 - side2) << shift;
  75384. temp3R = (mid3 - side3) << shift;
  75385. pOutputSamples[i*8+0] = (ma_int32)temp0L * factor;
  75386. pOutputSamples[i*8+1] = (ma_int32)temp0R * factor;
  75387. pOutputSamples[i*8+2] = (ma_int32)temp1L * factor;
  75388. pOutputSamples[i*8+3] = (ma_int32)temp1R * factor;
  75389. pOutputSamples[i*8+4] = (ma_int32)temp2L * factor;
  75390. pOutputSamples[i*8+5] = (ma_int32)temp2R * factor;
  75391. pOutputSamples[i*8+6] = (ma_int32)temp3L * factor;
  75392. pOutputSamples[i*8+7] = (ma_int32)temp3R * factor;
  75393. }
  75394. } else {
  75395. for (i = 0; i < frameCount4; ++i) {
  75396. ma_uint32 temp0L;
  75397. ma_uint32 temp1L;
  75398. ma_uint32 temp2L;
  75399. ma_uint32 temp3L;
  75400. ma_uint32 temp0R;
  75401. ma_uint32 temp1R;
  75402. ma_uint32 temp2R;
  75403. ma_uint32 temp3R;
  75404. ma_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75405. ma_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75406. ma_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75407. ma_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75408. ma_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75409. ma_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75410. ma_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75411. ma_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75412. mid0 = (mid0 << 1) | (side0 & 0x01);
  75413. mid1 = (mid1 << 1) | (side1 & 0x01);
  75414. mid2 = (mid2 << 1) | (side2 & 0x01);
  75415. mid3 = (mid3 << 1) | (side3 & 0x01);
  75416. temp0L = (ma_uint32)((ma_int32)(mid0 + side0) >> 1);
  75417. temp1L = (ma_uint32)((ma_int32)(mid1 + side1) >> 1);
  75418. temp2L = (ma_uint32)((ma_int32)(mid2 + side2) >> 1);
  75419. temp3L = (ma_uint32)((ma_int32)(mid3 + side3) >> 1);
  75420. temp0R = (ma_uint32)((ma_int32)(mid0 - side0) >> 1);
  75421. temp1R = (ma_uint32)((ma_int32)(mid1 - side1) >> 1);
  75422. temp2R = (ma_uint32)((ma_int32)(mid2 - side2) >> 1);
  75423. temp3R = (ma_uint32)((ma_int32)(mid3 - side3) >> 1);
  75424. pOutputSamples[i*8+0] = (ma_int32)temp0L * factor;
  75425. pOutputSamples[i*8+1] = (ma_int32)temp0R * factor;
  75426. pOutputSamples[i*8+2] = (ma_int32)temp1L * factor;
  75427. pOutputSamples[i*8+3] = (ma_int32)temp1R * factor;
  75428. pOutputSamples[i*8+4] = (ma_int32)temp2L * factor;
  75429. pOutputSamples[i*8+5] = (ma_int32)temp2R * factor;
  75430. pOutputSamples[i*8+6] = (ma_int32)temp3L * factor;
  75431. pOutputSamples[i*8+7] = (ma_int32)temp3R * factor;
  75432. }
  75433. }
  75434. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75435. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75436. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75437. mid = (mid << 1) | (side & 0x01);
  75438. pOutputSamples[i*2+0] = (ma_int32)((ma_uint32)((ma_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
  75439. pOutputSamples[i*2+1] = (ma_int32)((ma_uint32)((ma_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
  75440. }
  75441. }
  75442. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75443. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75444. {
  75445. ma_uint64 i;
  75446. ma_uint64 frameCount4 = frameCount >> 2;
  75447. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75448. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75449. ma_uint32 shift = unusedBitsPerSample - 8;
  75450. float factor;
  75451. __m128 factor128;
  75452. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75453. factor = 1.0f / 8388608.0f;
  75454. factor128 = _mm_set1_ps(factor);
  75455. if (shift == 0) {
  75456. for (i = 0; i < frameCount4; ++i) {
  75457. __m128i mid;
  75458. __m128i side;
  75459. __m128i tempL;
  75460. __m128i tempR;
  75461. __m128 leftf;
  75462. __m128 rightf;
  75463. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75464. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75465. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  75466. tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  75467. tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  75468. leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  75469. rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  75470. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75471. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75472. }
  75473. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75474. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75475. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75476. mid = (mid << 1) | (side & 0x01);
  75477. pOutputSamples[i*2+0] = ((ma_int32)(mid + side) >> 1) * factor;
  75478. pOutputSamples[i*2+1] = ((ma_int32)(mid - side) >> 1) * factor;
  75479. }
  75480. } else {
  75481. shift -= 1;
  75482. for (i = 0; i < frameCount4; ++i) {
  75483. __m128i mid;
  75484. __m128i side;
  75485. __m128i tempL;
  75486. __m128i tempR;
  75487. __m128 leftf;
  75488. __m128 rightf;
  75489. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75490. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75491. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  75492. tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  75493. tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  75494. leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  75495. rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  75496. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75497. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75498. }
  75499. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75500. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75501. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75502. mid = (mid << 1) | (side & 0x01);
  75503. pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift) * factor;
  75504. pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift) * factor;
  75505. }
  75506. }
  75507. }
  75508. #endif
  75509. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  75510. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75511. {
  75512. ma_uint64 i;
  75513. ma_uint64 frameCount4 = frameCount >> 2;
  75514. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75515. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75516. ma_uint32 shift = unusedBitsPerSample - 8;
  75517. float factor;
  75518. float32x4_t factor4;
  75519. int32x4_t shift4;
  75520. int32x4_t wbps0_4;
  75521. int32x4_t wbps1_4;
  75522. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 24);
  75523. factor = 1.0f / 8388608.0f;
  75524. factor4 = vdupq_n_f32(factor);
  75525. wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  75526. wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  75527. if (shift == 0) {
  75528. for (i = 0; i < frameCount4; ++i) {
  75529. int32x4_t lefti;
  75530. int32x4_t righti;
  75531. float32x4_t leftf;
  75532. float32x4_t rightf;
  75533. uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  75534. uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  75535. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  75536. lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  75537. righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  75538. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  75539. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  75540. ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75541. }
  75542. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75543. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75544. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75545. mid = (mid << 1) | (side & 0x01);
  75546. pOutputSamples[i*2+0] = ((ma_int32)(mid + side) >> 1) * factor;
  75547. pOutputSamples[i*2+1] = ((ma_int32)(mid - side) >> 1) * factor;
  75548. }
  75549. } else {
  75550. shift -= 1;
  75551. shift4 = vdupq_n_s32(shift);
  75552. for (i = 0; i < frameCount4; ++i) {
  75553. uint32x4_t mid;
  75554. uint32x4_t side;
  75555. int32x4_t lefti;
  75556. int32x4_t righti;
  75557. float32x4_t leftf;
  75558. float32x4_t rightf;
  75559. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  75560. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  75561. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  75562. lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  75563. righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  75564. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  75565. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  75566. ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75567. }
  75568. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75569. ma_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75570. ma_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75571. mid = (mid << 1) | (side & 0x01);
  75572. pOutputSamples[i*2+0] = (ma_int32)((mid + side) << shift) * factor;
  75573. pOutputSamples[i*2+1] = (ma_int32)((mid - side) << shift) * factor;
  75574. }
  75575. }
  75576. }
  75577. #endif
  75578. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_mid_side(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75579. {
  75580. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75581. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75582. ma_dr_flac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75583. } else
  75584. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  75585. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75586. ma_dr_flac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75587. } else
  75588. #endif
  75589. {
  75590. #if 0
  75591. ma_dr_flac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75592. #else
  75593. ma_dr_flac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75594. #endif
  75595. }
  75596. }
  75597. #if 0
  75598. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__reference(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75599. {
  75600. for (ma_uint64 i = 0; i < frameCount; ++i) {
  75601. pOutputSamples[i*2+0] = (float)((ma_int32)((ma_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
  75602. pOutputSamples[i*2+1] = (float)((ma_int32)((ma_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
  75603. }
  75604. }
  75605. #endif
  75606. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__scalar(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75607. {
  75608. ma_uint64 i;
  75609. ma_uint64 frameCount4 = frameCount >> 2;
  75610. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75611. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75612. ma_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  75613. ma_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  75614. float factor = 1 / 2147483648.0;
  75615. for (i = 0; i < frameCount4; ++i) {
  75616. ma_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  75617. ma_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  75618. ma_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  75619. ma_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  75620. ma_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  75621. ma_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  75622. ma_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  75623. ma_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  75624. pOutputSamples[i*8+0] = (ma_int32)tempL0 * factor;
  75625. pOutputSamples[i*8+1] = (ma_int32)tempR0 * factor;
  75626. pOutputSamples[i*8+2] = (ma_int32)tempL1 * factor;
  75627. pOutputSamples[i*8+3] = (ma_int32)tempR1 * factor;
  75628. pOutputSamples[i*8+4] = (ma_int32)tempL2 * factor;
  75629. pOutputSamples[i*8+5] = (ma_int32)tempR2 * factor;
  75630. pOutputSamples[i*8+6] = (ma_int32)tempL3 * factor;
  75631. pOutputSamples[i*8+7] = (ma_int32)tempR3 * factor;
  75632. }
  75633. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75634. pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0) * factor;
  75635. pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1) * factor;
  75636. }
  75637. }
  75638. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75639. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__sse2(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75640. {
  75641. ma_uint64 i;
  75642. ma_uint64 frameCount4 = frameCount >> 2;
  75643. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75644. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75645. ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75646. ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75647. float factor = 1.0f / 8388608.0f;
  75648. __m128 factor128 = _mm_set1_ps(factor);
  75649. for (i = 0; i < frameCount4; ++i) {
  75650. __m128i lefti;
  75651. __m128i righti;
  75652. __m128 leftf;
  75653. __m128 rightf;
  75654. lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  75655. righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  75656. leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
  75657. rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
  75658. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  75659. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  75660. }
  75661. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75662. pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0) * factor;
  75663. pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1) * factor;
  75664. }
  75665. }
  75666. #endif
  75667. #if defined(MA_DR_FLAC_SUPPORT_NEON)
  75668. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__neon(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75669. {
  75670. ma_uint64 i;
  75671. ma_uint64 frameCount4 = frameCount >> 2;
  75672. const ma_uint32* pInputSamples0U32 = (const ma_uint32*)pInputSamples0;
  75673. const ma_uint32* pInputSamples1U32 = (const ma_uint32*)pInputSamples1;
  75674. ma_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  75675. ma_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  75676. float factor = 1.0f / 8388608.0f;
  75677. float32x4_t factor4 = vdupq_n_f32(factor);
  75678. int32x4_t shift0_4 = vdupq_n_s32(shift0);
  75679. int32x4_t shift1_4 = vdupq_n_s32(shift1);
  75680. for (i = 0; i < frameCount4; ++i) {
  75681. int32x4_t lefti;
  75682. int32x4_t righti;
  75683. float32x4_t leftf;
  75684. float32x4_t rightf;
  75685. lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  75686. righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  75687. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  75688. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  75689. ma_dr_flac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  75690. }
  75691. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  75692. pOutputSamples[i*2+0] = (ma_int32)(pInputSamples0U32[i] << shift0) * factor;
  75693. pOutputSamples[i*2+1] = (ma_int32)(pInputSamples1U32[i] << shift1) * factor;
  75694. }
  75695. }
  75696. #endif
  75697. static MA_INLINE void ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo(ma_dr_flac* pFlac, ma_uint64 frameCount, ma_uint32 unusedBitsPerSample, const ma_int32* pInputSamples0, const ma_int32* pInputSamples1, float* pOutputSamples)
  75698. {
  75699. #if defined(MA_DR_FLAC_SUPPORT_SSE2)
  75700. if (ma_dr_flac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  75701. ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75702. } else
  75703. #elif defined(MA_DR_FLAC_SUPPORT_NEON)
  75704. if (ma_dr_flac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  75705. ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75706. } else
  75707. #endif
  75708. {
  75709. #if 0
  75710. ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75711. #else
  75712. ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  75713. #endif
  75714. }
  75715. }
  75716. MA_API ma_uint64 ma_dr_flac_read_pcm_frames_f32(ma_dr_flac* pFlac, ma_uint64 framesToRead, float* pBufferOut)
  75717. {
  75718. ma_uint64 framesRead;
  75719. ma_uint32 unusedBitsPerSample;
  75720. if (pFlac == NULL || framesToRead == 0) {
  75721. return 0;
  75722. }
  75723. if (pBufferOut == NULL) {
  75724. return ma_dr_flac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  75725. }
  75726. MA_DR_FLAC_ASSERT(pFlac->bitsPerSample <= 32);
  75727. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  75728. framesRead = 0;
  75729. while (framesToRead > 0) {
  75730. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  75731. if (!ma_dr_flac__read_and_decode_next_flac_frame(pFlac)) {
  75732. break;
  75733. }
  75734. } else {
  75735. unsigned int channelCount = ma_dr_flac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  75736. ma_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  75737. ma_uint64 frameCountThisIteration = framesToRead;
  75738. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  75739. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  75740. }
  75741. if (channelCount == 2) {
  75742. const ma_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  75743. const ma_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  75744. switch (pFlac->currentFLACFrame.header.channelAssignment)
  75745. {
  75746. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  75747. {
  75748. ma_dr_flac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75749. } break;
  75750. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  75751. {
  75752. ma_dr_flac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75753. } break;
  75754. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  75755. {
  75756. ma_dr_flac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75757. } break;
  75758. case MA_DR_FLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  75759. default:
  75760. {
  75761. ma_dr_flac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  75762. } break;
  75763. }
  75764. } else {
  75765. ma_uint64 i;
  75766. for (i = 0; i < frameCountThisIteration; ++i) {
  75767. unsigned int j;
  75768. for (j = 0; j < channelCount; ++j) {
  75769. ma_int32 sampleS32 = (ma_int32)((ma_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  75770. pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
  75771. }
  75772. }
  75773. }
  75774. framesRead += frameCountThisIteration;
  75775. pBufferOut += frameCountThisIteration * channelCount;
  75776. framesToRead -= frameCountThisIteration;
  75777. pFlac->currentPCMFrame += frameCountThisIteration;
  75778. pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
  75779. }
  75780. }
  75781. return framesRead;
  75782. }
  75783. MA_API ma_bool32 ma_dr_flac_seek_to_pcm_frame(ma_dr_flac* pFlac, ma_uint64 pcmFrameIndex)
  75784. {
  75785. if (pFlac == NULL) {
  75786. return MA_FALSE;
  75787. }
  75788. if (pFlac->currentPCMFrame == pcmFrameIndex) {
  75789. return MA_TRUE;
  75790. }
  75791. if (pFlac->firstFLACFramePosInBytes == 0) {
  75792. return MA_FALSE;
  75793. }
  75794. if (pcmFrameIndex == 0) {
  75795. pFlac->currentPCMFrame = 0;
  75796. return ma_dr_flac__seek_to_first_frame(pFlac);
  75797. } else {
  75798. ma_bool32 wasSuccessful = MA_FALSE;
  75799. ma_uint64 originalPCMFrame = pFlac->currentPCMFrame;
  75800. if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
  75801. pcmFrameIndex = pFlac->totalPCMFrameCount;
  75802. }
  75803. if (pcmFrameIndex > pFlac->currentPCMFrame) {
  75804. ma_uint32 offset = (ma_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
  75805. if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
  75806. pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
  75807. pFlac->currentPCMFrame = pcmFrameIndex;
  75808. return MA_TRUE;
  75809. }
  75810. } else {
  75811. ma_uint32 offsetAbs = (ma_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
  75812. ma_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  75813. ma_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
  75814. if (currentFLACFramePCMFramesConsumed > offsetAbs) {
  75815. pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
  75816. pFlac->currentPCMFrame = pcmFrameIndex;
  75817. return MA_TRUE;
  75818. }
  75819. }
  75820. #ifndef MA_DR_FLAC_NO_OGG
  75821. if (pFlac->container == ma_dr_flac_container_ogg)
  75822. {
  75823. wasSuccessful = ma_dr_flac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
  75824. }
  75825. else
  75826. #endif
  75827. {
  75828. if (!pFlac->_noSeekTableSeek) {
  75829. wasSuccessful = ma_dr_flac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
  75830. }
  75831. #if !defined(MA_DR_FLAC_NO_CRC)
  75832. if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
  75833. wasSuccessful = ma_dr_flac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
  75834. }
  75835. #endif
  75836. if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
  75837. wasSuccessful = ma_dr_flac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
  75838. }
  75839. }
  75840. if (wasSuccessful) {
  75841. pFlac->currentPCMFrame = pcmFrameIndex;
  75842. } else {
  75843. if (ma_dr_flac_seek_to_pcm_frame(pFlac, originalPCMFrame) == MA_FALSE) {
  75844. ma_dr_flac_seek_to_pcm_frame(pFlac, 0);
  75845. }
  75846. }
  75847. return wasSuccessful;
  75848. }
  75849. }
  75850. #define MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
  75851. static type* ma_dr_flac__full_read_and_close_ ## extension (ma_dr_flac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut)\
  75852. { \
  75853. type* pSampleData = NULL; \
  75854. ma_uint64 totalPCMFrameCount; \
  75855. \
  75856. MA_DR_FLAC_ASSERT(pFlac != NULL); \
  75857. \
  75858. totalPCMFrameCount = pFlac->totalPCMFrameCount; \
  75859. \
  75860. if (totalPCMFrameCount == 0) { \
  75861. type buffer[4096]; \
  75862. ma_uint64 pcmFramesRead; \
  75863. size_t sampleDataBufferSize = sizeof(buffer); \
  75864. \
  75865. pSampleData = (type*)ma_dr_flac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
  75866. if (pSampleData == NULL) { \
  75867. goto on_error; \
  75868. } \
  75869. \
  75870. while ((pcmFramesRead = (ma_uint64)ma_dr_flac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
  75871. if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
  75872. type* pNewSampleData; \
  75873. size_t newSampleDataBufferSize; \
  75874. \
  75875. newSampleDataBufferSize = sampleDataBufferSize * 2; \
  75876. pNewSampleData = (type*)ma_dr_flac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
  75877. if (pNewSampleData == NULL) { \
  75878. ma_dr_flac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
  75879. goto on_error; \
  75880. } \
  75881. \
  75882. sampleDataBufferSize = newSampleDataBufferSize; \
  75883. pSampleData = pNewSampleData; \
  75884. } \
  75885. \
  75886. MA_DR_FLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
  75887. totalPCMFrameCount += pcmFramesRead; \
  75888. } \
  75889. \
  75890. \
  75891. MA_DR_FLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
  75892. } else { \
  75893. ma_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \
  75894. if (dataSize > (ma_uint64)MA_SIZE_MAX) { \
  75895. goto on_error; \
  75896. } \
  75897. \
  75898. pSampleData = (type*)ma_dr_flac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks); \
  75899. if (pSampleData == NULL) { \
  75900. goto on_error; \
  75901. } \
  75902. \
  75903. totalPCMFrameCount = ma_dr_flac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \
  75904. } \
  75905. \
  75906. if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
  75907. if (channelsOut) *channelsOut = pFlac->channels; \
  75908. if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
  75909. \
  75910. ma_dr_flac_close(pFlac); \
  75911. return pSampleData; \
  75912. \
  75913. on_error: \
  75914. ma_dr_flac_close(pFlac); \
  75915. return NULL; \
  75916. }
  75917. MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(s32, ma_int32)
  75918. MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(s16, ma_int16)
  75919. MA_DR_FLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
  75920. MA_API ma_int32* ma_dr_flac_open_and_read_pcm_frames_s32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  75921. {
  75922. ma_dr_flac* pFlac;
  75923. if (channelsOut) {
  75924. *channelsOut = 0;
  75925. }
  75926. if (sampleRateOut) {
  75927. *sampleRateOut = 0;
  75928. }
  75929. if (totalPCMFrameCountOut) {
  75930. *totalPCMFrameCountOut = 0;
  75931. }
  75932. pFlac = ma_dr_flac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  75933. if (pFlac == NULL) {
  75934. return NULL;
  75935. }
  75936. return ma_dr_flac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  75937. }
  75938. MA_API ma_int16* ma_dr_flac_open_and_read_pcm_frames_s16(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  75939. {
  75940. ma_dr_flac* pFlac;
  75941. if (channelsOut) {
  75942. *channelsOut = 0;
  75943. }
  75944. if (sampleRateOut) {
  75945. *sampleRateOut = 0;
  75946. }
  75947. if (totalPCMFrameCountOut) {
  75948. *totalPCMFrameCountOut = 0;
  75949. }
  75950. pFlac = ma_dr_flac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  75951. if (pFlac == NULL) {
  75952. return NULL;
  75953. }
  75954. return ma_dr_flac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  75955. }
  75956. MA_API float* ma_dr_flac_open_and_read_pcm_frames_f32(ma_dr_flac_read_proc onRead, ma_dr_flac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, ma_uint64* totalPCMFrameCountOut, const ma_allocation_callbacks* pAllocationCallbacks)
  75957. {
  75958. ma_dr_flac* pFlac;
  75959. if (channelsOut) {
  75960. *channelsOut = 0;
  75961. }
  75962. if (sampleRateOut) {
  75963. *sampleRateOut = 0;
  75964. }
  75965. if (totalPCMFrameCountOut) {
  75966. *totalPCMFrameCountOut = 0;
  75967. }
  75968. pFlac = ma_dr_flac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  75969. if (pFlac == NULL) {
  75970. return NULL;
  75971. }
  75972. return ma_dr_flac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  75973. }
  75974. #ifndef MA_DR_FLAC_NO_STDIO
  75975. MA_API ma_int32* ma_dr_flac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  75976. {
  75977. ma_dr_flac* pFlac;
  75978. if (sampleRate) {
  75979. *sampleRate = 0;
  75980. }
  75981. if (channels) {
  75982. *channels = 0;
  75983. }
  75984. if (totalPCMFrameCount) {
  75985. *totalPCMFrameCount = 0;
  75986. }
  75987. pFlac = ma_dr_flac_open_file(filename, pAllocationCallbacks);
  75988. if (pFlac == NULL) {
  75989. return NULL;
  75990. }
  75991. return ma_dr_flac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  75992. }
  75993. MA_API ma_int16* ma_dr_flac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  75994. {
  75995. ma_dr_flac* pFlac;
  75996. if (sampleRate) {
  75997. *sampleRate = 0;
  75998. }
  75999. if (channels) {
  76000. *channels = 0;
  76001. }
  76002. if (totalPCMFrameCount) {
  76003. *totalPCMFrameCount = 0;
  76004. }
  76005. pFlac = ma_dr_flac_open_file(filename, pAllocationCallbacks);
  76006. if (pFlac == NULL) {
  76007. return NULL;
  76008. }
  76009. return ma_dr_flac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  76010. }
  76011. MA_API float* ma_dr_flac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  76012. {
  76013. ma_dr_flac* pFlac;
  76014. if (sampleRate) {
  76015. *sampleRate = 0;
  76016. }
  76017. if (channels) {
  76018. *channels = 0;
  76019. }
  76020. if (totalPCMFrameCount) {
  76021. *totalPCMFrameCount = 0;
  76022. }
  76023. pFlac = ma_dr_flac_open_file(filename, pAllocationCallbacks);
  76024. if (pFlac == NULL) {
  76025. return NULL;
  76026. }
  76027. return ma_dr_flac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76028. }
  76029. #endif
  76030. MA_API ma_int32* ma_dr_flac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  76031. {
  76032. ma_dr_flac* pFlac;
  76033. if (sampleRate) {
  76034. *sampleRate = 0;
  76035. }
  76036. if (channels) {
  76037. *channels = 0;
  76038. }
  76039. if (totalPCMFrameCount) {
  76040. *totalPCMFrameCount = 0;
  76041. }
  76042. pFlac = ma_dr_flac_open_memory(data, dataSize, pAllocationCallbacks);
  76043. if (pFlac == NULL) {
  76044. return NULL;
  76045. }
  76046. return ma_dr_flac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76047. }
  76048. MA_API ma_int16* ma_dr_flac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  76049. {
  76050. ma_dr_flac* pFlac;
  76051. if (sampleRate) {
  76052. *sampleRate = 0;
  76053. }
  76054. if (channels) {
  76055. *channels = 0;
  76056. }
  76057. if (totalPCMFrameCount) {
  76058. *totalPCMFrameCount = 0;
  76059. }
  76060. pFlac = ma_dr_flac_open_memory(data, dataSize, pAllocationCallbacks);
  76061. if (pFlac == NULL) {
  76062. return NULL;
  76063. }
  76064. return ma_dr_flac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  76065. }
  76066. MA_API float* ma_dr_flac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, ma_uint64* totalPCMFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  76067. {
  76068. ma_dr_flac* pFlac;
  76069. if (sampleRate) {
  76070. *sampleRate = 0;
  76071. }
  76072. if (channels) {
  76073. *channels = 0;
  76074. }
  76075. if (totalPCMFrameCount) {
  76076. *totalPCMFrameCount = 0;
  76077. }
  76078. pFlac = ma_dr_flac_open_memory(data, dataSize, pAllocationCallbacks);
  76079. if (pFlac == NULL) {
  76080. return NULL;
  76081. }
  76082. return ma_dr_flac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  76083. }
  76084. MA_API void ma_dr_flac_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  76085. {
  76086. if (pAllocationCallbacks != NULL) {
  76087. ma_dr_flac__free_from_callbacks(p, pAllocationCallbacks);
  76088. } else {
  76089. ma_dr_flac__free_default(p, NULL);
  76090. }
  76091. }
  76092. MA_API void ma_dr_flac_init_vorbis_comment_iterator(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32 commentCount, const void* pComments)
  76093. {
  76094. if (pIter == NULL) {
  76095. return;
  76096. }
  76097. pIter->countRemaining = commentCount;
  76098. pIter->pRunningData = (const char*)pComments;
  76099. }
  76100. MA_API const char* ma_dr_flac_next_vorbis_comment(ma_dr_flac_vorbis_comment_iterator* pIter, ma_uint32* pCommentLengthOut)
  76101. {
  76102. ma_int32 length;
  76103. const char* pComment;
  76104. if (pCommentLengthOut) {
  76105. *pCommentLengthOut = 0;
  76106. }
  76107. if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  76108. return NULL;
  76109. }
  76110. length = ma_dr_flac__le2host_32_ptr_unaligned(pIter->pRunningData);
  76111. pIter->pRunningData += 4;
  76112. pComment = pIter->pRunningData;
  76113. pIter->pRunningData += length;
  76114. pIter->countRemaining -= 1;
  76115. if (pCommentLengthOut) {
  76116. *pCommentLengthOut = length;
  76117. }
  76118. return pComment;
  76119. }
  76120. MA_API void ma_dr_flac_init_cuesheet_track_iterator(ma_dr_flac_cuesheet_track_iterator* pIter, ma_uint32 trackCount, const void* pTrackData)
  76121. {
  76122. if (pIter == NULL) {
  76123. return;
  76124. }
  76125. pIter->countRemaining = trackCount;
  76126. pIter->pRunningData = (const char*)pTrackData;
  76127. }
  76128. MA_API ma_bool32 ma_dr_flac_next_cuesheet_track(ma_dr_flac_cuesheet_track_iterator* pIter, ma_dr_flac_cuesheet_track* pCuesheetTrack)
  76129. {
  76130. ma_dr_flac_cuesheet_track cuesheetTrack;
  76131. const char* pRunningData;
  76132. ma_uint64 offsetHi;
  76133. ma_uint64 offsetLo;
  76134. if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  76135. return MA_FALSE;
  76136. }
  76137. pRunningData = pIter->pRunningData;
  76138. offsetHi = ma_dr_flac__be2host_32(*(const ma_uint32*)pRunningData); pRunningData += 4;
  76139. offsetLo = ma_dr_flac__be2host_32(*(const ma_uint32*)pRunningData); pRunningData += 4;
  76140. cuesheetTrack.offset = offsetLo | (offsetHi << 32);
  76141. cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
  76142. MA_DR_FLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
  76143. cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
  76144. cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
  76145. cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
  76146. cuesheetTrack.pIndexPoints = (const ma_dr_flac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(ma_dr_flac_cuesheet_track_index);
  76147. pIter->pRunningData = pRunningData;
  76148. pIter->countRemaining -= 1;
  76149. if (pCuesheetTrack) {
  76150. *pCuesheetTrack = cuesheetTrack;
  76151. }
  76152. return MA_TRUE;
  76153. }
  76154. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  76155. #pragma GCC diagnostic pop
  76156. #endif
  76157. #endif
  76158. /* dr_flac_c end */
  76159. #endif /* MA_DR_FLAC_IMPLEMENTATION */
  76160. #endif /* MA_NO_FLAC */
  76161. #if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
  76162. #if !defined(MA_DR_MP3_IMPLEMENTATION) && !defined(MA_DR_MP3_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  76163. /* dr_mp3_c begin */
  76164. #ifndef ma_dr_mp3_c
  76165. #define ma_dr_mp3_c
  76166. #include <stdlib.h>
  76167. #include <string.h>
  76168. #include <limits.h>
  76169. MA_API void ma_dr_mp3_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
  76170. {
  76171. if (pMajor) {
  76172. *pMajor = MA_DR_MP3_VERSION_MAJOR;
  76173. }
  76174. if (pMinor) {
  76175. *pMinor = MA_DR_MP3_VERSION_MINOR;
  76176. }
  76177. if (pRevision) {
  76178. *pRevision = MA_DR_MP3_VERSION_REVISION;
  76179. }
  76180. }
  76181. MA_API const char* ma_dr_mp3_version_string(void)
  76182. {
  76183. return MA_DR_MP3_VERSION_STRING;
  76184. }
  76185. #if defined(__TINYC__)
  76186. #define MA_DR_MP3_NO_SIMD
  76187. #endif
  76188. #define MA_DR_MP3_OFFSET_PTR(p, offset) ((void*)((ma_uint8*)(p) + (offset)))
  76189. #define MA_DR_MP3_MAX_FREE_FORMAT_FRAME_SIZE 2304
  76190. #ifndef MA_DR_MP3_MAX_FRAME_SYNC_MATCHES
  76191. #define MA_DR_MP3_MAX_FRAME_SYNC_MATCHES 10
  76192. #endif
  76193. #define MA_DR_MP3_MAX_L3_FRAME_PAYLOAD_BYTES MA_DR_MP3_MAX_FREE_FORMAT_FRAME_SIZE
  76194. #define MA_DR_MP3_MAX_BITRESERVOIR_BYTES 511
  76195. #define MA_DR_MP3_SHORT_BLOCK_TYPE 2
  76196. #define MA_DR_MP3_STOP_BLOCK_TYPE 3
  76197. #define MA_DR_MP3_MODE_MONO 3
  76198. #define MA_DR_MP3_MODE_JOINT_STEREO 1
  76199. #define MA_DR_MP3_HDR_SIZE 4
  76200. #define MA_DR_MP3_HDR_IS_MONO(h) (((h[3]) & 0xC0) == 0xC0)
  76201. #define MA_DR_MP3_HDR_IS_MS_STEREO(h) (((h[3]) & 0xE0) == 0x60)
  76202. #define MA_DR_MP3_HDR_IS_FREE_FORMAT(h) (((h[2]) & 0xF0) == 0)
  76203. #define MA_DR_MP3_HDR_IS_CRC(h) (!((h[1]) & 1))
  76204. #define MA_DR_MP3_HDR_TEST_PADDING(h) ((h[2]) & 0x2)
  76205. #define MA_DR_MP3_HDR_TEST_MPEG1(h) ((h[1]) & 0x8)
  76206. #define MA_DR_MP3_HDR_TEST_NOT_MPEG25(h) ((h[1]) & 0x10)
  76207. #define MA_DR_MP3_HDR_TEST_I_STEREO(h) ((h[3]) & 0x10)
  76208. #define MA_DR_MP3_HDR_TEST_MS_STEREO(h) ((h[3]) & 0x20)
  76209. #define MA_DR_MP3_HDR_GET_STEREO_MODE(h) (((h[3]) >> 6) & 3)
  76210. #define MA_DR_MP3_HDR_GET_STEREO_MODE_EXT(h) (((h[3]) >> 4) & 3)
  76211. #define MA_DR_MP3_HDR_GET_LAYER(h) (((h[1]) >> 1) & 3)
  76212. #define MA_DR_MP3_HDR_GET_BITRATE(h) ((h[2]) >> 4)
  76213. #define MA_DR_MP3_HDR_GET_SAMPLE_RATE(h) (((h[2]) >> 2) & 3)
  76214. #define MA_DR_MP3_HDR_GET_MY_SAMPLE_RATE(h) (MA_DR_MP3_HDR_GET_SAMPLE_RATE(h) + (((h[1] >> 3) & 1) + ((h[1] >> 4) & 1))*3)
  76215. #define MA_DR_MP3_HDR_IS_FRAME_576(h) ((h[1] & 14) == 2)
  76216. #define MA_DR_MP3_HDR_IS_LAYER_1(h) ((h[1] & 6) == 6)
  76217. #define MA_DR_MP3_BITS_DEQUANTIZER_OUT -1
  76218. #define MA_DR_MP3_MAX_SCF (255 + MA_DR_MP3_BITS_DEQUANTIZER_OUT*4 - 210)
  76219. #define MA_DR_MP3_MAX_SCFI ((MA_DR_MP3_MAX_SCF + 3) & ~3)
  76220. #define MA_DR_MP3_MIN(a, b) ((a) > (b) ? (b) : (a))
  76221. #define MA_DR_MP3_MAX(a, b) ((a) < (b) ? (b) : (a))
  76222. #if !defined(MA_DR_MP3_NO_SIMD)
  76223. #if !defined(MA_DR_MP3_ONLY_SIMD) && (defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(_M_ARM64))
  76224. #define MA_DR_MP3_ONLY_SIMD
  76225. #endif
  76226. #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__)))
  76227. #if defined(_MSC_VER)
  76228. #include <intrin.h>
  76229. #endif
  76230. #include <emmintrin.h>
  76231. #define MA_DR_MP3_HAVE_SSE 1
  76232. #define MA_DR_MP3_HAVE_SIMD 1
  76233. #define MA_DR_MP3_VSTORE _mm_storeu_ps
  76234. #define MA_DR_MP3_VLD _mm_loadu_ps
  76235. #define MA_DR_MP3_VSET _mm_set1_ps
  76236. #define MA_DR_MP3_VADD _mm_add_ps
  76237. #define MA_DR_MP3_VSUB _mm_sub_ps
  76238. #define MA_DR_MP3_VMUL _mm_mul_ps
  76239. #define MA_DR_MP3_VMAC(a, x, y) _mm_add_ps(a, _mm_mul_ps(x, y))
  76240. #define MA_DR_MP3_VMSB(a, x, y) _mm_sub_ps(a, _mm_mul_ps(x, y))
  76241. #define MA_DR_MP3_VMUL_S(x, s) _mm_mul_ps(x, _mm_set1_ps(s))
  76242. #define MA_DR_MP3_VREV(x) _mm_shuffle_ps(x, x, _MM_SHUFFLE(0, 1, 2, 3))
  76243. typedef __m128 ma_dr_mp3_f4;
  76244. #if defined(_MSC_VER) || defined(MA_DR_MP3_ONLY_SIMD)
  76245. #define ma_dr_mp3_cpuid __cpuid
  76246. #else
  76247. static __inline__ __attribute__((always_inline)) void ma_dr_mp3_cpuid(int CPUInfo[], const int InfoType)
  76248. {
  76249. #if defined(__PIC__)
  76250. __asm__ __volatile__(
  76251. #if defined(__x86_64__)
  76252. "push %%rbx\n"
  76253. "cpuid\n"
  76254. "xchgl %%ebx, %1\n"
  76255. "pop %%rbx\n"
  76256. #else
  76257. "xchgl %%ebx, %1\n"
  76258. "cpuid\n"
  76259. "xchgl %%ebx, %1\n"
  76260. #endif
  76261. : "=a" (CPUInfo[0]), "=r" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
  76262. : "a" (InfoType));
  76263. #else
  76264. __asm__ __volatile__(
  76265. "cpuid"
  76266. : "=a" (CPUInfo[0]), "=b" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
  76267. : "a" (InfoType));
  76268. #endif
  76269. }
  76270. #endif
  76271. static int ma_dr_mp3_have_simd(void)
  76272. {
  76273. #ifdef MA_DR_MP3_ONLY_SIMD
  76274. return 1;
  76275. #else
  76276. static int g_have_simd;
  76277. int CPUInfo[4];
  76278. #ifdef MINIMP3_TEST
  76279. static int g_counter;
  76280. if (g_counter++ > 100)
  76281. return 0;
  76282. #endif
  76283. if (g_have_simd)
  76284. goto end;
  76285. ma_dr_mp3_cpuid(CPUInfo, 0);
  76286. if (CPUInfo[0] > 0)
  76287. {
  76288. ma_dr_mp3_cpuid(CPUInfo, 1);
  76289. g_have_simd = (CPUInfo[3] & (1 << 26)) + 1;
  76290. return g_have_simd - 1;
  76291. }
  76292. end:
  76293. return g_have_simd - 1;
  76294. #endif
  76295. }
  76296. #elif defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)
  76297. #include <arm_neon.h>
  76298. #define MA_DR_MP3_HAVE_SSE 0
  76299. #define MA_DR_MP3_HAVE_SIMD 1
  76300. #define MA_DR_MP3_VSTORE vst1q_f32
  76301. #define MA_DR_MP3_VLD vld1q_f32
  76302. #define MA_DR_MP3_VSET vmovq_n_f32
  76303. #define MA_DR_MP3_VADD vaddq_f32
  76304. #define MA_DR_MP3_VSUB vsubq_f32
  76305. #define MA_DR_MP3_VMUL vmulq_f32
  76306. #define MA_DR_MP3_VMAC(a, x, y) vmlaq_f32(a, x, y)
  76307. #define MA_DR_MP3_VMSB(a, x, y) vmlsq_f32(a, x, y)
  76308. #define MA_DR_MP3_VMUL_S(x, s) vmulq_f32(x, vmovq_n_f32(s))
  76309. #define MA_DR_MP3_VREV(x) vcombine_f32(vget_high_f32(vrev64q_f32(x)), vget_low_f32(vrev64q_f32(x)))
  76310. typedef float32x4_t ma_dr_mp3_f4;
  76311. static int ma_dr_mp3_have_simd(void)
  76312. {
  76313. return 1;
  76314. }
  76315. #else
  76316. #define MA_DR_MP3_HAVE_SSE 0
  76317. #define MA_DR_MP3_HAVE_SIMD 0
  76318. #ifdef MA_DR_MP3_ONLY_SIMD
  76319. #error MA_DR_MP3_ONLY_SIMD used, but SSE/NEON not enabled
  76320. #endif
  76321. #endif
  76322. #else
  76323. #define MA_DR_MP3_HAVE_SIMD 0
  76324. #endif
  76325. #if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) && !defined(__aarch64__) && !defined(_M_ARM64) && !defined(__ARM_ARCH_6M__)
  76326. #define MA_DR_MP3_HAVE_ARMV6 1
  76327. static __inline__ __attribute__((always_inline)) ma_int32 ma_dr_mp3_clip_int16_arm(ma_int32 a)
  76328. {
  76329. ma_int32 x = 0;
  76330. __asm__ ("ssat %0, #16, %1" : "=r"(x) : "r"(a));
  76331. return x;
  76332. }
  76333. #else
  76334. #define MA_DR_MP3_HAVE_ARMV6 0
  76335. #endif
  76336. #ifndef MA_DR_MP3_ASSERT
  76337. #include <assert.h>
  76338. #define MA_DR_MP3_ASSERT(expression) assert(expression)
  76339. #endif
  76340. #ifndef MA_DR_MP3_COPY_MEMORY
  76341. #define MA_DR_MP3_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  76342. #endif
  76343. #ifndef MA_DR_MP3_MOVE_MEMORY
  76344. #define MA_DR_MP3_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz))
  76345. #endif
  76346. #ifndef MA_DR_MP3_ZERO_MEMORY
  76347. #define MA_DR_MP3_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  76348. #endif
  76349. #define MA_DR_MP3_ZERO_OBJECT(p) MA_DR_MP3_ZERO_MEMORY((p), sizeof(*(p)))
  76350. #ifndef MA_DR_MP3_MALLOC
  76351. #define MA_DR_MP3_MALLOC(sz) malloc((sz))
  76352. #endif
  76353. #ifndef MA_DR_MP3_REALLOC
  76354. #define MA_DR_MP3_REALLOC(p, sz) realloc((p), (sz))
  76355. #endif
  76356. #ifndef MA_DR_MP3_FREE
  76357. #define MA_DR_MP3_FREE(p) free((p))
  76358. #endif
  76359. typedef struct
  76360. {
  76361. const ma_uint8 *buf;
  76362. int pos, limit;
  76363. } ma_dr_mp3_bs;
  76364. typedef struct
  76365. {
  76366. float scf[3*64];
  76367. ma_uint8 total_bands, stereo_bands, bitalloc[64], scfcod[64];
  76368. } ma_dr_mp3_L12_scale_info;
  76369. typedef struct
  76370. {
  76371. ma_uint8 tab_offset, code_tab_width, band_count;
  76372. } ma_dr_mp3_L12_subband_alloc;
  76373. typedef struct
  76374. {
  76375. const ma_uint8 *sfbtab;
  76376. ma_uint16 part_23_length, big_values, scalefac_compress;
  76377. ma_uint8 global_gain, block_type, mixed_block_flag, n_long_sfb, n_short_sfb;
  76378. ma_uint8 table_select[3], region_count[3], subblock_gain[3];
  76379. ma_uint8 preflag, scalefac_scale, count1_table, scfsi;
  76380. } ma_dr_mp3_L3_gr_info;
  76381. typedef struct
  76382. {
  76383. ma_dr_mp3_bs bs;
  76384. ma_uint8 maindata[MA_DR_MP3_MAX_BITRESERVOIR_BYTES + MA_DR_MP3_MAX_L3_FRAME_PAYLOAD_BYTES];
  76385. ma_dr_mp3_L3_gr_info gr_info[4];
  76386. float grbuf[2][576], scf[40], syn[18 + 15][2*32];
  76387. ma_uint8 ist_pos[2][39];
  76388. } ma_dr_mp3dec_scratch;
  76389. static void ma_dr_mp3_bs_init(ma_dr_mp3_bs *bs, const ma_uint8 *data, int bytes)
  76390. {
  76391. bs->buf = data;
  76392. bs->pos = 0;
  76393. bs->limit = bytes*8;
  76394. }
  76395. static ma_uint32 ma_dr_mp3_bs_get_bits(ma_dr_mp3_bs *bs, int n)
  76396. {
  76397. ma_uint32 next, cache = 0, s = bs->pos & 7;
  76398. int shl = n + s;
  76399. const ma_uint8 *p = bs->buf + (bs->pos >> 3);
  76400. if ((bs->pos += n) > bs->limit)
  76401. return 0;
  76402. next = *p++ & (255 >> s);
  76403. while ((shl -= 8) > 0)
  76404. {
  76405. cache |= next << shl;
  76406. next = *p++;
  76407. }
  76408. return cache | (next >> -shl);
  76409. }
  76410. static int ma_dr_mp3_hdr_valid(const ma_uint8 *h)
  76411. {
  76412. return h[0] == 0xff &&
  76413. ((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) &&
  76414. (MA_DR_MP3_HDR_GET_LAYER(h) != 0) &&
  76415. (MA_DR_MP3_HDR_GET_BITRATE(h) != 15) &&
  76416. (MA_DR_MP3_HDR_GET_SAMPLE_RATE(h) != 3);
  76417. }
  76418. static int ma_dr_mp3_hdr_compare(const ma_uint8 *h1, const ma_uint8 *h2)
  76419. {
  76420. return ma_dr_mp3_hdr_valid(h2) &&
  76421. ((h1[1] ^ h2[1]) & 0xFE) == 0 &&
  76422. ((h1[2] ^ h2[2]) & 0x0C) == 0 &&
  76423. !(MA_DR_MP3_HDR_IS_FREE_FORMAT(h1) ^ MA_DR_MP3_HDR_IS_FREE_FORMAT(h2));
  76424. }
  76425. static unsigned ma_dr_mp3_hdr_bitrate_kbps(const ma_uint8 *h)
  76426. {
  76427. static const ma_uint8 halfrate[2][3][15] = {
  76428. { { 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 } },
  76429. { { 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 } },
  76430. };
  76431. return 2*halfrate[!!MA_DR_MP3_HDR_TEST_MPEG1(h)][MA_DR_MP3_HDR_GET_LAYER(h) - 1][MA_DR_MP3_HDR_GET_BITRATE(h)];
  76432. }
  76433. static unsigned ma_dr_mp3_hdr_sample_rate_hz(const ma_uint8 *h)
  76434. {
  76435. static const unsigned g_hz[3] = { 44100, 48000, 32000 };
  76436. return g_hz[MA_DR_MP3_HDR_GET_SAMPLE_RATE(h)] >> (int)!MA_DR_MP3_HDR_TEST_MPEG1(h) >> (int)!MA_DR_MP3_HDR_TEST_NOT_MPEG25(h);
  76437. }
  76438. static unsigned ma_dr_mp3_hdr_frame_samples(const ma_uint8 *h)
  76439. {
  76440. return MA_DR_MP3_HDR_IS_LAYER_1(h) ? 384 : (1152 >> (int)MA_DR_MP3_HDR_IS_FRAME_576(h));
  76441. }
  76442. static int ma_dr_mp3_hdr_frame_bytes(const ma_uint8 *h, int free_format_size)
  76443. {
  76444. int frame_bytes = ma_dr_mp3_hdr_frame_samples(h)*ma_dr_mp3_hdr_bitrate_kbps(h)*125/ma_dr_mp3_hdr_sample_rate_hz(h);
  76445. if (MA_DR_MP3_HDR_IS_LAYER_1(h))
  76446. {
  76447. frame_bytes &= ~3;
  76448. }
  76449. return frame_bytes ? frame_bytes : free_format_size;
  76450. }
  76451. static int ma_dr_mp3_hdr_padding(const ma_uint8 *h)
  76452. {
  76453. return MA_DR_MP3_HDR_TEST_PADDING(h) ? (MA_DR_MP3_HDR_IS_LAYER_1(h) ? 4 : 1) : 0;
  76454. }
  76455. #ifndef MA_DR_MP3_ONLY_MP3
  76456. static const ma_dr_mp3_L12_subband_alloc *ma_dr_mp3_L12_subband_alloc_table(const ma_uint8 *hdr, ma_dr_mp3_L12_scale_info *sci)
  76457. {
  76458. const ma_dr_mp3_L12_subband_alloc *alloc;
  76459. int mode = MA_DR_MP3_HDR_GET_STEREO_MODE(hdr);
  76460. int nbands, stereo_bands = (mode == MA_DR_MP3_MODE_MONO) ? 0 : (mode == MA_DR_MP3_MODE_JOINT_STEREO) ? (MA_DR_MP3_HDR_GET_STEREO_MODE_EXT(hdr) << 2) + 4 : 32;
  76461. if (MA_DR_MP3_HDR_IS_LAYER_1(hdr))
  76462. {
  76463. static const ma_dr_mp3_L12_subband_alloc g_alloc_L1[] = { { 76, 4, 32 } };
  76464. alloc = g_alloc_L1;
  76465. nbands = 32;
  76466. } else if (!MA_DR_MP3_HDR_TEST_MPEG1(hdr))
  76467. {
  76468. static const ma_dr_mp3_L12_subband_alloc g_alloc_L2M2[] = { { 60, 4, 4 }, { 44, 3, 7 }, { 44, 2, 19 } };
  76469. alloc = g_alloc_L2M2;
  76470. nbands = 30;
  76471. } else
  76472. {
  76473. static const ma_dr_mp3_L12_subband_alloc g_alloc_L2M1[] = { { 0, 4, 3 }, { 16, 4, 8 }, { 32, 3, 12 }, { 40, 2, 7 } };
  76474. int sample_rate_idx = MA_DR_MP3_HDR_GET_SAMPLE_RATE(hdr);
  76475. unsigned kbps = ma_dr_mp3_hdr_bitrate_kbps(hdr) >> (int)(mode != MA_DR_MP3_MODE_MONO);
  76476. if (!kbps)
  76477. {
  76478. kbps = 192;
  76479. }
  76480. alloc = g_alloc_L2M1;
  76481. nbands = 27;
  76482. if (kbps < 56)
  76483. {
  76484. static const ma_dr_mp3_L12_subband_alloc g_alloc_L2M1_lowrate[] = { { 44, 4, 2 }, { 44, 3, 10 } };
  76485. alloc = g_alloc_L2M1_lowrate;
  76486. nbands = sample_rate_idx == 2 ? 12 : 8;
  76487. } else if (kbps >= 96 && sample_rate_idx != 1)
  76488. {
  76489. nbands = 30;
  76490. }
  76491. }
  76492. sci->total_bands = (ma_uint8)nbands;
  76493. sci->stereo_bands = (ma_uint8)MA_DR_MP3_MIN(stereo_bands, nbands);
  76494. return alloc;
  76495. }
  76496. static void ma_dr_mp3_L12_read_scalefactors(ma_dr_mp3_bs *bs, ma_uint8 *pba, ma_uint8 *scfcod, int bands, float *scf)
  76497. {
  76498. static const float g_deq_L12[18*3] = {
  76499. #define MA_DR_MP3_DQ(x) 9.53674316e-07f/x, 7.56931807e-07f/x, 6.00777173e-07f/x
  76500. MA_DR_MP3_DQ(3),MA_DR_MP3_DQ(7),MA_DR_MP3_DQ(15),MA_DR_MP3_DQ(31),MA_DR_MP3_DQ(63),MA_DR_MP3_DQ(127),MA_DR_MP3_DQ(255),MA_DR_MP3_DQ(511),MA_DR_MP3_DQ(1023),MA_DR_MP3_DQ(2047),MA_DR_MP3_DQ(4095),MA_DR_MP3_DQ(8191),MA_DR_MP3_DQ(16383),MA_DR_MP3_DQ(32767),MA_DR_MP3_DQ(65535),MA_DR_MP3_DQ(3),MA_DR_MP3_DQ(5),MA_DR_MP3_DQ(9)
  76501. };
  76502. int i, m;
  76503. for (i = 0; i < bands; i++)
  76504. {
  76505. float s = 0;
  76506. int ba = *pba++;
  76507. int mask = ba ? 4 + ((19 >> scfcod[i]) & 3) : 0;
  76508. for (m = 4; m; m >>= 1)
  76509. {
  76510. if (mask & m)
  76511. {
  76512. int b = ma_dr_mp3_bs_get_bits(bs, 6);
  76513. s = g_deq_L12[ba*3 - 6 + b % 3]*(int)(1 << 21 >> b/3);
  76514. }
  76515. *scf++ = s;
  76516. }
  76517. }
  76518. }
  76519. static void ma_dr_mp3_L12_read_scale_info(const ma_uint8 *hdr, ma_dr_mp3_bs *bs, ma_dr_mp3_L12_scale_info *sci)
  76520. {
  76521. static const ma_uint8 g_bitalloc_code_tab[] = {
  76522. 0,17, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16,
  76523. 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,16,
  76524. 0,17,18, 3,19,4,5,16,
  76525. 0,17,18,16,
  76526. 0,17,18,19, 4,5,6, 7,8, 9,10,11,12,13,14,15,
  76527. 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,14,
  76528. 0, 2, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16
  76529. };
  76530. const ma_dr_mp3_L12_subband_alloc *subband_alloc = ma_dr_mp3_L12_subband_alloc_table(hdr, sci);
  76531. int i, k = 0, ba_bits = 0;
  76532. const ma_uint8 *ba_code_tab = g_bitalloc_code_tab;
  76533. for (i = 0; i < sci->total_bands; i++)
  76534. {
  76535. ma_uint8 ba;
  76536. if (i == k)
  76537. {
  76538. k += subband_alloc->band_count;
  76539. ba_bits = subband_alloc->code_tab_width;
  76540. ba_code_tab = g_bitalloc_code_tab + subband_alloc->tab_offset;
  76541. subband_alloc++;
  76542. }
  76543. ba = ba_code_tab[ma_dr_mp3_bs_get_bits(bs, ba_bits)];
  76544. sci->bitalloc[2*i] = ba;
  76545. if (i < sci->stereo_bands)
  76546. {
  76547. ba = ba_code_tab[ma_dr_mp3_bs_get_bits(bs, ba_bits)];
  76548. }
  76549. sci->bitalloc[2*i + 1] = sci->stereo_bands ? ba : 0;
  76550. }
  76551. for (i = 0; i < 2*sci->total_bands; i++)
  76552. {
  76553. sci->scfcod[i] = (ma_uint8)(sci->bitalloc[i] ? MA_DR_MP3_HDR_IS_LAYER_1(hdr) ? 2 : ma_dr_mp3_bs_get_bits(bs, 2) : 6);
  76554. }
  76555. ma_dr_mp3_L12_read_scalefactors(bs, sci->bitalloc, sci->scfcod, sci->total_bands*2, sci->scf);
  76556. for (i = sci->stereo_bands; i < sci->total_bands; i++)
  76557. {
  76558. sci->bitalloc[2*i + 1] = 0;
  76559. }
  76560. }
  76561. static int ma_dr_mp3_L12_dequantize_granule(float *grbuf, ma_dr_mp3_bs *bs, ma_dr_mp3_L12_scale_info *sci, int group_size)
  76562. {
  76563. int i, j, k, choff = 576;
  76564. for (j = 0; j < 4; j++)
  76565. {
  76566. float *dst = grbuf + group_size*j;
  76567. for (i = 0; i < 2*sci->total_bands; i++)
  76568. {
  76569. int ba = sci->bitalloc[i];
  76570. if (ba != 0)
  76571. {
  76572. if (ba < 17)
  76573. {
  76574. int half = (1 << (ba - 1)) - 1;
  76575. for (k = 0; k < group_size; k++)
  76576. {
  76577. dst[k] = (float)((int)ma_dr_mp3_bs_get_bits(bs, ba) - half);
  76578. }
  76579. } else
  76580. {
  76581. unsigned mod = (2 << (ba - 17)) + 1;
  76582. unsigned code = ma_dr_mp3_bs_get_bits(bs, mod + 2 - (mod >> 3));
  76583. for (k = 0; k < group_size; k++, code /= mod)
  76584. {
  76585. dst[k] = (float)((int)(code % mod - mod/2));
  76586. }
  76587. }
  76588. }
  76589. dst += choff;
  76590. choff = 18 - choff;
  76591. }
  76592. }
  76593. return group_size*4;
  76594. }
  76595. static void ma_dr_mp3_L12_apply_scf_384(ma_dr_mp3_L12_scale_info *sci, const float *scf, float *dst)
  76596. {
  76597. int i, k;
  76598. MA_DR_MP3_COPY_MEMORY(dst + 576 + sci->stereo_bands*18, dst + sci->stereo_bands*18, (sci->total_bands - sci->stereo_bands)*18*sizeof(float));
  76599. for (i = 0; i < sci->total_bands; i++, dst += 18, scf += 6)
  76600. {
  76601. for (k = 0; k < 12; k++)
  76602. {
  76603. dst[k + 0] *= scf[0];
  76604. dst[k + 576] *= scf[3];
  76605. }
  76606. }
  76607. }
  76608. #endif
  76609. static int ma_dr_mp3_L3_read_side_info(ma_dr_mp3_bs *bs, ma_dr_mp3_L3_gr_info *gr, const ma_uint8 *hdr)
  76610. {
  76611. static const ma_uint8 g_scf_long[8][23] = {
  76612. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  76613. { 12,12,12,12,12,12,16,20,24,28,32,40,48,56,64,76,90,2,2,2,2,2,0 },
  76614. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  76615. { 6,6,6,6,6,6,8,10,12,14,16,18,22,26,32,38,46,54,62,70,76,36,0 },
  76616. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  76617. { 4,4,4,4,4,4,6,6,8,8,10,12,16,20,24,28,34,42,50,54,76,158,0 },
  76618. { 4,4,4,4,4,4,6,6,6,8,10,12,16,18,22,28,34,40,46,54,54,192,0 },
  76619. { 4,4,4,4,4,4,6,6,8,10,12,16,20,24,30,38,46,56,68,84,102,26,0 }
  76620. };
  76621. static const ma_uint8 g_scf_short[8][40] = {
  76622. { 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 },
  76623. { 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 },
  76624. { 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 },
  76625. { 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 },
  76626. { 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 },
  76627. { 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 },
  76628. { 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 },
  76629. { 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 }
  76630. };
  76631. static const ma_uint8 g_scf_mixed[8][40] = {
  76632. { 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 },
  76633. { 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 },
  76634. { 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 },
  76635. { 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 },
  76636. { 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 },
  76637. { 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 },
  76638. { 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 },
  76639. { 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 }
  76640. };
  76641. unsigned tables, scfsi = 0;
  76642. int main_data_begin, part_23_sum = 0;
  76643. int gr_count = MA_DR_MP3_HDR_IS_MONO(hdr) ? 1 : 2;
  76644. int sr_idx = MA_DR_MP3_HDR_GET_MY_SAMPLE_RATE(hdr); sr_idx -= (sr_idx != 0);
  76645. if (MA_DR_MP3_HDR_TEST_MPEG1(hdr))
  76646. {
  76647. gr_count *= 2;
  76648. main_data_begin = ma_dr_mp3_bs_get_bits(bs, 9);
  76649. scfsi = ma_dr_mp3_bs_get_bits(bs, 7 + gr_count);
  76650. } else
  76651. {
  76652. main_data_begin = ma_dr_mp3_bs_get_bits(bs, 8 + gr_count) >> gr_count;
  76653. }
  76654. do
  76655. {
  76656. if (MA_DR_MP3_HDR_IS_MONO(hdr))
  76657. {
  76658. scfsi <<= 4;
  76659. }
  76660. gr->part_23_length = (ma_uint16)ma_dr_mp3_bs_get_bits(bs, 12);
  76661. part_23_sum += gr->part_23_length;
  76662. gr->big_values = (ma_uint16)ma_dr_mp3_bs_get_bits(bs, 9);
  76663. if (gr->big_values > 288)
  76664. {
  76665. return -1;
  76666. }
  76667. gr->global_gain = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 8);
  76668. gr->scalefac_compress = (ma_uint16)ma_dr_mp3_bs_get_bits(bs, MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 4 : 9);
  76669. gr->sfbtab = g_scf_long[sr_idx];
  76670. gr->n_long_sfb = 22;
  76671. gr->n_short_sfb = 0;
  76672. if (ma_dr_mp3_bs_get_bits(bs, 1))
  76673. {
  76674. gr->block_type = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 2);
  76675. if (!gr->block_type)
  76676. {
  76677. return -1;
  76678. }
  76679. gr->mixed_block_flag = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 1);
  76680. gr->region_count[0] = 7;
  76681. gr->region_count[1] = 255;
  76682. if (gr->block_type == MA_DR_MP3_SHORT_BLOCK_TYPE)
  76683. {
  76684. scfsi &= 0x0F0F;
  76685. if (!gr->mixed_block_flag)
  76686. {
  76687. gr->region_count[0] = 8;
  76688. gr->sfbtab = g_scf_short[sr_idx];
  76689. gr->n_long_sfb = 0;
  76690. gr->n_short_sfb = 39;
  76691. } else
  76692. {
  76693. gr->sfbtab = g_scf_mixed[sr_idx];
  76694. gr->n_long_sfb = MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 8 : 6;
  76695. gr->n_short_sfb = 30;
  76696. }
  76697. }
  76698. tables = ma_dr_mp3_bs_get_bits(bs, 10);
  76699. tables <<= 5;
  76700. gr->subblock_gain[0] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3);
  76701. gr->subblock_gain[1] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3);
  76702. gr->subblock_gain[2] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3);
  76703. } else
  76704. {
  76705. gr->block_type = 0;
  76706. gr->mixed_block_flag = 0;
  76707. tables = ma_dr_mp3_bs_get_bits(bs, 15);
  76708. gr->region_count[0] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 4);
  76709. gr->region_count[1] = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 3);
  76710. gr->region_count[2] = 255;
  76711. }
  76712. gr->table_select[0] = (ma_uint8)(tables >> 10);
  76713. gr->table_select[1] = (ma_uint8)((tables >> 5) & 31);
  76714. gr->table_select[2] = (ma_uint8)((tables) & 31);
  76715. gr->preflag = (ma_uint8)(MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? ma_dr_mp3_bs_get_bits(bs, 1) : (gr->scalefac_compress >= 500));
  76716. gr->scalefac_scale = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 1);
  76717. gr->count1_table = (ma_uint8)ma_dr_mp3_bs_get_bits(bs, 1);
  76718. gr->scfsi = (ma_uint8)((scfsi >> 12) & 15);
  76719. scfsi <<= 4;
  76720. gr++;
  76721. } while(--gr_count);
  76722. if (part_23_sum + bs->pos > bs->limit + main_data_begin*8)
  76723. {
  76724. return -1;
  76725. }
  76726. return main_data_begin;
  76727. }
  76728. static void ma_dr_mp3_L3_read_scalefactors(ma_uint8 *scf, ma_uint8 *ist_pos, const ma_uint8 *scf_size, const ma_uint8 *scf_count, ma_dr_mp3_bs *bitbuf, int scfsi)
  76729. {
  76730. int i, k;
  76731. for (i = 0; i < 4 && scf_count[i]; i++, scfsi *= 2)
  76732. {
  76733. int cnt = scf_count[i];
  76734. if (scfsi & 8)
  76735. {
  76736. MA_DR_MP3_COPY_MEMORY(scf, ist_pos, cnt);
  76737. } else
  76738. {
  76739. int bits = scf_size[i];
  76740. if (!bits)
  76741. {
  76742. MA_DR_MP3_ZERO_MEMORY(scf, cnt);
  76743. MA_DR_MP3_ZERO_MEMORY(ist_pos, cnt);
  76744. } else
  76745. {
  76746. int max_scf = (scfsi < 0) ? (1 << bits) - 1 : -1;
  76747. for (k = 0; k < cnt; k++)
  76748. {
  76749. int s = ma_dr_mp3_bs_get_bits(bitbuf, bits);
  76750. ist_pos[k] = (ma_uint8)(s == max_scf ? -1 : s);
  76751. scf[k] = (ma_uint8)s;
  76752. }
  76753. }
  76754. }
  76755. ist_pos += cnt;
  76756. scf += cnt;
  76757. }
  76758. scf[0] = scf[1] = scf[2] = 0;
  76759. }
  76760. static float ma_dr_mp3_L3_ldexp_q2(float y, int exp_q2)
  76761. {
  76762. static const float g_expfrac[4] = { 9.31322575e-10f,7.83145814e-10f,6.58544508e-10f,5.53767716e-10f };
  76763. int e;
  76764. do
  76765. {
  76766. e = MA_DR_MP3_MIN(30*4, exp_q2);
  76767. y *= g_expfrac[e & 3]*(1 << 30 >> (e >> 2));
  76768. } while ((exp_q2 -= e) > 0);
  76769. return y;
  76770. }
  76771. static void ma_dr_mp3_L3_decode_scalefactors(const ma_uint8 *hdr, ma_uint8 *ist_pos, ma_dr_mp3_bs *bs, const ma_dr_mp3_L3_gr_info *gr, float *scf, int ch)
  76772. {
  76773. static const ma_uint8 g_scf_partitions[3][28] = {
  76774. { 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 },
  76775. { 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 },
  76776. { 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 }
  76777. };
  76778. const ma_uint8 *scf_partition = g_scf_partitions[!!gr->n_short_sfb + !gr->n_long_sfb];
  76779. ma_uint8 scf_size[4], iscf[40];
  76780. int i, scf_shift = gr->scalefac_scale + 1, gain_exp, scfsi = gr->scfsi;
  76781. float gain;
  76782. if (MA_DR_MP3_HDR_TEST_MPEG1(hdr))
  76783. {
  76784. static const ma_uint8 g_scfc_decode[16] = { 0,1,2,3, 12,5,6,7, 9,10,11,13, 14,15,18,19 };
  76785. int part = g_scfc_decode[gr->scalefac_compress];
  76786. scf_size[1] = scf_size[0] = (ma_uint8)(part >> 2);
  76787. scf_size[3] = scf_size[2] = (ma_uint8)(part & 3);
  76788. } else
  76789. {
  76790. static const ma_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 };
  76791. int k, modprod, sfc, ist = MA_DR_MP3_HDR_TEST_I_STEREO(hdr) && ch;
  76792. sfc = gr->scalefac_compress >> ist;
  76793. for (k = ist*3*4; sfc >= 0; sfc -= modprod, k += 4)
  76794. {
  76795. for (modprod = 1, i = 3; i >= 0; i--)
  76796. {
  76797. scf_size[i] = (ma_uint8)(sfc / modprod % g_mod[k + i]);
  76798. modprod *= g_mod[k + i];
  76799. }
  76800. }
  76801. scf_partition += k;
  76802. scfsi = -16;
  76803. }
  76804. ma_dr_mp3_L3_read_scalefactors(iscf, ist_pos, scf_size, scf_partition, bs, scfsi);
  76805. if (gr->n_short_sfb)
  76806. {
  76807. int sh = 3 - scf_shift;
  76808. for (i = 0; i < gr->n_short_sfb; i += 3)
  76809. {
  76810. iscf[gr->n_long_sfb + i + 0] = (ma_uint8)(iscf[gr->n_long_sfb + i + 0] + (gr->subblock_gain[0] << sh));
  76811. iscf[gr->n_long_sfb + i + 1] = (ma_uint8)(iscf[gr->n_long_sfb + i + 1] + (gr->subblock_gain[1] << sh));
  76812. iscf[gr->n_long_sfb + i + 2] = (ma_uint8)(iscf[gr->n_long_sfb + i + 2] + (gr->subblock_gain[2] << sh));
  76813. }
  76814. } else if (gr->preflag)
  76815. {
  76816. static const ma_uint8 g_preamp[10] = { 1,1,1,1,2,2,3,3,3,2 };
  76817. for (i = 0; i < 10; i++)
  76818. {
  76819. iscf[11 + i] = (ma_uint8)(iscf[11 + i] + g_preamp[i]);
  76820. }
  76821. }
  76822. gain_exp = gr->global_gain + MA_DR_MP3_BITS_DEQUANTIZER_OUT*4 - 210 - (MA_DR_MP3_HDR_IS_MS_STEREO(hdr) ? 2 : 0);
  76823. gain = ma_dr_mp3_L3_ldexp_q2(1 << (MA_DR_MP3_MAX_SCFI/4), MA_DR_MP3_MAX_SCFI - gain_exp);
  76824. for (i = 0; i < (int)(gr->n_long_sfb + gr->n_short_sfb); i++)
  76825. {
  76826. scf[i] = ma_dr_mp3_L3_ldexp_q2(gain, iscf[i] << scf_shift);
  76827. }
  76828. }
  76829. static const float g_ma_dr_mp3_pow43[129 + 16] = {
  76830. 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,
  76831. 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
  76832. };
  76833. static float ma_dr_mp3_L3_pow_43(int x)
  76834. {
  76835. float frac;
  76836. int sign, mult = 256;
  76837. if (x < 129)
  76838. {
  76839. return g_ma_dr_mp3_pow43[16 + x];
  76840. }
  76841. if (x < 1024)
  76842. {
  76843. mult = 16;
  76844. x <<= 3;
  76845. }
  76846. sign = 2*x & 64;
  76847. frac = (float)((x & 63) - sign) / ((x & ~63) + sign);
  76848. return g_ma_dr_mp3_pow43[16 + ((x + sign) >> 6)]*(1.f + frac*((4.f/3) + frac*(2.f/9)))*mult;
  76849. }
  76850. static void ma_dr_mp3_L3_huffman(float *dst, ma_dr_mp3_bs *bs, const ma_dr_mp3_L3_gr_info *gr_info, const float *scf, int layer3gr_limit)
  76851. {
  76852. static const ma_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,
  76853. 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,
  76854. -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,
  76855. -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,
  76856. -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,
  76857. -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,
  76858. -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,
  76859. -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,
  76860. -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,
  76861. -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,
  76862. -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,
  76863. -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,
  76864. -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,
  76865. -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,
  76866. -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,
  76867. -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 };
  76868. static const ma_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};
  76869. static const ma_uint8 tab33[] = { 252,236,220,204,188,172,156,140,124,108,92,76,60,44,28,12 };
  76870. static const ma_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 };
  76871. static const ma_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 };
  76872. #define MA_DR_MP3_PEEK_BITS(n) (bs_cache >> (32 - (n)))
  76873. #define MA_DR_MP3_FLUSH_BITS(n) { bs_cache <<= (n); bs_sh += (n); }
  76874. #define MA_DR_MP3_CHECK_BITS while (bs_sh >= 0) { bs_cache |= (ma_uint32)*bs_next_ptr++ << bs_sh; bs_sh -= 8; }
  76875. #define MA_DR_MP3_BSPOS ((bs_next_ptr - bs->buf)*8 - 24 + bs_sh)
  76876. float one = 0.0f;
  76877. int ireg = 0, big_val_cnt = gr_info->big_values;
  76878. const ma_uint8 *sfb = gr_info->sfbtab;
  76879. const ma_uint8 *bs_next_ptr = bs->buf + bs->pos/8;
  76880. ma_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);
  76881. int pairs_to_decode, np, bs_sh = (bs->pos & 7) - 8;
  76882. bs_next_ptr += 4;
  76883. while (big_val_cnt > 0)
  76884. {
  76885. int tab_num = gr_info->table_select[ireg];
  76886. int sfb_cnt = gr_info->region_count[ireg++];
  76887. const ma_int16 *codebook = tabs + tabindex[tab_num];
  76888. int linbits = g_linbits[tab_num];
  76889. if (linbits)
  76890. {
  76891. do
  76892. {
  76893. np = *sfb++ / 2;
  76894. pairs_to_decode = MA_DR_MP3_MIN(big_val_cnt, np);
  76895. one = *scf++;
  76896. do
  76897. {
  76898. int j, w = 5;
  76899. int leaf = codebook[MA_DR_MP3_PEEK_BITS(w)];
  76900. while (leaf < 0)
  76901. {
  76902. MA_DR_MP3_FLUSH_BITS(w);
  76903. w = leaf & 7;
  76904. leaf = codebook[MA_DR_MP3_PEEK_BITS(w) - (leaf >> 3)];
  76905. }
  76906. MA_DR_MP3_FLUSH_BITS(leaf >> 8);
  76907. for (j = 0; j < 2; j++, dst++, leaf >>= 4)
  76908. {
  76909. int lsb = leaf & 0x0F;
  76910. if (lsb == 15)
  76911. {
  76912. lsb += MA_DR_MP3_PEEK_BITS(linbits);
  76913. MA_DR_MP3_FLUSH_BITS(linbits);
  76914. MA_DR_MP3_CHECK_BITS;
  76915. *dst = one*ma_dr_mp3_L3_pow_43(lsb)*((ma_int32)bs_cache < 0 ? -1: 1);
  76916. } else
  76917. {
  76918. *dst = g_ma_dr_mp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
  76919. }
  76920. MA_DR_MP3_FLUSH_BITS(lsb ? 1 : 0);
  76921. }
  76922. MA_DR_MP3_CHECK_BITS;
  76923. } while (--pairs_to_decode);
  76924. } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
  76925. } else
  76926. {
  76927. do
  76928. {
  76929. np = *sfb++ / 2;
  76930. pairs_to_decode = MA_DR_MP3_MIN(big_val_cnt, np);
  76931. one = *scf++;
  76932. do
  76933. {
  76934. int j, w = 5;
  76935. int leaf = codebook[MA_DR_MP3_PEEK_BITS(w)];
  76936. while (leaf < 0)
  76937. {
  76938. MA_DR_MP3_FLUSH_BITS(w);
  76939. w = leaf & 7;
  76940. leaf = codebook[MA_DR_MP3_PEEK_BITS(w) - (leaf >> 3)];
  76941. }
  76942. MA_DR_MP3_FLUSH_BITS(leaf >> 8);
  76943. for (j = 0; j < 2; j++, dst++, leaf >>= 4)
  76944. {
  76945. int lsb = leaf & 0x0F;
  76946. *dst = g_ma_dr_mp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
  76947. MA_DR_MP3_FLUSH_BITS(lsb ? 1 : 0);
  76948. }
  76949. MA_DR_MP3_CHECK_BITS;
  76950. } while (--pairs_to_decode);
  76951. } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
  76952. }
  76953. }
  76954. for (np = 1 - big_val_cnt;; dst += 4)
  76955. {
  76956. const ma_uint8 *codebook_count1 = (gr_info->count1_table) ? tab33 : tab32;
  76957. int leaf = codebook_count1[MA_DR_MP3_PEEK_BITS(4)];
  76958. if (!(leaf & 8))
  76959. {
  76960. leaf = codebook_count1[(leaf >> 3) + (bs_cache << 4 >> (32 - (leaf & 3)))];
  76961. }
  76962. MA_DR_MP3_FLUSH_BITS(leaf & 7);
  76963. if (MA_DR_MP3_BSPOS > layer3gr_limit)
  76964. {
  76965. break;
  76966. }
  76967. #define MA_DR_MP3_RELOAD_SCALEFACTOR if (!--np) { np = *sfb++/2; if (!np) break; one = *scf++; }
  76968. #define MA_DR_MP3_DEQ_COUNT1(s) if (leaf & (128 >> s)) { dst[s] = ((ma_int32)bs_cache < 0) ? -one : one; MA_DR_MP3_FLUSH_BITS(1) }
  76969. MA_DR_MP3_RELOAD_SCALEFACTOR;
  76970. MA_DR_MP3_DEQ_COUNT1(0);
  76971. MA_DR_MP3_DEQ_COUNT1(1);
  76972. MA_DR_MP3_RELOAD_SCALEFACTOR;
  76973. MA_DR_MP3_DEQ_COUNT1(2);
  76974. MA_DR_MP3_DEQ_COUNT1(3);
  76975. MA_DR_MP3_CHECK_BITS;
  76976. }
  76977. bs->pos = layer3gr_limit;
  76978. }
  76979. static void ma_dr_mp3_L3_midside_stereo(float *left, int n)
  76980. {
  76981. int i = 0;
  76982. float *right = left + 576;
  76983. #if MA_DR_MP3_HAVE_SIMD
  76984. if (ma_dr_mp3_have_simd())
  76985. {
  76986. for (; i < n - 3; i += 4)
  76987. {
  76988. ma_dr_mp3_f4 vl = MA_DR_MP3_VLD(left + i);
  76989. ma_dr_mp3_f4 vr = MA_DR_MP3_VLD(right + i);
  76990. MA_DR_MP3_VSTORE(left + i, MA_DR_MP3_VADD(vl, vr));
  76991. MA_DR_MP3_VSTORE(right + i, MA_DR_MP3_VSUB(vl, vr));
  76992. }
  76993. #ifdef __GNUC__
  76994. if (__builtin_constant_p(n % 4 == 0) && n % 4 == 0)
  76995. return;
  76996. #endif
  76997. }
  76998. #endif
  76999. for (; i < n; i++)
  77000. {
  77001. float a = left[i];
  77002. float b = right[i];
  77003. left[i] = a + b;
  77004. right[i] = a - b;
  77005. }
  77006. }
  77007. static void ma_dr_mp3_L3_intensity_stereo_band(float *left, int n, float kl, float kr)
  77008. {
  77009. int i;
  77010. for (i = 0; i < n; i++)
  77011. {
  77012. left[i + 576] = left[i]*kr;
  77013. left[i] = left[i]*kl;
  77014. }
  77015. }
  77016. static void ma_dr_mp3_L3_stereo_top_band(const float *right, const ma_uint8 *sfb, int nbands, int max_band[3])
  77017. {
  77018. int i, k;
  77019. max_band[0] = max_band[1] = max_band[2] = -1;
  77020. for (i = 0; i < nbands; i++)
  77021. {
  77022. for (k = 0; k < sfb[i]; k += 2)
  77023. {
  77024. if (right[k] != 0 || right[k + 1] != 0)
  77025. {
  77026. max_band[i % 3] = i;
  77027. break;
  77028. }
  77029. }
  77030. right += sfb[i];
  77031. }
  77032. }
  77033. static void ma_dr_mp3_L3_stereo_process(float *left, const ma_uint8 *ist_pos, const ma_uint8 *sfb, const ma_uint8 *hdr, int max_band[3], int mpeg2_sh)
  77034. {
  77035. 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 };
  77036. unsigned i, max_pos = MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 7 : 64;
  77037. for (i = 0; sfb[i]; i++)
  77038. {
  77039. unsigned ipos = ist_pos[i];
  77040. if ((int)i > max_band[i % 3] && ipos < max_pos)
  77041. {
  77042. float kl, kr, s = MA_DR_MP3_HDR_TEST_MS_STEREO(hdr) ? 1.41421356f : 1;
  77043. if (MA_DR_MP3_HDR_TEST_MPEG1(hdr))
  77044. {
  77045. kl = g_pan[2*ipos];
  77046. kr = g_pan[2*ipos + 1];
  77047. } else
  77048. {
  77049. kl = 1;
  77050. kr = ma_dr_mp3_L3_ldexp_q2(1, (ipos + 1) >> 1 << mpeg2_sh);
  77051. if (ipos & 1)
  77052. {
  77053. kl = kr;
  77054. kr = 1;
  77055. }
  77056. }
  77057. ma_dr_mp3_L3_intensity_stereo_band(left, sfb[i], kl*s, kr*s);
  77058. } else if (MA_DR_MP3_HDR_TEST_MS_STEREO(hdr))
  77059. {
  77060. ma_dr_mp3_L3_midside_stereo(left, sfb[i]);
  77061. }
  77062. left += sfb[i];
  77063. }
  77064. }
  77065. static void ma_dr_mp3_L3_intensity_stereo(float *left, ma_uint8 *ist_pos, const ma_dr_mp3_L3_gr_info *gr, const ma_uint8 *hdr)
  77066. {
  77067. int max_band[3], n_sfb = gr->n_long_sfb + gr->n_short_sfb;
  77068. int i, max_blocks = gr->n_short_sfb ? 3 : 1;
  77069. ma_dr_mp3_L3_stereo_top_band(left + 576, gr->sfbtab, n_sfb, max_band);
  77070. if (gr->n_long_sfb)
  77071. {
  77072. max_band[0] = max_band[1] = max_band[2] = MA_DR_MP3_MAX(MA_DR_MP3_MAX(max_band[0], max_band[1]), max_band[2]);
  77073. }
  77074. for (i = 0; i < max_blocks; i++)
  77075. {
  77076. int default_pos = MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 3 : 0;
  77077. int itop = n_sfb - max_blocks + i;
  77078. int prev = itop - max_blocks;
  77079. ist_pos[itop] = (ma_uint8)(max_band[i] >= prev ? default_pos : ist_pos[prev]);
  77080. }
  77081. ma_dr_mp3_L3_stereo_process(left, ist_pos, gr->sfbtab, hdr, max_band, gr[1].scalefac_compress & 1);
  77082. }
  77083. static void ma_dr_mp3_L3_reorder(float *grbuf, float *scratch, const ma_uint8 *sfb)
  77084. {
  77085. int i, len;
  77086. float *src = grbuf, *dst = scratch;
  77087. for (;0 != (len = *sfb); sfb += 3, src += 2*len)
  77088. {
  77089. for (i = 0; i < len; i++, src++)
  77090. {
  77091. *dst++ = src[0*len];
  77092. *dst++ = src[1*len];
  77093. *dst++ = src[2*len];
  77094. }
  77095. }
  77096. MA_DR_MP3_COPY_MEMORY(grbuf, scratch, (dst - scratch)*sizeof(float));
  77097. }
  77098. static void ma_dr_mp3_L3_antialias(float *grbuf, int nbands)
  77099. {
  77100. static const float g_aa[2][8] = {
  77101. {0.85749293f,0.88174200f,0.94962865f,0.98331459f,0.99551782f,0.99916056f,0.99989920f,0.99999316f},
  77102. {0.51449576f,0.47173197f,0.31337745f,0.18191320f,0.09457419f,0.04096558f,0.01419856f,0.00369997f}
  77103. };
  77104. for (; nbands > 0; nbands--, grbuf += 18)
  77105. {
  77106. int i = 0;
  77107. #if MA_DR_MP3_HAVE_SIMD
  77108. if (ma_dr_mp3_have_simd()) for (; i < 8; i += 4)
  77109. {
  77110. ma_dr_mp3_f4 vu = MA_DR_MP3_VLD(grbuf + 18 + i);
  77111. ma_dr_mp3_f4 vd = MA_DR_MP3_VLD(grbuf + 14 - i);
  77112. ma_dr_mp3_f4 vc0 = MA_DR_MP3_VLD(g_aa[0] + i);
  77113. ma_dr_mp3_f4 vc1 = MA_DR_MP3_VLD(g_aa[1] + i);
  77114. vd = MA_DR_MP3_VREV(vd);
  77115. MA_DR_MP3_VSTORE(grbuf + 18 + i, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vu, vc0), MA_DR_MP3_VMUL(vd, vc1)));
  77116. vd = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vu, vc1), MA_DR_MP3_VMUL(vd, vc0));
  77117. MA_DR_MP3_VSTORE(grbuf + 14 - i, MA_DR_MP3_VREV(vd));
  77118. }
  77119. #endif
  77120. #ifndef MA_DR_MP3_ONLY_SIMD
  77121. for(; i < 8; i++)
  77122. {
  77123. float u = grbuf[18 + i];
  77124. float d = grbuf[17 - i];
  77125. grbuf[18 + i] = u*g_aa[0][i] - d*g_aa[1][i];
  77126. grbuf[17 - i] = u*g_aa[1][i] + d*g_aa[0][i];
  77127. }
  77128. #endif
  77129. }
  77130. }
  77131. static void ma_dr_mp3_L3_dct3_9(float *y)
  77132. {
  77133. float s0, s1, s2, s3, s4, s5, s6, s7, s8, t0, t2, t4;
  77134. s0 = y[0]; s2 = y[2]; s4 = y[4]; s6 = y[6]; s8 = y[8];
  77135. t0 = s0 + s6*0.5f;
  77136. s0 -= s6;
  77137. t4 = (s4 + s2)*0.93969262f;
  77138. t2 = (s8 + s2)*0.76604444f;
  77139. s6 = (s4 - s8)*0.17364818f;
  77140. s4 += s8 - s2;
  77141. s2 = s0 - s4*0.5f;
  77142. y[4] = s4 + s0;
  77143. s8 = t0 - t2 + s6;
  77144. s0 = t0 - t4 + t2;
  77145. s4 = t0 + t4 - s6;
  77146. s1 = y[1]; s3 = y[3]; s5 = y[5]; s7 = y[7];
  77147. s3 *= 0.86602540f;
  77148. t0 = (s5 + s1)*0.98480775f;
  77149. t4 = (s5 - s7)*0.34202014f;
  77150. t2 = (s1 + s7)*0.64278761f;
  77151. s1 = (s1 - s5 - s7)*0.86602540f;
  77152. s5 = t0 - s3 - t2;
  77153. s7 = t4 - s3 - t0;
  77154. s3 = t4 + s3 - t2;
  77155. y[0] = s4 - s7;
  77156. y[1] = s2 + s1;
  77157. y[2] = s0 - s3;
  77158. y[3] = s8 + s5;
  77159. y[5] = s8 - s5;
  77160. y[6] = s0 + s3;
  77161. y[7] = s2 - s1;
  77162. y[8] = s4 + s7;
  77163. }
  77164. static void ma_dr_mp3_L3_imdct36(float *grbuf, float *overlap, const float *window, int nbands)
  77165. {
  77166. int i, j;
  77167. static const float g_twid9[18] = {
  77168. 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
  77169. };
  77170. for (j = 0; j < nbands; j++, grbuf += 18, overlap += 9)
  77171. {
  77172. float co[9], si[9];
  77173. co[0] = -grbuf[0];
  77174. si[0] = grbuf[17];
  77175. for (i = 0; i < 4; i++)
  77176. {
  77177. si[8 - 2*i] = grbuf[4*i + 1] - grbuf[4*i + 2];
  77178. co[1 + 2*i] = grbuf[4*i + 1] + grbuf[4*i + 2];
  77179. si[7 - 2*i] = grbuf[4*i + 4] - grbuf[4*i + 3];
  77180. co[2 + 2*i] = -(grbuf[4*i + 3] + grbuf[4*i + 4]);
  77181. }
  77182. ma_dr_mp3_L3_dct3_9(co);
  77183. ma_dr_mp3_L3_dct3_9(si);
  77184. si[1] = -si[1];
  77185. si[3] = -si[3];
  77186. si[5] = -si[5];
  77187. si[7] = -si[7];
  77188. i = 0;
  77189. #if MA_DR_MP3_HAVE_SIMD
  77190. if (ma_dr_mp3_have_simd()) for (; i < 8; i += 4)
  77191. {
  77192. ma_dr_mp3_f4 vovl = MA_DR_MP3_VLD(overlap + i);
  77193. ma_dr_mp3_f4 vc = MA_DR_MP3_VLD(co + i);
  77194. ma_dr_mp3_f4 vs = MA_DR_MP3_VLD(si + i);
  77195. ma_dr_mp3_f4 vr0 = MA_DR_MP3_VLD(g_twid9 + i);
  77196. ma_dr_mp3_f4 vr1 = MA_DR_MP3_VLD(g_twid9 + 9 + i);
  77197. ma_dr_mp3_f4 vw0 = MA_DR_MP3_VLD(window + i);
  77198. ma_dr_mp3_f4 vw1 = MA_DR_MP3_VLD(window + 9 + i);
  77199. ma_dr_mp3_f4 vsum = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vc, vr1), MA_DR_MP3_VMUL(vs, vr0));
  77200. MA_DR_MP3_VSTORE(overlap + i, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vc, vr0), MA_DR_MP3_VMUL(vs, vr1)));
  77201. MA_DR_MP3_VSTORE(grbuf + i, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vovl, vw0), MA_DR_MP3_VMUL(vsum, vw1)));
  77202. vsum = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vovl, vw1), MA_DR_MP3_VMUL(vsum, vw0));
  77203. MA_DR_MP3_VSTORE(grbuf + 14 - i, MA_DR_MP3_VREV(vsum));
  77204. }
  77205. #endif
  77206. for (; i < 9; i++)
  77207. {
  77208. float ovl = overlap[i];
  77209. float sum = co[i]*g_twid9[9 + i] + si[i]*g_twid9[0 + i];
  77210. overlap[i] = co[i]*g_twid9[0 + i] - si[i]*g_twid9[9 + i];
  77211. grbuf[i] = ovl*window[0 + i] - sum*window[9 + i];
  77212. grbuf[17 - i] = ovl*window[9 + i] + sum*window[0 + i];
  77213. }
  77214. }
  77215. }
  77216. static void ma_dr_mp3_L3_idct3(float x0, float x1, float x2, float *dst)
  77217. {
  77218. float m1 = x1*0.86602540f;
  77219. float a1 = x0 - x2*0.5f;
  77220. dst[1] = x0 + x2;
  77221. dst[0] = a1 + m1;
  77222. dst[2] = a1 - m1;
  77223. }
  77224. static void ma_dr_mp3_L3_imdct12(float *x, float *dst, float *overlap)
  77225. {
  77226. static const float g_twid3[6] = { 0.79335334f,0.92387953f,0.99144486f, 0.60876143f,0.38268343f,0.13052619f };
  77227. float co[3], si[3];
  77228. int i;
  77229. ma_dr_mp3_L3_idct3(-x[0], x[6] + x[3], x[12] + x[9], co);
  77230. ma_dr_mp3_L3_idct3(x[15], x[12] - x[9], x[6] - x[3], si);
  77231. si[1] = -si[1];
  77232. for (i = 0; i < 3; i++)
  77233. {
  77234. float ovl = overlap[i];
  77235. float sum = co[i]*g_twid3[3 + i] + si[i]*g_twid3[0 + i];
  77236. overlap[i] = co[i]*g_twid3[0 + i] - si[i]*g_twid3[3 + i];
  77237. dst[i] = ovl*g_twid3[2 - i] - sum*g_twid3[5 - i];
  77238. dst[5 - i] = ovl*g_twid3[5 - i] + sum*g_twid3[2 - i];
  77239. }
  77240. }
  77241. static void ma_dr_mp3_L3_imdct_short(float *grbuf, float *overlap, int nbands)
  77242. {
  77243. for (;nbands > 0; nbands--, overlap += 9, grbuf += 18)
  77244. {
  77245. float tmp[18];
  77246. MA_DR_MP3_COPY_MEMORY(tmp, grbuf, sizeof(tmp));
  77247. MA_DR_MP3_COPY_MEMORY(grbuf, overlap, 6*sizeof(float));
  77248. ma_dr_mp3_L3_imdct12(tmp, grbuf + 6, overlap + 6);
  77249. ma_dr_mp3_L3_imdct12(tmp + 1, grbuf + 12, overlap + 6);
  77250. ma_dr_mp3_L3_imdct12(tmp + 2, overlap, overlap + 6);
  77251. }
  77252. }
  77253. static void ma_dr_mp3_L3_change_sign(float *grbuf)
  77254. {
  77255. int b, i;
  77256. for (b = 0, grbuf += 18; b < 32; b += 2, grbuf += 36)
  77257. for (i = 1; i < 18; i += 2)
  77258. grbuf[i] = -grbuf[i];
  77259. }
  77260. static void ma_dr_mp3_L3_imdct_gr(float *grbuf, float *overlap, unsigned block_type, unsigned n_long_bands)
  77261. {
  77262. static const float g_mdct_window[2][18] = {
  77263. { 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 },
  77264. { 1,1,1,1,1,1,0.99144486f,0.92387953f,0.79335334f,0,0,0,0,0,0,0.13052619f,0.38268343f,0.60876143f }
  77265. };
  77266. if (n_long_bands)
  77267. {
  77268. ma_dr_mp3_L3_imdct36(grbuf, overlap, g_mdct_window[0], n_long_bands);
  77269. grbuf += 18*n_long_bands;
  77270. overlap += 9*n_long_bands;
  77271. }
  77272. if (block_type == MA_DR_MP3_SHORT_BLOCK_TYPE)
  77273. ma_dr_mp3_L3_imdct_short(grbuf, overlap, 32 - n_long_bands);
  77274. else
  77275. ma_dr_mp3_L3_imdct36(grbuf, overlap, g_mdct_window[block_type == MA_DR_MP3_STOP_BLOCK_TYPE], 32 - n_long_bands);
  77276. }
  77277. static void ma_dr_mp3_L3_save_reservoir(ma_dr_mp3dec *h, ma_dr_mp3dec_scratch *s)
  77278. {
  77279. int pos = (s->bs.pos + 7)/8u;
  77280. int remains = s->bs.limit/8u - pos;
  77281. if (remains > MA_DR_MP3_MAX_BITRESERVOIR_BYTES)
  77282. {
  77283. pos += remains - MA_DR_MP3_MAX_BITRESERVOIR_BYTES;
  77284. remains = MA_DR_MP3_MAX_BITRESERVOIR_BYTES;
  77285. }
  77286. if (remains > 0)
  77287. {
  77288. MA_DR_MP3_MOVE_MEMORY(h->reserv_buf, s->maindata + pos, remains);
  77289. }
  77290. h->reserv = remains;
  77291. }
  77292. static int ma_dr_mp3_L3_restore_reservoir(ma_dr_mp3dec *h, ma_dr_mp3_bs *bs, ma_dr_mp3dec_scratch *s, int main_data_begin)
  77293. {
  77294. int frame_bytes = (bs->limit - bs->pos)/8;
  77295. int bytes_have = MA_DR_MP3_MIN(h->reserv, main_data_begin);
  77296. MA_DR_MP3_COPY_MEMORY(s->maindata, h->reserv_buf + MA_DR_MP3_MAX(0, h->reserv - main_data_begin), MA_DR_MP3_MIN(h->reserv, main_data_begin));
  77297. MA_DR_MP3_COPY_MEMORY(s->maindata + bytes_have, bs->buf + bs->pos/8, frame_bytes);
  77298. ma_dr_mp3_bs_init(&s->bs, s->maindata, bytes_have + frame_bytes);
  77299. return h->reserv >= main_data_begin;
  77300. }
  77301. static void ma_dr_mp3_L3_decode(ma_dr_mp3dec *h, ma_dr_mp3dec_scratch *s, ma_dr_mp3_L3_gr_info *gr_info, int nch)
  77302. {
  77303. int ch;
  77304. for (ch = 0; ch < nch; ch++)
  77305. {
  77306. int layer3gr_limit = s->bs.pos + gr_info[ch].part_23_length;
  77307. ma_dr_mp3_L3_decode_scalefactors(h->header, s->ist_pos[ch], &s->bs, gr_info + ch, s->scf, ch);
  77308. ma_dr_mp3_L3_huffman(s->grbuf[ch], &s->bs, gr_info + ch, s->scf, layer3gr_limit);
  77309. }
  77310. if (MA_DR_MP3_HDR_TEST_I_STEREO(h->header))
  77311. {
  77312. ma_dr_mp3_L3_intensity_stereo(s->grbuf[0], s->ist_pos[1], gr_info, h->header);
  77313. } else if (MA_DR_MP3_HDR_IS_MS_STEREO(h->header))
  77314. {
  77315. ma_dr_mp3_L3_midside_stereo(s->grbuf[0], 576);
  77316. }
  77317. for (ch = 0; ch < nch; ch++, gr_info++)
  77318. {
  77319. int aa_bands = 31;
  77320. int n_long_bands = (gr_info->mixed_block_flag ? 2 : 0) << (int)(MA_DR_MP3_HDR_GET_MY_SAMPLE_RATE(h->header) == 2);
  77321. if (gr_info->n_short_sfb)
  77322. {
  77323. aa_bands = n_long_bands - 1;
  77324. ma_dr_mp3_L3_reorder(s->grbuf[ch] + n_long_bands*18, s->syn[0], gr_info->sfbtab + gr_info->n_long_sfb);
  77325. }
  77326. ma_dr_mp3_L3_antialias(s->grbuf[ch], aa_bands);
  77327. ma_dr_mp3_L3_imdct_gr(s->grbuf[ch], h->mdct_overlap[ch], gr_info->block_type, n_long_bands);
  77328. ma_dr_mp3_L3_change_sign(s->grbuf[ch]);
  77329. }
  77330. }
  77331. static void ma_dr_mp3d_DCT_II(float *grbuf, int n)
  77332. {
  77333. static const float g_sec[24] = {
  77334. 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
  77335. };
  77336. int i, k = 0;
  77337. #if MA_DR_MP3_HAVE_SIMD
  77338. if (ma_dr_mp3_have_simd()) for (; k < n; k += 4)
  77339. {
  77340. ma_dr_mp3_f4 t[4][8], *x;
  77341. float *y = grbuf + k;
  77342. for (x = t[0], i = 0; i < 8; i++, x++)
  77343. {
  77344. ma_dr_mp3_f4 x0 = MA_DR_MP3_VLD(&y[i*18]);
  77345. ma_dr_mp3_f4 x1 = MA_DR_MP3_VLD(&y[(15 - i)*18]);
  77346. ma_dr_mp3_f4 x2 = MA_DR_MP3_VLD(&y[(16 + i)*18]);
  77347. ma_dr_mp3_f4 x3 = MA_DR_MP3_VLD(&y[(31 - i)*18]);
  77348. ma_dr_mp3_f4 t0 = MA_DR_MP3_VADD(x0, x3);
  77349. ma_dr_mp3_f4 t1 = MA_DR_MP3_VADD(x1, x2);
  77350. ma_dr_mp3_f4 t2 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x1, x2), g_sec[3*i + 0]);
  77351. ma_dr_mp3_f4 t3 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x0, x3), g_sec[3*i + 1]);
  77352. x[0] = MA_DR_MP3_VADD(t0, t1);
  77353. x[8] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(t0, t1), g_sec[3*i + 2]);
  77354. x[16] = MA_DR_MP3_VADD(t3, t2);
  77355. x[24] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(t3, t2), g_sec[3*i + 2]);
  77356. }
  77357. for (x = t[0], i = 0; i < 4; i++, x += 8)
  77358. {
  77359. ma_dr_mp3_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;
  77360. xt = MA_DR_MP3_VSUB(x0, x7); x0 = MA_DR_MP3_VADD(x0, x7);
  77361. x7 = MA_DR_MP3_VSUB(x1, x6); x1 = MA_DR_MP3_VADD(x1, x6);
  77362. x6 = MA_DR_MP3_VSUB(x2, x5); x2 = MA_DR_MP3_VADD(x2, x5);
  77363. x5 = MA_DR_MP3_VSUB(x3, x4); x3 = MA_DR_MP3_VADD(x3, x4);
  77364. x4 = MA_DR_MP3_VSUB(x0, x3); x0 = MA_DR_MP3_VADD(x0, x3);
  77365. x3 = MA_DR_MP3_VSUB(x1, x2); x1 = MA_DR_MP3_VADD(x1, x2);
  77366. x[0] = MA_DR_MP3_VADD(x0, x1);
  77367. x[4] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x0, x1), 0.70710677f);
  77368. x5 = MA_DR_MP3_VADD(x5, x6);
  77369. x6 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x6, x7), 0.70710677f);
  77370. x7 = MA_DR_MP3_VADD(x7, xt);
  77371. x3 = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x3, x4), 0.70710677f);
  77372. x5 = MA_DR_MP3_VSUB(x5, MA_DR_MP3_VMUL_S(x7, 0.198912367f));
  77373. x7 = MA_DR_MP3_VADD(x7, MA_DR_MP3_VMUL_S(x5, 0.382683432f));
  77374. x5 = MA_DR_MP3_VSUB(x5, MA_DR_MP3_VMUL_S(x7, 0.198912367f));
  77375. x0 = MA_DR_MP3_VSUB(xt, x6); xt = MA_DR_MP3_VADD(xt, x6);
  77376. x[1] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(xt, x7), 0.50979561f);
  77377. x[2] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x4, x3), 0.54119611f);
  77378. x[3] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x0, x5), 0.60134488f);
  77379. x[5] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VADD(x0, x5), 0.89997619f);
  77380. x[6] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(x4, x3), 1.30656302f);
  77381. x[7] = MA_DR_MP3_VMUL_S(MA_DR_MP3_VSUB(xt, x7), 2.56291556f);
  77382. }
  77383. if (k > n - 3)
  77384. {
  77385. #if MA_DR_MP3_HAVE_SSE
  77386. #define MA_DR_MP3_VSAVE2(i, v) _mm_storel_pi((__m64 *)(void*)&y[i*18], v)
  77387. #else
  77388. #define MA_DR_MP3_VSAVE2(i, v) vst1_f32((float32_t *)&y[(i)*18], vget_low_f32(v))
  77389. #endif
  77390. for (i = 0; i < 7; i++, y += 4*18)
  77391. {
  77392. ma_dr_mp3_f4 s = MA_DR_MP3_VADD(t[3][i], t[3][i + 1]);
  77393. MA_DR_MP3_VSAVE2(0, t[0][i]);
  77394. MA_DR_MP3_VSAVE2(1, MA_DR_MP3_VADD(t[2][i], s));
  77395. MA_DR_MP3_VSAVE2(2, MA_DR_MP3_VADD(t[1][i], t[1][i + 1]));
  77396. MA_DR_MP3_VSAVE2(3, MA_DR_MP3_VADD(t[2][1 + i], s));
  77397. }
  77398. MA_DR_MP3_VSAVE2(0, t[0][7]);
  77399. MA_DR_MP3_VSAVE2(1, MA_DR_MP3_VADD(t[2][7], t[3][7]));
  77400. MA_DR_MP3_VSAVE2(2, t[1][7]);
  77401. MA_DR_MP3_VSAVE2(3, t[3][7]);
  77402. } else
  77403. {
  77404. #define MA_DR_MP3_VSAVE4(i, v) MA_DR_MP3_VSTORE(&y[(i)*18], v)
  77405. for (i = 0; i < 7; i++, y += 4*18)
  77406. {
  77407. ma_dr_mp3_f4 s = MA_DR_MP3_VADD(t[3][i], t[3][i + 1]);
  77408. MA_DR_MP3_VSAVE4(0, t[0][i]);
  77409. MA_DR_MP3_VSAVE4(1, MA_DR_MP3_VADD(t[2][i], s));
  77410. MA_DR_MP3_VSAVE4(2, MA_DR_MP3_VADD(t[1][i], t[1][i + 1]));
  77411. MA_DR_MP3_VSAVE4(3, MA_DR_MP3_VADD(t[2][1 + i], s));
  77412. }
  77413. MA_DR_MP3_VSAVE4(0, t[0][7]);
  77414. MA_DR_MP3_VSAVE4(1, MA_DR_MP3_VADD(t[2][7], t[3][7]));
  77415. MA_DR_MP3_VSAVE4(2, t[1][7]);
  77416. MA_DR_MP3_VSAVE4(3, t[3][7]);
  77417. }
  77418. } else
  77419. #endif
  77420. #ifdef MA_DR_MP3_ONLY_SIMD
  77421. {}
  77422. #else
  77423. for (; k < n; k++)
  77424. {
  77425. float t[4][8], *x, *y = grbuf + k;
  77426. for (x = t[0], i = 0; i < 8; i++, x++)
  77427. {
  77428. float x0 = y[i*18];
  77429. float x1 = y[(15 - i)*18];
  77430. float x2 = y[(16 + i)*18];
  77431. float x3 = y[(31 - i)*18];
  77432. float t0 = x0 + x3;
  77433. float t1 = x1 + x2;
  77434. float t2 = (x1 - x2)*g_sec[3*i + 0];
  77435. float t3 = (x0 - x3)*g_sec[3*i + 1];
  77436. x[0] = t0 + t1;
  77437. x[8] = (t0 - t1)*g_sec[3*i + 2];
  77438. x[16] = t3 + t2;
  77439. x[24] = (t3 - t2)*g_sec[3*i + 2];
  77440. }
  77441. for (x = t[0], i = 0; i < 4; i++, x += 8)
  77442. {
  77443. 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;
  77444. xt = x0 - x7; x0 += x7;
  77445. x7 = x1 - x6; x1 += x6;
  77446. x6 = x2 - x5; x2 += x5;
  77447. x5 = x3 - x4; x3 += x4;
  77448. x4 = x0 - x3; x0 += x3;
  77449. x3 = x1 - x2; x1 += x2;
  77450. x[0] = x0 + x1;
  77451. x[4] = (x0 - x1)*0.70710677f;
  77452. x5 = x5 + x6;
  77453. x6 = (x6 + x7)*0.70710677f;
  77454. x7 = x7 + xt;
  77455. x3 = (x3 + x4)*0.70710677f;
  77456. x5 -= x7*0.198912367f;
  77457. x7 += x5*0.382683432f;
  77458. x5 -= x7*0.198912367f;
  77459. x0 = xt - x6; xt += x6;
  77460. x[1] = (xt + x7)*0.50979561f;
  77461. x[2] = (x4 + x3)*0.54119611f;
  77462. x[3] = (x0 - x5)*0.60134488f;
  77463. x[5] = (x0 + x5)*0.89997619f;
  77464. x[6] = (x4 - x3)*1.30656302f;
  77465. x[7] = (xt - x7)*2.56291556f;
  77466. }
  77467. for (i = 0; i < 7; i++, y += 4*18)
  77468. {
  77469. y[0*18] = t[0][i];
  77470. y[1*18] = t[2][i] + t[3][i] + t[3][i + 1];
  77471. y[2*18] = t[1][i] + t[1][i + 1];
  77472. y[3*18] = t[2][i + 1] + t[3][i] + t[3][i + 1];
  77473. }
  77474. y[0*18] = t[0][7];
  77475. y[1*18] = t[2][7] + t[3][7];
  77476. y[2*18] = t[1][7];
  77477. y[3*18] = t[3][7];
  77478. }
  77479. #endif
  77480. }
  77481. #ifndef MA_DR_MP3_FLOAT_OUTPUT
  77482. typedef ma_int16 ma_dr_mp3d_sample_t;
  77483. static ma_int16 ma_dr_mp3d_scale_pcm(float sample)
  77484. {
  77485. ma_int16 s;
  77486. #if MA_DR_MP3_HAVE_ARMV6
  77487. ma_int32 s32 = (ma_int32)(sample + .5f);
  77488. s32 -= (s32 < 0);
  77489. s = (ma_int16)ma_dr_mp3_clip_int16_arm(s32);
  77490. #else
  77491. if (sample >= 32766.5) return (ma_int16) 32767;
  77492. if (sample <= -32767.5) return (ma_int16)-32768;
  77493. s = (ma_int16)(sample + .5f);
  77494. s -= (s < 0);
  77495. #endif
  77496. return s;
  77497. }
  77498. #else
  77499. typedef float ma_dr_mp3d_sample_t;
  77500. static float ma_dr_mp3d_scale_pcm(float sample)
  77501. {
  77502. return sample*(1.f/32768.f);
  77503. }
  77504. #endif
  77505. static void ma_dr_mp3d_synth_pair(ma_dr_mp3d_sample_t *pcm, int nch, const float *z)
  77506. {
  77507. float a;
  77508. a = (z[14*64] - z[ 0]) * 29;
  77509. a += (z[ 1*64] + z[13*64]) * 213;
  77510. a += (z[12*64] - z[ 2*64]) * 459;
  77511. a += (z[ 3*64] + z[11*64]) * 2037;
  77512. a += (z[10*64] - z[ 4*64]) * 5153;
  77513. a += (z[ 5*64] + z[ 9*64]) * 6574;
  77514. a += (z[ 8*64] - z[ 6*64]) * 37489;
  77515. a += z[ 7*64] * 75038;
  77516. pcm[0] = ma_dr_mp3d_scale_pcm(a);
  77517. z += 2;
  77518. a = z[14*64] * 104;
  77519. a += z[12*64] * 1567;
  77520. a += z[10*64] * 9727;
  77521. a += z[ 8*64] * 64019;
  77522. a += z[ 6*64] * -9975;
  77523. a += z[ 4*64] * -45;
  77524. a += z[ 2*64] * 146;
  77525. a += z[ 0*64] * -5;
  77526. pcm[16*nch] = ma_dr_mp3d_scale_pcm(a);
  77527. }
  77528. static void ma_dr_mp3d_synth(float *xl, ma_dr_mp3d_sample_t *dstl, int nch, float *lins)
  77529. {
  77530. int i;
  77531. float *xr = xl + 576*(nch - 1);
  77532. ma_dr_mp3d_sample_t *dstr = dstl + (nch - 1);
  77533. static const float g_win[] = {
  77534. -1,26,-31,208,218,401,-519,2063,2000,4788,-5517,7134,5959,35640,-39336,74992,
  77535. -1,24,-35,202,222,347,-581,2080,1952,4425,-5879,7640,5288,33791,-41176,74856,
  77536. -1,21,-38,196,225,294,-645,2087,1893,4063,-6237,8092,4561,31947,-43006,74630,
  77537. -1,19,-41,190,227,244,-711,2085,1822,3705,-6589,8492,3776,30112,-44821,74313,
  77538. -1,17,-45,183,228,197,-779,2075,1739,3351,-6935,8840,2935,28289,-46617,73908,
  77539. -1,16,-49,176,228,153,-848,2057,1644,3004,-7271,9139,2037,26482,-48390,73415,
  77540. -2,14,-53,169,227,111,-919,2032,1535,2663,-7597,9389,1082,24694,-50137,72835,
  77541. -2,13,-58,161,224,72,-991,2001,1414,2330,-7910,9592,70,22929,-51853,72169,
  77542. -2,11,-63,154,221,36,-1064,1962,1280,2006,-8209,9750,-998,21189,-53534,71420,
  77543. -2,10,-68,147,215,2,-1137,1919,1131,1692,-8491,9863,-2122,19478,-55178,70590,
  77544. -3,9,-73,139,208,-29,-1210,1870,970,1388,-8755,9935,-3300,17799,-56778,69679,
  77545. -3,8,-79,132,200,-57,-1283,1817,794,1095,-8998,9966,-4533,16155,-58333,68692,
  77546. -4,7,-85,125,189,-83,-1356,1759,605,814,-9219,9959,-5818,14548,-59838,67629,
  77547. -4,7,-91,117,177,-106,-1428,1698,402,545,-9416,9916,-7154,12980,-61289,66494,
  77548. -5,6,-97,111,163,-127,-1498,1634,185,288,-9585,9838,-8540,11455,-62684,65290
  77549. };
  77550. float *zlin = lins + 15*64;
  77551. const float *w = g_win;
  77552. zlin[4*15] = xl[18*16];
  77553. zlin[4*15 + 1] = xr[18*16];
  77554. zlin[4*15 + 2] = xl[0];
  77555. zlin[4*15 + 3] = xr[0];
  77556. zlin[4*31] = xl[1 + 18*16];
  77557. zlin[4*31 + 1] = xr[1 + 18*16];
  77558. zlin[4*31 + 2] = xl[1];
  77559. zlin[4*31 + 3] = xr[1];
  77560. ma_dr_mp3d_synth_pair(dstr, nch, lins + 4*15 + 1);
  77561. ma_dr_mp3d_synth_pair(dstr + 32*nch, nch, lins + 4*15 + 64 + 1);
  77562. ma_dr_mp3d_synth_pair(dstl, nch, lins + 4*15);
  77563. ma_dr_mp3d_synth_pair(dstl + 32*nch, nch, lins + 4*15 + 64);
  77564. #if MA_DR_MP3_HAVE_SIMD
  77565. if (ma_dr_mp3_have_simd()) for (i = 14; i >= 0; i--)
  77566. {
  77567. #define MA_DR_MP3_VLOAD(k) ma_dr_mp3_f4 w0 = MA_DR_MP3_VSET(*w++); ma_dr_mp3_f4 w1 = MA_DR_MP3_VSET(*w++); ma_dr_mp3_f4 vz = MA_DR_MP3_VLD(&zlin[4*i - 64*k]); ma_dr_mp3_f4 vy = MA_DR_MP3_VLD(&zlin[4*i - 64*(15 - k)]);
  77568. #define MA_DR_MP3_V0(k) { MA_DR_MP3_VLOAD(k) b = MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vz, w1), MA_DR_MP3_VMUL(vy, w0)) ; a = MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vz, w0), MA_DR_MP3_VMUL(vy, w1)); }
  77569. #define MA_DR_MP3_V1(k) { MA_DR_MP3_VLOAD(k) b = MA_DR_MP3_VADD(b, MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vz, w1), MA_DR_MP3_VMUL(vy, w0))); a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vz, w0), MA_DR_MP3_VMUL(vy, w1))); }
  77570. #define MA_DR_MP3_V2(k) { MA_DR_MP3_VLOAD(k) b = MA_DR_MP3_VADD(b, MA_DR_MP3_VADD(MA_DR_MP3_VMUL(vz, w1), MA_DR_MP3_VMUL(vy, w0))); a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSUB(MA_DR_MP3_VMUL(vy, w1), MA_DR_MP3_VMUL(vz, w0))); }
  77571. ma_dr_mp3_f4 a, b;
  77572. zlin[4*i] = xl[18*(31 - i)];
  77573. zlin[4*i + 1] = xr[18*(31 - i)];
  77574. zlin[4*i + 2] = xl[1 + 18*(31 - i)];
  77575. zlin[4*i + 3] = xr[1 + 18*(31 - i)];
  77576. zlin[4*i + 64] = xl[1 + 18*(1 + i)];
  77577. zlin[4*i + 64 + 1] = xr[1 + 18*(1 + i)];
  77578. zlin[4*i - 64 + 2] = xl[18*(1 + i)];
  77579. zlin[4*i - 64 + 3] = xr[18*(1 + i)];
  77580. MA_DR_MP3_V0(0) MA_DR_MP3_V2(1) MA_DR_MP3_V1(2) MA_DR_MP3_V2(3) MA_DR_MP3_V1(4) MA_DR_MP3_V2(5) MA_DR_MP3_V1(6) MA_DR_MP3_V2(7)
  77581. {
  77582. #ifndef MA_DR_MP3_FLOAT_OUTPUT
  77583. #if MA_DR_MP3_HAVE_SSE
  77584. static const ma_dr_mp3_f4 g_max = { 32767.0f, 32767.0f, 32767.0f, 32767.0f };
  77585. static const ma_dr_mp3_f4 g_min = { -32768.0f, -32768.0f, -32768.0f, -32768.0f };
  77586. __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, g_max), g_min)),
  77587. _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, g_max), g_min)));
  77588. dstr[(15 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 1);
  77589. dstr[(17 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 5);
  77590. dstl[(15 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 0);
  77591. dstl[(17 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 4);
  77592. dstr[(47 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 3);
  77593. dstr[(49 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 7);
  77594. dstl[(47 - i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 2);
  77595. dstl[(49 + i)*nch] = (ma_int16)_mm_extract_epi16(pcm8, 6);
  77596. #else
  77597. int16x4_t pcma, pcmb;
  77598. a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSET(0.5f));
  77599. b = MA_DR_MP3_VADD(b, MA_DR_MP3_VSET(0.5f));
  77600. pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, MA_DR_MP3_VSET(0)))));
  77601. pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, MA_DR_MP3_VSET(0)))));
  77602. vst1_lane_s16(dstr + (15 - i)*nch, pcma, 1);
  77603. vst1_lane_s16(dstr + (17 + i)*nch, pcmb, 1);
  77604. vst1_lane_s16(dstl + (15 - i)*nch, pcma, 0);
  77605. vst1_lane_s16(dstl + (17 + i)*nch, pcmb, 0);
  77606. vst1_lane_s16(dstr + (47 - i)*nch, pcma, 3);
  77607. vst1_lane_s16(dstr + (49 + i)*nch, pcmb, 3);
  77608. vst1_lane_s16(dstl + (47 - i)*nch, pcma, 2);
  77609. vst1_lane_s16(dstl + (49 + i)*nch, pcmb, 2);
  77610. #endif
  77611. #else
  77612. #if MA_DR_MP3_HAVE_SSE
  77613. static const ma_dr_mp3_f4 g_scale = { 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f };
  77614. #else
  77615. const ma_dr_mp3_f4 g_scale = vdupq_n_f32(1.0f/32768.0f);
  77616. #endif
  77617. a = MA_DR_MP3_VMUL(a, g_scale);
  77618. b = MA_DR_MP3_VMUL(b, g_scale);
  77619. #if MA_DR_MP3_HAVE_SSE
  77620. _mm_store_ss(dstr + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)));
  77621. _mm_store_ss(dstr + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(1, 1, 1, 1)));
  77622. _mm_store_ss(dstl + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)));
  77623. _mm_store_ss(dstl + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(0, 0, 0, 0)));
  77624. _mm_store_ss(dstr + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 3, 3, 3)));
  77625. _mm_store_ss(dstr + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 3, 3, 3)));
  77626. _mm_store_ss(dstl + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)));
  77627. _mm_store_ss(dstl + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(2, 2, 2, 2)));
  77628. #else
  77629. vst1q_lane_f32(dstr + (15 - i)*nch, a, 1);
  77630. vst1q_lane_f32(dstr + (17 + i)*nch, b, 1);
  77631. vst1q_lane_f32(dstl + (15 - i)*nch, a, 0);
  77632. vst1q_lane_f32(dstl + (17 + i)*nch, b, 0);
  77633. vst1q_lane_f32(dstr + (47 - i)*nch, a, 3);
  77634. vst1q_lane_f32(dstr + (49 + i)*nch, b, 3);
  77635. vst1q_lane_f32(dstl + (47 - i)*nch, a, 2);
  77636. vst1q_lane_f32(dstl + (49 + i)*nch, b, 2);
  77637. #endif
  77638. #endif
  77639. }
  77640. } else
  77641. #endif
  77642. #ifdef MA_DR_MP3_ONLY_SIMD
  77643. {}
  77644. #else
  77645. for (i = 14; i >= 0; i--)
  77646. {
  77647. #define MA_DR_MP3_LOAD(k) float w0 = *w++; float w1 = *w++; float *vz = &zlin[4*i - k*64]; float *vy = &zlin[4*i - (15 - k)*64];
  77648. #define MA_DR_MP3_S0(k) { int j; MA_DR_MP3_LOAD(k); for (j = 0; j < 4; j++) b[j] = vz[j]*w1 + vy[j]*w0, a[j] = vz[j]*w0 - vy[j]*w1; }
  77649. #define MA_DR_MP3_S1(k) { int j; MA_DR_MP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vz[j]*w0 - vy[j]*w1; }
  77650. #define MA_DR_MP3_S2(k) { int j; MA_DR_MP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vy[j]*w1 - vz[j]*w0; }
  77651. float a[4], b[4];
  77652. zlin[4*i] = xl[18*(31 - i)];
  77653. zlin[4*i + 1] = xr[18*(31 - i)];
  77654. zlin[4*i + 2] = xl[1 + 18*(31 - i)];
  77655. zlin[4*i + 3] = xr[1 + 18*(31 - i)];
  77656. zlin[4*(i + 16)] = xl[1 + 18*(1 + i)];
  77657. zlin[4*(i + 16) + 1] = xr[1 + 18*(1 + i)];
  77658. zlin[4*(i - 16) + 2] = xl[18*(1 + i)];
  77659. zlin[4*(i - 16) + 3] = xr[18*(1 + i)];
  77660. MA_DR_MP3_S0(0) MA_DR_MP3_S2(1) MA_DR_MP3_S1(2) MA_DR_MP3_S2(3) MA_DR_MP3_S1(4) MA_DR_MP3_S2(5) MA_DR_MP3_S1(6) MA_DR_MP3_S2(7)
  77661. dstr[(15 - i)*nch] = ma_dr_mp3d_scale_pcm(a[1]);
  77662. dstr[(17 + i)*nch] = ma_dr_mp3d_scale_pcm(b[1]);
  77663. dstl[(15 - i)*nch] = ma_dr_mp3d_scale_pcm(a[0]);
  77664. dstl[(17 + i)*nch] = ma_dr_mp3d_scale_pcm(b[0]);
  77665. dstr[(47 - i)*nch] = ma_dr_mp3d_scale_pcm(a[3]);
  77666. dstr[(49 + i)*nch] = ma_dr_mp3d_scale_pcm(b[3]);
  77667. dstl[(47 - i)*nch] = ma_dr_mp3d_scale_pcm(a[2]);
  77668. dstl[(49 + i)*nch] = ma_dr_mp3d_scale_pcm(b[2]);
  77669. }
  77670. #endif
  77671. }
  77672. static void ma_dr_mp3d_synth_granule(float *qmf_state, float *grbuf, int nbands, int nch, ma_dr_mp3d_sample_t *pcm, float *lins)
  77673. {
  77674. int i;
  77675. for (i = 0; i < nch; i++)
  77676. {
  77677. ma_dr_mp3d_DCT_II(grbuf + 576*i, nbands);
  77678. }
  77679. MA_DR_MP3_COPY_MEMORY(lins, qmf_state, sizeof(float)*15*64);
  77680. for (i = 0; i < nbands; i += 2)
  77681. {
  77682. ma_dr_mp3d_synth(grbuf + i, pcm + 32*nch*i, nch, lins + i*64);
  77683. }
  77684. #ifndef MA_DR_MP3_NONSTANDARD_BUT_LOGICAL
  77685. if (nch == 1)
  77686. {
  77687. for (i = 0; i < 15*64; i += 2)
  77688. {
  77689. qmf_state[i] = lins[nbands*64 + i];
  77690. }
  77691. } else
  77692. #endif
  77693. {
  77694. MA_DR_MP3_COPY_MEMORY(qmf_state, lins + nbands*64, sizeof(float)*15*64);
  77695. }
  77696. }
  77697. static int ma_dr_mp3d_match_frame(const ma_uint8 *hdr, int mp3_bytes, int frame_bytes)
  77698. {
  77699. int i, nmatch;
  77700. for (i = 0, nmatch = 0; nmatch < MA_DR_MP3_MAX_FRAME_SYNC_MATCHES; nmatch++)
  77701. {
  77702. i += ma_dr_mp3_hdr_frame_bytes(hdr + i, frame_bytes) + ma_dr_mp3_hdr_padding(hdr + i);
  77703. if (i + MA_DR_MP3_HDR_SIZE > mp3_bytes)
  77704. return nmatch > 0;
  77705. if (!ma_dr_mp3_hdr_compare(hdr, hdr + i))
  77706. return 0;
  77707. }
  77708. return 1;
  77709. }
  77710. static int ma_dr_mp3d_find_frame(const ma_uint8 *mp3, int mp3_bytes, int *free_format_bytes, int *ptr_frame_bytes)
  77711. {
  77712. int i, k;
  77713. for (i = 0; i < mp3_bytes - MA_DR_MP3_HDR_SIZE; i++, mp3++)
  77714. {
  77715. if (ma_dr_mp3_hdr_valid(mp3))
  77716. {
  77717. int frame_bytes = ma_dr_mp3_hdr_frame_bytes(mp3, *free_format_bytes);
  77718. int frame_and_padding = frame_bytes + ma_dr_mp3_hdr_padding(mp3);
  77719. for (k = MA_DR_MP3_HDR_SIZE; !frame_bytes && k < MA_DR_MP3_MAX_FREE_FORMAT_FRAME_SIZE && i + 2*k < mp3_bytes - MA_DR_MP3_HDR_SIZE; k++)
  77720. {
  77721. if (ma_dr_mp3_hdr_compare(mp3, mp3 + k))
  77722. {
  77723. int fb = k - ma_dr_mp3_hdr_padding(mp3);
  77724. int nextfb = fb + ma_dr_mp3_hdr_padding(mp3 + k);
  77725. if (i + k + nextfb + MA_DR_MP3_HDR_SIZE > mp3_bytes || !ma_dr_mp3_hdr_compare(mp3, mp3 + k + nextfb))
  77726. continue;
  77727. frame_and_padding = k;
  77728. frame_bytes = fb;
  77729. *free_format_bytes = fb;
  77730. }
  77731. }
  77732. if ((frame_bytes && i + frame_and_padding <= mp3_bytes &&
  77733. ma_dr_mp3d_match_frame(mp3, mp3_bytes - i, frame_bytes)) ||
  77734. (!i && frame_and_padding == mp3_bytes))
  77735. {
  77736. *ptr_frame_bytes = frame_and_padding;
  77737. return i;
  77738. }
  77739. *free_format_bytes = 0;
  77740. }
  77741. }
  77742. *ptr_frame_bytes = 0;
  77743. return mp3_bytes;
  77744. }
  77745. MA_API void ma_dr_mp3dec_init(ma_dr_mp3dec *dec)
  77746. {
  77747. dec->header[0] = 0;
  77748. }
  77749. MA_API int ma_dr_mp3dec_decode_frame(ma_dr_mp3dec *dec, const ma_uint8 *mp3, int mp3_bytes, void *pcm, ma_dr_mp3dec_frame_info *info)
  77750. {
  77751. int i = 0, igr, frame_size = 0, success = 1;
  77752. const ma_uint8 *hdr;
  77753. ma_dr_mp3_bs bs_frame[1];
  77754. ma_dr_mp3dec_scratch scratch;
  77755. if (mp3_bytes > 4 && dec->header[0] == 0xff && ma_dr_mp3_hdr_compare(dec->header, mp3))
  77756. {
  77757. frame_size = ma_dr_mp3_hdr_frame_bytes(mp3, dec->free_format_bytes) + ma_dr_mp3_hdr_padding(mp3);
  77758. if (frame_size != mp3_bytes && (frame_size + MA_DR_MP3_HDR_SIZE > mp3_bytes || !ma_dr_mp3_hdr_compare(mp3, mp3 + frame_size)))
  77759. {
  77760. frame_size = 0;
  77761. }
  77762. }
  77763. if (!frame_size)
  77764. {
  77765. MA_DR_MP3_ZERO_MEMORY(dec, sizeof(ma_dr_mp3dec));
  77766. i = ma_dr_mp3d_find_frame(mp3, mp3_bytes, &dec->free_format_bytes, &frame_size);
  77767. if (!frame_size || i + frame_size > mp3_bytes)
  77768. {
  77769. info->frame_bytes = i;
  77770. return 0;
  77771. }
  77772. }
  77773. hdr = mp3 + i;
  77774. MA_DR_MP3_COPY_MEMORY(dec->header, hdr, MA_DR_MP3_HDR_SIZE);
  77775. info->frame_bytes = i + frame_size;
  77776. info->channels = MA_DR_MP3_HDR_IS_MONO(hdr) ? 1 : 2;
  77777. info->hz = ma_dr_mp3_hdr_sample_rate_hz(hdr);
  77778. info->layer = 4 - MA_DR_MP3_HDR_GET_LAYER(hdr);
  77779. info->bitrate_kbps = ma_dr_mp3_hdr_bitrate_kbps(hdr);
  77780. ma_dr_mp3_bs_init(bs_frame, hdr + MA_DR_MP3_HDR_SIZE, frame_size - MA_DR_MP3_HDR_SIZE);
  77781. if (MA_DR_MP3_HDR_IS_CRC(hdr))
  77782. {
  77783. ma_dr_mp3_bs_get_bits(bs_frame, 16);
  77784. }
  77785. if (info->layer == 3)
  77786. {
  77787. int main_data_begin = ma_dr_mp3_L3_read_side_info(bs_frame, scratch.gr_info, hdr);
  77788. if (main_data_begin < 0 || bs_frame->pos > bs_frame->limit)
  77789. {
  77790. ma_dr_mp3dec_init(dec);
  77791. return 0;
  77792. }
  77793. success = ma_dr_mp3_L3_restore_reservoir(dec, bs_frame, &scratch, main_data_begin);
  77794. if (success && pcm != NULL)
  77795. {
  77796. for (igr = 0; igr < (MA_DR_MP3_HDR_TEST_MPEG1(hdr) ? 2 : 1); igr++, pcm = MA_DR_MP3_OFFSET_PTR(pcm, sizeof(ma_dr_mp3d_sample_t)*576*info->channels))
  77797. {
  77798. MA_DR_MP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  77799. ma_dr_mp3_L3_decode(dec, &scratch, scratch.gr_info + igr*info->channels, info->channels);
  77800. ma_dr_mp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 18, info->channels, (ma_dr_mp3d_sample_t*)pcm, scratch.syn[0]);
  77801. }
  77802. }
  77803. ma_dr_mp3_L3_save_reservoir(dec, &scratch);
  77804. } else
  77805. {
  77806. #ifdef MA_DR_MP3_ONLY_MP3
  77807. return 0;
  77808. #else
  77809. ma_dr_mp3_L12_scale_info sci[1];
  77810. if (pcm == NULL) {
  77811. return ma_dr_mp3_hdr_frame_samples(hdr);
  77812. }
  77813. ma_dr_mp3_L12_read_scale_info(hdr, bs_frame, sci);
  77814. MA_DR_MP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  77815. for (i = 0, igr = 0; igr < 3; igr++)
  77816. {
  77817. if (12 == (i += ma_dr_mp3_L12_dequantize_granule(scratch.grbuf[0] + i, bs_frame, sci, info->layer | 1)))
  77818. {
  77819. i = 0;
  77820. ma_dr_mp3_L12_apply_scf_384(sci, sci->scf + igr, scratch.grbuf[0]);
  77821. ma_dr_mp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 12, info->channels, (ma_dr_mp3d_sample_t*)pcm, scratch.syn[0]);
  77822. MA_DR_MP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  77823. pcm = MA_DR_MP3_OFFSET_PTR(pcm, sizeof(ma_dr_mp3d_sample_t)*384*info->channels);
  77824. }
  77825. if (bs_frame->pos > bs_frame->limit)
  77826. {
  77827. ma_dr_mp3dec_init(dec);
  77828. return 0;
  77829. }
  77830. }
  77831. #endif
  77832. }
  77833. return success*ma_dr_mp3_hdr_frame_samples(dec->header);
  77834. }
  77835. MA_API void ma_dr_mp3dec_f32_to_s16(const float *in, ma_int16 *out, size_t num_samples)
  77836. {
  77837. size_t i = 0;
  77838. #if MA_DR_MP3_HAVE_SIMD
  77839. size_t aligned_count = num_samples & ~7;
  77840. for(; i < aligned_count; i+=8)
  77841. {
  77842. ma_dr_mp3_f4 scale = MA_DR_MP3_VSET(32768.0f);
  77843. ma_dr_mp3_f4 a = MA_DR_MP3_VMUL(MA_DR_MP3_VLD(&in[i ]), scale);
  77844. ma_dr_mp3_f4 b = MA_DR_MP3_VMUL(MA_DR_MP3_VLD(&in[i+4]), scale);
  77845. #if MA_DR_MP3_HAVE_SSE
  77846. ma_dr_mp3_f4 s16max = MA_DR_MP3_VSET( 32767.0f);
  77847. ma_dr_mp3_f4 s16min = MA_DR_MP3_VSET(-32768.0f);
  77848. __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, s16max), s16min)),
  77849. _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, s16max), s16min)));
  77850. out[i ] = (ma_int16)_mm_extract_epi16(pcm8, 0);
  77851. out[i+1] = (ma_int16)_mm_extract_epi16(pcm8, 1);
  77852. out[i+2] = (ma_int16)_mm_extract_epi16(pcm8, 2);
  77853. out[i+3] = (ma_int16)_mm_extract_epi16(pcm8, 3);
  77854. out[i+4] = (ma_int16)_mm_extract_epi16(pcm8, 4);
  77855. out[i+5] = (ma_int16)_mm_extract_epi16(pcm8, 5);
  77856. out[i+6] = (ma_int16)_mm_extract_epi16(pcm8, 6);
  77857. out[i+7] = (ma_int16)_mm_extract_epi16(pcm8, 7);
  77858. #else
  77859. int16x4_t pcma, pcmb;
  77860. a = MA_DR_MP3_VADD(a, MA_DR_MP3_VSET(0.5f));
  77861. b = MA_DR_MP3_VADD(b, MA_DR_MP3_VSET(0.5f));
  77862. pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, MA_DR_MP3_VSET(0)))));
  77863. pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, MA_DR_MP3_VSET(0)))));
  77864. vst1_lane_s16(out+i , pcma, 0);
  77865. vst1_lane_s16(out+i+1, pcma, 1);
  77866. vst1_lane_s16(out+i+2, pcma, 2);
  77867. vst1_lane_s16(out+i+3, pcma, 3);
  77868. vst1_lane_s16(out+i+4, pcmb, 0);
  77869. vst1_lane_s16(out+i+5, pcmb, 1);
  77870. vst1_lane_s16(out+i+6, pcmb, 2);
  77871. vst1_lane_s16(out+i+7, pcmb, 3);
  77872. #endif
  77873. }
  77874. #endif
  77875. for(; i < num_samples; i++)
  77876. {
  77877. float sample = in[i] * 32768.0f;
  77878. if (sample >= 32766.5)
  77879. out[i] = (ma_int16) 32767;
  77880. else if (sample <= -32767.5)
  77881. out[i] = (ma_int16)-32768;
  77882. else
  77883. {
  77884. short s = (ma_int16)(sample + .5f);
  77885. s -= (s < 0);
  77886. out[i] = s;
  77887. }
  77888. }
  77889. }
  77890. #ifndef MA_DR_MP3_SEEK_LEADING_MP3_FRAMES
  77891. #define MA_DR_MP3_SEEK_LEADING_MP3_FRAMES 2
  77892. #endif
  77893. #define MA_DR_MP3_MIN_DATA_CHUNK_SIZE 16384
  77894. #ifndef MA_DR_MP3_DATA_CHUNK_SIZE
  77895. #define MA_DR_MP3_DATA_CHUNK_SIZE (MA_DR_MP3_MIN_DATA_CHUNK_SIZE*4)
  77896. #endif
  77897. #define MA_DR_MP3_COUNTOF(x) (sizeof(x) / sizeof(x[0]))
  77898. #define MA_DR_MP3_CLAMP(x, lo, hi) (MA_DR_MP3_MAX(lo, MA_DR_MP3_MIN(x, hi)))
  77899. #ifndef MA_DR_MP3_PI_D
  77900. #define MA_DR_MP3_PI_D 3.14159265358979323846264
  77901. #endif
  77902. #define MA_DR_MP3_DEFAULT_RESAMPLER_LPF_ORDER 2
  77903. static MA_INLINE float ma_dr_mp3_mix_f32(float x, float y, float a)
  77904. {
  77905. return x*(1-a) + y*a;
  77906. }
  77907. static MA_INLINE float ma_dr_mp3_mix_f32_fast(float x, float y, float a)
  77908. {
  77909. float r0 = (y - x);
  77910. float r1 = r0*a;
  77911. return x + r1;
  77912. }
  77913. static MA_INLINE ma_uint32 ma_dr_mp3_gcf_u32(ma_uint32 a, ma_uint32 b)
  77914. {
  77915. for (;;) {
  77916. if (b == 0) {
  77917. break;
  77918. } else {
  77919. ma_uint32 t = a;
  77920. a = b;
  77921. b = t % a;
  77922. }
  77923. }
  77924. return a;
  77925. }
  77926. static void* ma_dr_mp3__malloc_default(size_t sz, void* pUserData)
  77927. {
  77928. (void)pUserData;
  77929. return MA_DR_MP3_MALLOC(sz);
  77930. }
  77931. static void* ma_dr_mp3__realloc_default(void* p, size_t sz, void* pUserData)
  77932. {
  77933. (void)pUserData;
  77934. return MA_DR_MP3_REALLOC(p, sz);
  77935. }
  77936. static void ma_dr_mp3__free_default(void* p, void* pUserData)
  77937. {
  77938. (void)pUserData;
  77939. MA_DR_MP3_FREE(p);
  77940. }
  77941. static void* ma_dr_mp3__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  77942. {
  77943. if (pAllocationCallbacks == NULL) {
  77944. return NULL;
  77945. }
  77946. if (pAllocationCallbacks->onMalloc != NULL) {
  77947. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  77948. }
  77949. if (pAllocationCallbacks->onRealloc != NULL) {
  77950. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  77951. }
  77952. return NULL;
  77953. }
  77954. static void* ma_dr_mp3__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks)
  77955. {
  77956. if (pAllocationCallbacks == NULL) {
  77957. return NULL;
  77958. }
  77959. if (pAllocationCallbacks->onRealloc != NULL) {
  77960. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  77961. }
  77962. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  77963. void* p2;
  77964. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  77965. if (p2 == NULL) {
  77966. return NULL;
  77967. }
  77968. if (p != NULL) {
  77969. MA_DR_MP3_COPY_MEMORY(p2, p, szOld);
  77970. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  77971. }
  77972. return p2;
  77973. }
  77974. return NULL;
  77975. }
  77976. static void ma_dr_mp3__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  77977. {
  77978. if (p == NULL || pAllocationCallbacks == NULL) {
  77979. return;
  77980. }
  77981. if (pAllocationCallbacks->onFree != NULL) {
  77982. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  77983. }
  77984. }
  77985. static ma_allocation_callbacks ma_dr_mp3_copy_allocation_callbacks_or_defaults(const ma_allocation_callbacks* pAllocationCallbacks)
  77986. {
  77987. if (pAllocationCallbacks != NULL) {
  77988. return *pAllocationCallbacks;
  77989. } else {
  77990. ma_allocation_callbacks allocationCallbacks;
  77991. allocationCallbacks.pUserData = NULL;
  77992. allocationCallbacks.onMalloc = ma_dr_mp3__malloc_default;
  77993. allocationCallbacks.onRealloc = ma_dr_mp3__realloc_default;
  77994. allocationCallbacks.onFree = ma_dr_mp3__free_default;
  77995. return allocationCallbacks;
  77996. }
  77997. }
  77998. static size_t ma_dr_mp3__on_read(ma_dr_mp3* pMP3, void* pBufferOut, size_t bytesToRead)
  77999. {
  78000. size_t bytesRead = pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead);
  78001. pMP3->streamCursor += bytesRead;
  78002. return bytesRead;
  78003. }
  78004. static ma_bool32 ma_dr_mp3__on_seek(ma_dr_mp3* pMP3, int offset, ma_dr_mp3_seek_origin origin)
  78005. {
  78006. MA_DR_MP3_ASSERT(offset >= 0);
  78007. if (!pMP3->onSeek(pMP3->pUserData, offset, origin)) {
  78008. return MA_FALSE;
  78009. }
  78010. if (origin == ma_dr_mp3_seek_origin_start) {
  78011. pMP3->streamCursor = (ma_uint64)offset;
  78012. } else {
  78013. pMP3->streamCursor += offset;
  78014. }
  78015. return MA_TRUE;
  78016. }
  78017. static ma_bool32 ma_dr_mp3__on_seek_64(ma_dr_mp3* pMP3, ma_uint64 offset, ma_dr_mp3_seek_origin origin)
  78018. {
  78019. if (offset <= 0x7FFFFFFF) {
  78020. return ma_dr_mp3__on_seek(pMP3, (int)offset, origin);
  78021. }
  78022. if (!ma_dr_mp3__on_seek(pMP3, 0x7FFFFFFF, ma_dr_mp3_seek_origin_start)) {
  78023. return MA_FALSE;
  78024. }
  78025. offset -= 0x7FFFFFFF;
  78026. while (offset > 0) {
  78027. if (offset <= 0x7FFFFFFF) {
  78028. if (!ma_dr_mp3__on_seek(pMP3, (int)offset, ma_dr_mp3_seek_origin_current)) {
  78029. return MA_FALSE;
  78030. }
  78031. offset = 0;
  78032. } else {
  78033. if (!ma_dr_mp3__on_seek(pMP3, 0x7FFFFFFF, ma_dr_mp3_seek_origin_current)) {
  78034. return MA_FALSE;
  78035. }
  78036. offset -= 0x7FFFFFFF;
  78037. }
  78038. }
  78039. return MA_TRUE;
  78040. }
  78041. static ma_uint32 ma_dr_mp3_decode_next_frame_ex__callbacks(ma_dr_mp3* pMP3, ma_dr_mp3d_sample_t* pPCMFrames)
  78042. {
  78043. ma_uint32 pcmFramesRead = 0;
  78044. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78045. MA_DR_MP3_ASSERT(pMP3->onRead != NULL);
  78046. if (pMP3->atEnd) {
  78047. return 0;
  78048. }
  78049. for (;;) {
  78050. ma_dr_mp3dec_frame_info info;
  78051. if (pMP3->dataSize < MA_DR_MP3_MIN_DATA_CHUNK_SIZE) {
  78052. size_t bytesRead;
  78053. if (pMP3->pData != NULL) {
  78054. MA_DR_MP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
  78055. }
  78056. pMP3->dataConsumed = 0;
  78057. if (pMP3->dataCapacity < MA_DR_MP3_DATA_CHUNK_SIZE) {
  78058. ma_uint8* pNewData;
  78059. size_t newDataCap;
  78060. newDataCap = MA_DR_MP3_DATA_CHUNK_SIZE;
  78061. pNewData = (ma_uint8*)ma_dr_mp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
  78062. if (pNewData == NULL) {
  78063. return 0;
  78064. }
  78065. pMP3->pData = pNewData;
  78066. pMP3->dataCapacity = newDataCap;
  78067. }
  78068. bytesRead = ma_dr_mp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
  78069. if (bytesRead == 0) {
  78070. if (pMP3->dataSize == 0) {
  78071. pMP3->atEnd = MA_TRUE;
  78072. return 0;
  78073. }
  78074. }
  78075. pMP3->dataSize += bytesRead;
  78076. }
  78077. if (pMP3->dataSize > INT_MAX) {
  78078. pMP3->atEnd = MA_TRUE;
  78079. return 0;
  78080. }
  78081. MA_DR_MP3_ASSERT(pMP3->pData != NULL);
  78082. MA_DR_MP3_ASSERT(pMP3->dataCapacity > 0);
  78083. if (pMP3->pData == NULL) {
  78084. return 0;
  78085. }
  78086. pcmFramesRead = ma_dr_mp3dec_decode_frame(&pMP3->decoder, pMP3->pData + pMP3->dataConsumed, (int)pMP3->dataSize, pPCMFrames, &info);
  78087. if (info.frame_bytes > 0) {
  78088. pMP3->dataConsumed += (size_t)info.frame_bytes;
  78089. pMP3->dataSize -= (size_t)info.frame_bytes;
  78090. }
  78091. if (pcmFramesRead > 0) {
  78092. pcmFramesRead = ma_dr_mp3_hdr_frame_samples(pMP3->decoder.header);
  78093. pMP3->pcmFramesConsumedInMP3Frame = 0;
  78094. pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
  78095. pMP3->mp3FrameChannels = info.channels;
  78096. pMP3->mp3FrameSampleRate = info.hz;
  78097. break;
  78098. } else if (info.frame_bytes == 0) {
  78099. size_t bytesRead;
  78100. MA_DR_MP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
  78101. pMP3->dataConsumed = 0;
  78102. if (pMP3->dataCapacity == pMP3->dataSize) {
  78103. ma_uint8* pNewData;
  78104. size_t newDataCap;
  78105. newDataCap = pMP3->dataCapacity + MA_DR_MP3_DATA_CHUNK_SIZE;
  78106. pNewData = (ma_uint8*)ma_dr_mp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
  78107. if (pNewData == NULL) {
  78108. return 0;
  78109. }
  78110. pMP3->pData = pNewData;
  78111. pMP3->dataCapacity = newDataCap;
  78112. }
  78113. bytesRead = ma_dr_mp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
  78114. if (bytesRead == 0) {
  78115. pMP3->atEnd = MA_TRUE;
  78116. return 0;
  78117. }
  78118. pMP3->dataSize += bytesRead;
  78119. }
  78120. };
  78121. return pcmFramesRead;
  78122. }
  78123. static ma_uint32 ma_dr_mp3_decode_next_frame_ex__memory(ma_dr_mp3* pMP3, ma_dr_mp3d_sample_t* pPCMFrames)
  78124. {
  78125. ma_uint32 pcmFramesRead = 0;
  78126. ma_dr_mp3dec_frame_info info;
  78127. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78128. MA_DR_MP3_ASSERT(pMP3->memory.pData != NULL);
  78129. if (pMP3->atEnd) {
  78130. return 0;
  78131. }
  78132. for (;;) {
  78133. pcmFramesRead = ma_dr_mp3dec_decode_frame(&pMP3->decoder, pMP3->memory.pData + pMP3->memory.currentReadPos, (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos), pPCMFrames, &info);
  78134. if (pcmFramesRead > 0) {
  78135. pcmFramesRead = ma_dr_mp3_hdr_frame_samples(pMP3->decoder.header);
  78136. pMP3->pcmFramesConsumedInMP3Frame = 0;
  78137. pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
  78138. pMP3->mp3FrameChannels = info.channels;
  78139. pMP3->mp3FrameSampleRate = info.hz;
  78140. break;
  78141. } else if (info.frame_bytes > 0) {
  78142. pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
  78143. } else {
  78144. break;
  78145. }
  78146. }
  78147. pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
  78148. return pcmFramesRead;
  78149. }
  78150. static ma_uint32 ma_dr_mp3_decode_next_frame_ex(ma_dr_mp3* pMP3, ma_dr_mp3d_sample_t* pPCMFrames)
  78151. {
  78152. if (pMP3->memory.pData != NULL && pMP3->memory.dataSize > 0) {
  78153. return ma_dr_mp3_decode_next_frame_ex__memory(pMP3, pPCMFrames);
  78154. } else {
  78155. return ma_dr_mp3_decode_next_frame_ex__callbacks(pMP3, pPCMFrames);
  78156. }
  78157. }
  78158. static ma_uint32 ma_dr_mp3_decode_next_frame(ma_dr_mp3* pMP3)
  78159. {
  78160. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78161. return ma_dr_mp3_decode_next_frame_ex(pMP3, (ma_dr_mp3d_sample_t*)pMP3->pcmFrames);
  78162. }
  78163. #if 0
  78164. static ma_uint32 ma_dr_mp3_seek_next_frame(ma_dr_mp3* pMP3)
  78165. {
  78166. ma_uint32 pcmFrameCount;
  78167. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78168. pcmFrameCount = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL);
  78169. if (pcmFrameCount == 0) {
  78170. return 0;
  78171. }
  78172. pMP3->currentPCMFrame += pcmFrameCount;
  78173. pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount;
  78174. pMP3->pcmFramesRemainingInMP3Frame = 0;
  78175. return pcmFrameCount;
  78176. }
  78177. #endif
  78178. static ma_bool32 ma_dr_mp3_init_internal(ma_dr_mp3* pMP3, ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  78179. {
  78180. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78181. MA_DR_MP3_ASSERT(onRead != NULL);
  78182. ma_dr_mp3dec_init(&pMP3->decoder);
  78183. pMP3->onRead = onRead;
  78184. pMP3->onSeek = onSeek;
  78185. pMP3->pUserData = pUserData;
  78186. pMP3->allocationCallbacks = ma_dr_mp3_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  78187. if (pMP3->allocationCallbacks.onFree == NULL || (pMP3->allocationCallbacks.onMalloc == NULL && pMP3->allocationCallbacks.onRealloc == NULL)) {
  78188. return MA_FALSE;
  78189. }
  78190. if (ma_dr_mp3_decode_next_frame(pMP3) == 0) {
  78191. ma_dr_mp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
  78192. return MA_FALSE;
  78193. }
  78194. pMP3->channels = pMP3->mp3FrameChannels;
  78195. pMP3->sampleRate = pMP3->mp3FrameSampleRate;
  78196. return MA_TRUE;
  78197. }
  78198. MA_API ma_bool32 ma_dr_mp3_init(ma_dr_mp3* pMP3, ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, const ma_allocation_callbacks* pAllocationCallbacks)
  78199. {
  78200. if (pMP3 == NULL || onRead == NULL) {
  78201. return MA_FALSE;
  78202. }
  78203. MA_DR_MP3_ZERO_OBJECT(pMP3);
  78204. return ma_dr_mp3_init_internal(pMP3, onRead, onSeek, pUserData, pAllocationCallbacks);
  78205. }
  78206. static size_t ma_dr_mp3__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  78207. {
  78208. ma_dr_mp3* pMP3 = (ma_dr_mp3*)pUserData;
  78209. size_t bytesRemaining;
  78210. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78211. MA_DR_MP3_ASSERT(pMP3->memory.dataSize >= pMP3->memory.currentReadPos);
  78212. bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos;
  78213. if (bytesToRead > bytesRemaining) {
  78214. bytesToRead = bytesRemaining;
  78215. }
  78216. if (bytesToRead > 0) {
  78217. MA_DR_MP3_COPY_MEMORY(pBufferOut, pMP3->memory.pData + pMP3->memory.currentReadPos, bytesToRead);
  78218. pMP3->memory.currentReadPos += bytesToRead;
  78219. }
  78220. return bytesToRead;
  78221. }
  78222. static ma_bool32 ma_dr_mp3__on_seek_memory(void* pUserData, int byteOffset, ma_dr_mp3_seek_origin origin)
  78223. {
  78224. ma_dr_mp3* pMP3 = (ma_dr_mp3*)pUserData;
  78225. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78226. if (origin == ma_dr_mp3_seek_origin_current) {
  78227. if (byteOffset > 0) {
  78228. if (pMP3->memory.currentReadPos + byteOffset > pMP3->memory.dataSize) {
  78229. byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos);
  78230. }
  78231. } else {
  78232. if (pMP3->memory.currentReadPos < (size_t)-byteOffset) {
  78233. byteOffset = -(int)pMP3->memory.currentReadPos;
  78234. }
  78235. }
  78236. pMP3->memory.currentReadPos += byteOffset;
  78237. } else {
  78238. if ((ma_uint32)byteOffset <= pMP3->memory.dataSize) {
  78239. pMP3->memory.currentReadPos = byteOffset;
  78240. } else {
  78241. pMP3->memory.currentReadPos = pMP3->memory.dataSize;
  78242. }
  78243. }
  78244. return MA_TRUE;
  78245. }
  78246. MA_API ma_bool32 ma_dr_mp3_init_memory(ma_dr_mp3* pMP3, const void* pData, size_t dataSize, const ma_allocation_callbacks* pAllocationCallbacks)
  78247. {
  78248. if (pMP3 == NULL) {
  78249. return MA_FALSE;
  78250. }
  78251. MA_DR_MP3_ZERO_OBJECT(pMP3);
  78252. if (pData == NULL || dataSize == 0) {
  78253. return MA_FALSE;
  78254. }
  78255. pMP3->memory.pData = (const ma_uint8*)pData;
  78256. pMP3->memory.dataSize = dataSize;
  78257. pMP3->memory.currentReadPos = 0;
  78258. return ma_dr_mp3_init_internal(pMP3, ma_dr_mp3__on_read_memory, ma_dr_mp3__on_seek_memory, pMP3, pAllocationCallbacks);
  78259. }
  78260. #ifndef MA_DR_MP3_NO_STDIO
  78261. #include <stdio.h>
  78262. #include <wchar.h>
  78263. static size_t ma_dr_mp3__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  78264. {
  78265. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  78266. }
  78267. static ma_bool32 ma_dr_mp3__on_seek_stdio(void* pUserData, int offset, ma_dr_mp3_seek_origin origin)
  78268. {
  78269. return fseek((FILE*)pUserData, offset, (origin == ma_dr_mp3_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  78270. }
  78271. MA_API ma_bool32 ma_dr_mp3_init_file(ma_dr_mp3* pMP3, const char* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks)
  78272. {
  78273. ma_bool32 result;
  78274. FILE* pFile;
  78275. if (ma_fopen(&pFile, pFilePath, "rb") != MA_SUCCESS) {
  78276. return MA_FALSE;
  78277. }
  78278. result = ma_dr_mp3_init(pMP3, ma_dr_mp3__on_read_stdio, ma_dr_mp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  78279. if (result != MA_TRUE) {
  78280. fclose(pFile);
  78281. return result;
  78282. }
  78283. return MA_TRUE;
  78284. }
  78285. MA_API ma_bool32 ma_dr_mp3_init_file_w(ma_dr_mp3* pMP3, const wchar_t* pFilePath, const ma_allocation_callbacks* pAllocationCallbacks)
  78286. {
  78287. ma_bool32 result;
  78288. FILE* pFile;
  78289. if (ma_wfopen(&pFile, pFilePath, L"rb", pAllocationCallbacks) != MA_SUCCESS) {
  78290. return MA_FALSE;
  78291. }
  78292. result = ma_dr_mp3_init(pMP3, ma_dr_mp3__on_read_stdio, ma_dr_mp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  78293. if (result != MA_TRUE) {
  78294. fclose(pFile);
  78295. return result;
  78296. }
  78297. return MA_TRUE;
  78298. }
  78299. #endif
  78300. MA_API void ma_dr_mp3_uninit(ma_dr_mp3* pMP3)
  78301. {
  78302. if (pMP3 == NULL) {
  78303. return;
  78304. }
  78305. #ifndef MA_DR_MP3_NO_STDIO
  78306. if (pMP3->onRead == ma_dr_mp3__on_read_stdio) {
  78307. FILE* pFile = (FILE*)pMP3->pUserData;
  78308. if (pFile != NULL) {
  78309. fclose(pFile);
  78310. pMP3->pUserData = NULL;
  78311. }
  78312. }
  78313. #endif
  78314. ma_dr_mp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
  78315. }
  78316. #if defined(MA_DR_MP3_FLOAT_OUTPUT)
  78317. static void ma_dr_mp3_f32_to_s16(ma_int16* dst, const float* src, ma_uint64 sampleCount)
  78318. {
  78319. ma_uint64 i;
  78320. ma_uint64 i4;
  78321. ma_uint64 sampleCount4;
  78322. i = 0;
  78323. sampleCount4 = sampleCount >> 2;
  78324. for (i4 = 0; i4 < sampleCount4; i4 += 1) {
  78325. float x0 = src[i+0];
  78326. float x1 = src[i+1];
  78327. float x2 = src[i+2];
  78328. float x3 = src[i+3];
  78329. x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
  78330. x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
  78331. x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
  78332. x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
  78333. x0 = x0 * 32767.0f;
  78334. x1 = x1 * 32767.0f;
  78335. x2 = x2 * 32767.0f;
  78336. x3 = x3 * 32767.0f;
  78337. dst[i+0] = (ma_int16)x0;
  78338. dst[i+1] = (ma_int16)x1;
  78339. dst[i+2] = (ma_int16)x2;
  78340. dst[i+3] = (ma_int16)x3;
  78341. i += 4;
  78342. }
  78343. for (; i < sampleCount; i += 1) {
  78344. float x = src[i];
  78345. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  78346. x = x * 32767.0f;
  78347. dst[i] = (ma_int16)x;
  78348. }
  78349. }
  78350. #endif
  78351. #if !defined(MA_DR_MP3_FLOAT_OUTPUT)
  78352. static void ma_dr_mp3_s16_to_f32(float* dst, const ma_int16* src, ma_uint64 sampleCount)
  78353. {
  78354. ma_uint64 i;
  78355. for (i = 0; i < sampleCount; i += 1) {
  78356. float x = (float)src[i];
  78357. x = x * 0.000030517578125f;
  78358. dst[i] = x;
  78359. }
  78360. }
  78361. #endif
  78362. static ma_uint64 ma_dr_mp3_read_pcm_frames_raw(ma_dr_mp3* pMP3, ma_uint64 framesToRead, void* pBufferOut)
  78363. {
  78364. ma_uint64 totalFramesRead = 0;
  78365. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78366. MA_DR_MP3_ASSERT(pMP3->onRead != NULL);
  78367. while (framesToRead > 0) {
  78368. ma_uint32 framesToConsume = (ma_uint32)MA_DR_MP3_MIN(pMP3->pcmFramesRemainingInMP3Frame, framesToRead);
  78369. if (pBufferOut != NULL) {
  78370. #if defined(MA_DR_MP3_FLOAT_OUTPUT)
  78371. float* pFramesOutF32 = (float*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalFramesRead * pMP3->channels);
  78372. float* pFramesInF32 = (float*)MA_DR_MP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(float) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
  78373. MA_DR_MP3_COPY_MEMORY(pFramesOutF32, pFramesInF32, sizeof(float) * framesToConsume * pMP3->channels);
  78374. #else
  78375. ma_int16* pFramesOutS16 = (ma_int16*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(ma_int16) * totalFramesRead * pMP3->channels);
  78376. ma_int16* pFramesInS16 = (ma_int16*)MA_DR_MP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(ma_int16) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
  78377. MA_DR_MP3_COPY_MEMORY(pFramesOutS16, pFramesInS16, sizeof(ma_int16) * framesToConsume * pMP3->channels);
  78378. #endif
  78379. }
  78380. pMP3->currentPCMFrame += framesToConsume;
  78381. pMP3->pcmFramesConsumedInMP3Frame += framesToConsume;
  78382. pMP3->pcmFramesRemainingInMP3Frame -= framesToConsume;
  78383. totalFramesRead += framesToConsume;
  78384. framesToRead -= framesToConsume;
  78385. if (framesToRead == 0) {
  78386. break;
  78387. }
  78388. MA_DR_MP3_ASSERT(pMP3->pcmFramesRemainingInMP3Frame == 0);
  78389. if (ma_dr_mp3_decode_next_frame(pMP3) == 0) {
  78390. break;
  78391. }
  78392. }
  78393. return totalFramesRead;
  78394. }
  78395. MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_f32(ma_dr_mp3* pMP3, ma_uint64 framesToRead, float* pBufferOut)
  78396. {
  78397. if (pMP3 == NULL || pMP3->onRead == NULL) {
  78398. return 0;
  78399. }
  78400. #if defined(MA_DR_MP3_FLOAT_OUTPUT)
  78401. return ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
  78402. #else
  78403. {
  78404. ma_int16 pTempS16[8192];
  78405. ma_uint64 totalPCMFramesRead = 0;
  78406. while (totalPCMFramesRead < framesToRead) {
  78407. ma_uint64 framesJustRead;
  78408. ma_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
  78409. ma_uint64 framesToReadNow = MA_DR_MP3_COUNTOF(pTempS16) / pMP3->channels;
  78410. if (framesToReadNow > framesRemaining) {
  78411. framesToReadNow = framesRemaining;
  78412. }
  78413. framesJustRead = ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempS16);
  78414. if (framesJustRead == 0) {
  78415. break;
  78416. }
  78417. ma_dr_mp3_s16_to_f32((float*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalPCMFramesRead * pMP3->channels), pTempS16, framesJustRead * pMP3->channels);
  78418. totalPCMFramesRead += framesJustRead;
  78419. }
  78420. return totalPCMFramesRead;
  78421. }
  78422. #endif
  78423. }
  78424. MA_API ma_uint64 ma_dr_mp3_read_pcm_frames_s16(ma_dr_mp3* pMP3, ma_uint64 framesToRead, ma_int16* pBufferOut)
  78425. {
  78426. if (pMP3 == NULL || pMP3->onRead == NULL) {
  78427. return 0;
  78428. }
  78429. #if !defined(MA_DR_MP3_FLOAT_OUTPUT)
  78430. return ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
  78431. #else
  78432. {
  78433. float pTempF32[4096];
  78434. ma_uint64 totalPCMFramesRead = 0;
  78435. while (totalPCMFramesRead < framesToRead) {
  78436. ma_uint64 framesJustRead;
  78437. ma_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
  78438. ma_uint64 framesToReadNow = MA_DR_MP3_COUNTOF(pTempF32) / pMP3->channels;
  78439. if (framesToReadNow > framesRemaining) {
  78440. framesToReadNow = framesRemaining;
  78441. }
  78442. framesJustRead = ma_dr_mp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempF32);
  78443. if (framesJustRead == 0) {
  78444. break;
  78445. }
  78446. ma_dr_mp3_f32_to_s16((ma_int16*)MA_DR_MP3_OFFSET_PTR(pBufferOut, sizeof(ma_int16) * totalPCMFramesRead * pMP3->channels), pTempF32, framesJustRead * pMP3->channels);
  78447. totalPCMFramesRead += framesJustRead;
  78448. }
  78449. return totalPCMFramesRead;
  78450. }
  78451. #endif
  78452. }
  78453. static void ma_dr_mp3_reset(ma_dr_mp3* pMP3)
  78454. {
  78455. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78456. pMP3->pcmFramesConsumedInMP3Frame = 0;
  78457. pMP3->pcmFramesRemainingInMP3Frame = 0;
  78458. pMP3->currentPCMFrame = 0;
  78459. pMP3->dataSize = 0;
  78460. pMP3->atEnd = MA_FALSE;
  78461. ma_dr_mp3dec_init(&pMP3->decoder);
  78462. }
  78463. static ma_bool32 ma_dr_mp3_seek_to_start_of_stream(ma_dr_mp3* pMP3)
  78464. {
  78465. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78466. MA_DR_MP3_ASSERT(pMP3->onSeek != NULL);
  78467. if (!ma_dr_mp3__on_seek(pMP3, 0, ma_dr_mp3_seek_origin_start)) {
  78468. return MA_FALSE;
  78469. }
  78470. ma_dr_mp3_reset(pMP3);
  78471. return MA_TRUE;
  78472. }
  78473. static ma_bool32 ma_dr_mp3_seek_forward_by_pcm_frames__brute_force(ma_dr_mp3* pMP3, ma_uint64 frameOffset)
  78474. {
  78475. ma_uint64 framesRead;
  78476. #if defined(MA_DR_MP3_FLOAT_OUTPUT)
  78477. framesRead = ma_dr_mp3_read_pcm_frames_f32(pMP3, frameOffset, NULL);
  78478. #else
  78479. framesRead = ma_dr_mp3_read_pcm_frames_s16(pMP3, frameOffset, NULL);
  78480. #endif
  78481. if (framesRead != frameOffset) {
  78482. return MA_FALSE;
  78483. }
  78484. return MA_TRUE;
  78485. }
  78486. static ma_bool32 ma_dr_mp3_seek_to_pcm_frame__brute_force(ma_dr_mp3* pMP3, ma_uint64 frameIndex)
  78487. {
  78488. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78489. if (frameIndex == pMP3->currentPCMFrame) {
  78490. return MA_TRUE;
  78491. }
  78492. if (frameIndex < pMP3->currentPCMFrame) {
  78493. if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) {
  78494. return MA_FALSE;
  78495. }
  78496. }
  78497. MA_DR_MP3_ASSERT(frameIndex >= pMP3->currentPCMFrame);
  78498. return ma_dr_mp3_seek_forward_by_pcm_frames__brute_force(pMP3, (frameIndex - pMP3->currentPCMFrame));
  78499. }
  78500. static ma_bool32 ma_dr_mp3_find_closest_seek_point(ma_dr_mp3* pMP3, ma_uint64 frameIndex, ma_uint32* pSeekPointIndex)
  78501. {
  78502. ma_uint32 iSeekPoint;
  78503. MA_DR_MP3_ASSERT(pSeekPointIndex != NULL);
  78504. *pSeekPointIndex = 0;
  78505. if (frameIndex < pMP3->pSeekPoints[0].pcmFrameIndex) {
  78506. return MA_FALSE;
  78507. }
  78508. for (iSeekPoint = 0; iSeekPoint < pMP3->seekPointCount; ++iSeekPoint) {
  78509. if (pMP3->pSeekPoints[iSeekPoint].pcmFrameIndex > frameIndex) {
  78510. break;
  78511. }
  78512. *pSeekPointIndex = iSeekPoint;
  78513. }
  78514. return MA_TRUE;
  78515. }
  78516. static ma_bool32 ma_dr_mp3_seek_to_pcm_frame__seek_table(ma_dr_mp3* pMP3, ma_uint64 frameIndex)
  78517. {
  78518. ma_dr_mp3_seek_point seekPoint;
  78519. ma_uint32 priorSeekPointIndex;
  78520. ma_uint16 iMP3Frame;
  78521. ma_uint64 leftoverFrames;
  78522. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78523. MA_DR_MP3_ASSERT(pMP3->pSeekPoints != NULL);
  78524. MA_DR_MP3_ASSERT(pMP3->seekPointCount > 0);
  78525. if (ma_dr_mp3_find_closest_seek_point(pMP3, frameIndex, &priorSeekPointIndex)) {
  78526. seekPoint = pMP3->pSeekPoints[priorSeekPointIndex];
  78527. } else {
  78528. seekPoint.seekPosInBytes = 0;
  78529. seekPoint.pcmFrameIndex = 0;
  78530. seekPoint.mp3FramesToDiscard = 0;
  78531. seekPoint.pcmFramesToDiscard = 0;
  78532. }
  78533. if (!ma_dr_mp3__on_seek_64(pMP3, seekPoint.seekPosInBytes, ma_dr_mp3_seek_origin_start)) {
  78534. return MA_FALSE;
  78535. }
  78536. ma_dr_mp3_reset(pMP3);
  78537. for (iMP3Frame = 0; iMP3Frame < seekPoint.mp3FramesToDiscard; ++iMP3Frame) {
  78538. ma_uint32 pcmFramesRead;
  78539. ma_dr_mp3d_sample_t* pPCMFrames;
  78540. pPCMFrames = NULL;
  78541. if (iMP3Frame == seekPoint.mp3FramesToDiscard-1) {
  78542. pPCMFrames = (ma_dr_mp3d_sample_t*)pMP3->pcmFrames;
  78543. }
  78544. pcmFramesRead = ma_dr_mp3_decode_next_frame_ex(pMP3, pPCMFrames);
  78545. if (pcmFramesRead == 0) {
  78546. return MA_FALSE;
  78547. }
  78548. }
  78549. pMP3->currentPCMFrame = seekPoint.pcmFrameIndex - seekPoint.pcmFramesToDiscard;
  78550. leftoverFrames = frameIndex - pMP3->currentPCMFrame;
  78551. return ma_dr_mp3_seek_forward_by_pcm_frames__brute_force(pMP3, leftoverFrames);
  78552. }
  78553. MA_API ma_bool32 ma_dr_mp3_seek_to_pcm_frame(ma_dr_mp3* pMP3, ma_uint64 frameIndex)
  78554. {
  78555. if (pMP3 == NULL || pMP3->onSeek == NULL) {
  78556. return MA_FALSE;
  78557. }
  78558. if (frameIndex == 0) {
  78559. return ma_dr_mp3_seek_to_start_of_stream(pMP3);
  78560. }
  78561. if (pMP3->pSeekPoints != NULL && pMP3->seekPointCount > 0) {
  78562. return ma_dr_mp3_seek_to_pcm_frame__seek_table(pMP3, frameIndex);
  78563. } else {
  78564. return ma_dr_mp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex);
  78565. }
  78566. }
  78567. MA_API ma_bool32 ma_dr_mp3_get_mp3_and_pcm_frame_count(ma_dr_mp3* pMP3, ma_uint64* pMP3FrameCount, ma_uint64* pPCMFrameCount)
  78568. {
  78569. ma_uint64 currentPCMFrame;
  78570. ma_uint64 totalPCMFrameCount;
  78571. ma_uint64 totalMP3FrameCount;
  78572. if (pMP3 == NULL) {
  78573. return MA_FALSE;
  78574. }
  78575. if (pMP3->onSeek == NULL) {
  78576. return MA_FALSE;
  78577. }
  78578. currentPCMFrame = pMP3->currentPCMFrame;
  78579. if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) {
  78580. return MA_FALSE;
  78581. }
  78582. totalPCMFrameCount = 0;
  78583. totalMP3FrameCount = 0;
  78584. for (;;) {
  78585. ma_uint32 pcmFramesInCurrentMP3Frame;
  78586. pcmFramesInCurrentMP3Frame = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL);
  78587. if (pcmFramesInCurrentMP3Frame == 0) {
  78588. break;
  78589. }
  78590. totalPCMFrameCount += pcmFramesInCurrentMP3Frame;
  78591. totalMP3FrameCount += 1;
  78592. }
  78593. if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) {
  78594. return MA_FALSE;
  78595. }
  78596. if (!ma_dr_mp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
  78597. return MA_FALSE;
  78598. }
  78599. if (pMP3FrameCount != NULL) {
  78600. *pMP3FrameCount = totalMP3FrameCount;
  78601. }
  78602. if (pPCMFrameCount != NULL) {
  78603. *pPCMFrameCount = totalPCMFrameCount;
  78604. }
  78605. return MA_TRUE;
  78606. }
  78607. MA_API ma_uint64 ma_dr_mp3_get_pcm_frame_count(ma_dr_mp3* pMP3)
  78608. {
  78609. ma_uint64 totalPCMFrameCount;
  78610. if (!ma_dr_mp3_get_mp3_and_pcm_frame_count(pMP3, NULL, &totalPCMFrameCount)) {
  78611. return 0;
  78612. }
  78613. return totalPCMFrameCount;
  78614. }
  78615. MA_API ma_uint64 ma_dr_mp3_get_mp3_frame_count(ma_dr_mp3* pMP3)
  78616. {
  78617. ma_uint64 totalMP3FrameCount;
  78618. if (!ma_dr_mp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, NULL)) {
  78619. return 0;
  78620. }
  78621. return totalMP3FrameCount;
  78622. }
  78623. static void ma_dr_mp3__accumulate_running_pcm_frame_count(ma_dr_mp3* pMP3, ma_uint32 pcmFrameCountIn, ma_uint64* pRunningPCMFrameCount, float* pRunningPCMFrameCountFractionalPart)
  78624. {
  78625. float srcRatio;
  78626. float pcmFrameCountOutF;
  78627. ma_uint32 pcmFrameCountOut;
  78628. srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate;
  78629. MA_DR_MP3_ASSERT(srcRatio > 0);
  78630. pcmFrameCountOutF = *pRunningPCMFrameCountFractionalPart + (pcmFrameCountIn / srcRatio);
  78631. pcmFrameCountOut = (ma_uint32)pcmFrameCountOutF;
  78632. *pRunningPCMFrameCountFractionalPart = pcmFrameCountOutF - pcmFrameCountOut;
  78633. *pRunningPCMFrameCount += pcmFrameCountOut;
  78634. }
  78635. typedef struct
  78636. {
  78637. ma_uint64 bytePos;
  78638. ma_uint64 pcmFrameIndex;
  78639. } ma_dr_mp3__seeking_mp3_frame_info;
  78640. MA_API ma_bool32 ma_dr_mp3_calculate_seek_points(ma_dr_mp3* pMP3, ma_uint32* pSeekPointCount, ma_dr_mp3_seek_point* pSeekPoints)
  78641. {
  78642. ma_uint32 seekPointCount;
  78643. ma_uint64 currentPCMFrame;
  78644. ma_uint64 totalMP3FrameCount;
  78645. ma_uint64 totalPCMFrameCount;
  78646. if (pMP3 == NULL || pSeekPointCount == NULL || pSeekPoints == NULL) {
  78647. return MA_FALSE;
  78648. }
  78649. seekPointCount = *pSeekPointCount;
  78650. if (seekPointCount == 0) {
  78651. return MA_FALSE;
  78652. }
  78653. currentPCMFrame = pMP3->currentPCMFrame;
  78654. if (!ma_dr_mp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, &totalPCMFrameCount)) {
  78655. return MA_FALSE;
  78656. }
  78657. if (totalMP3FrameCount < MA_DR_MP3_SEEK_LEADING_MP3_FRAMES+1) {
  78658. seekPointCount = 1;
  78659. pSeekPoints[0].seekPosInBytes = 0;
  78660. pSeekPoints[0].pcmFrameIndex = 0;
  78661. pSeekPoints[0].mp3FramesToDiscard = 0;
  78662. pSeekPoints[0].pcmFramesToDiscard = 0;
  78663. } else {
  78664. ma_uint64 pcmFramesBetweenSeekPoints;
  78665. ma_dr_mp3__seeking_mp3_frame_info mp3FrameInfo[MA_DR_MP3_SEEK_LEADING_MP3_FRAMES+1];
  78666. ma_uint64 runningPCMFrameCount = 0;
  78667. float runningPCMFrameCountFractionalPart = 0;
  78668. ma_uint64 nextTargetPCMFrame;
  78669. ma_uint32 iMP3Frame;
  78670. ma_uint32 iSeekPoint;
  78671. if (seekPointCount > totalMP3FrameCount-1) {
  78672. seekPointCount = (ma_uint32)totalMP3FrameCount-1;
  78673. }
  78674. pcmFramesBetweenSeekPoints = totalPCMFrameCount / (seekPointCount+1);
  78675. if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) {
  78676. return MA_FALSE;
  78677. }
  78678. for (iMP3Frame = 0; iMP3Frame < MA_DR_MP3_SEEK_LEADING_MP3_FRAMES+1; ++iMP3Frame) {
  78679. ma_uint32 pcmFramesInCurrentMP3FrameIn;
  78680. MA_DR_MP3_ASSERT(pMP3->streamCursor >= pMP3->dataSize);
  78681. mp3FrameInfo[iMP3Frame].bytePos = pMP3->streamCursor - pMP3->dataSize;
  78682. mp3FrameInfo[iMP3Frame].pcmFrameIndex = runningPCMFrameCount;
  78683. pcmFramesInCurrentMP3FrameIn = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL);
  78684. if (pcmFramesInCurrentMP3FrameIn == 0) {
  78685. return MA_FALSE;
  78686. }
  78687. ma_dr_mp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
  78688. }
  78689. nextTargetPCMFrame = 0;
  78690. for (iSeekPoint = 0; iSeekPoint < seekPointCount; ++iSeekPoint) {
  78691. nextTargetPCMFrame += pcmFramesBetweenSeekPoints;
  78692. for (;;) {
  78693. if (nextTargetPCMFrame < runningPCMFrameCount) {
  78694. pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
  78695. pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
  78696. pSeekPoints[iSeekPoint].mp3FramesToDiscard = MA_DR_MP3_SEEK_LEADING_MP3_FRAMES;
  78697. pSeekPoints[iSeekPoint].pcmFramesToDiscard = (ma_uint16)(nextTargetPCMFrame - mp3FrameInfo[MA_DR_MP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
  78698. break;
  78699. } else {
  78700. size_t i;
  78701. ma_uint32 pcmFramesInCurrentMP3FrameIn;
  78702. for (i = 0; i < MA_DR_MP3_COUNTOF(mp3FrameInfo)-1; ++i) {
  78703. mp3FrameInfo[i] = mp3FrameInfo[i+1];
  78704. }
  78705. mp3FrameInfo[MA_DR_MP3_COUNTOF(mp3FrameInfo)-1].bytePos = pMP3->streamCursor - pMP3->dataSize;
  78706. mp3FrameInfo[MA_DR_MP3_COUNTOF(mp3FrameInfo)-1].pcmFrameIndex = runningPCMFrameCount;
  78707. pcmFramesInCurrentMP3FrameIn = ma_dr_mp3_decode_next_frame_ex(pMP3, NULL);
  78708. if (pcmFramesInCurrentMP3FrameIn == 0) {
  78709. pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
  78710. pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
  78711. pSeekPoints[iSeekPoint].mp3FramesToDiscard = MA_DR_MP3_SEEK_LEADING_MP3_FRAMES;
  78712. pSeekPoints[iSeekPoint].pcmFramesToDiscard = (ma_uint16)(nextTargetPCMFrame - mp3FrameInfo[MA_DR_MP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
  78713. break;
  78714. }
  78715. ma_dr_mp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
  78716. }
  78717. }
  78718. }
  78719. if (!ma_dr_mp3_seek_to_start_of_stream(pMP3)) {
  78720. return MA_FALSE;
  78721. }
  78722. if (!ma_dr_mp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
  78723. return MA_FALSE;
  78724. }
  78725. }
  78726. *pSeekPointCount = seekPointCount;
  78727. return MA_TRUE;
  78728. }
  78729. MA_API ma_bool32 ma_dr_mp3_bind_seek_table(ma_dr_mp3* pMP3, ma_uint32 seekPointCount, ma_dr_mp3_seek_point* pSeekPoints)
  78730. {
  78731. if (pMP3 == NULL) {
  78732. return MA_FALSE;
  78733. }
  78734. if (seekPointCount == 0 || pSeekPoints == NULL) {
  78735. pMP3->seekPointCount = 0;
  78736. pMP3->pSeekPoints = NULL;
  78737. } else {
  78738. pMP3->seekPointCount = seekPointCount;
  78739. pMP3->pSeekPoints = pSeekPoints;
  78740. }
  78741. return MA_TRUE;
  78742. }
  78743. static float* ma_dr_mp3__full_read_and_close_f32(ma_dr_mp3* pMP3, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount)
  78744. {
  78745. ma_uint64 totalFramesRead = 0;
  78746. ma_uint64 framesCapacity = 0;
  78747. float* pFrames = NULL;
  78748. float temp[4096];
  78749. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78750. for (;;) {
  78751. ma_uint64 framesToReadRightNow = MA_DR_MP3_COUNTOF(temp) / pMP3->channels;
  78752. ma_uint64 framesJustRead = ma_dr_mp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp);
  78753. if (framesJustRead == 0) {
  78754. break;
  78755. }
  78756. if (framesCapacity < totalFramesRead + framesJustRead) {
  78757. ma_uint64 oldFramesBufferSize;
  78758. ma_uint64 newFramesBufferSize;
  78759. ma_uint64 newFramesCap;
  78760. float* pNewFrames;
  78761. newFramesCap = framesCapacity * 2;
  78762. if (newFramesCap < totalFramesRead + framesJustRead) {
  78763. newFramesCap = totalFramesRead + framesJustRead;
  78764. }
  78765. oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(float);
  78766. newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(float);
  78767. if (newFramesBufferSize > (ma_uint64)MA_SIZE_MAX) {
  78768. break;
  78769. }
  78770. pNewFrames = (float*)ma_dr_mp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
  78771. if (pNewFrames == NULL) {
  78772. ma_dr_mp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
  78773. break;
  78774. }
  78775. pFrames = pNewFrames;
  78776. framesCapacity = newFramesCap;
  78777. }
  78778. MA_DR_MP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(float)));
  78779. totalFramesRead += framesJustRead;
  78780. if (framesJustRead != framesToReadRightNow) {
  78781. break;
  78782. }
  78783. }
  78784. if (pConfig != NULL) {
  78785. pConfig->channels = pMP3->channels;
  78786. pConfig->sampleRate = pMP3->sampleRate;
  78787. }
  78788. ma_dr_mp3_uninit(pMP3);
  78789. if (pTotalFrameCount) {
  78790. *pTotalFrameCount = totalFramesRead;
  78791. }
  78792. return pFrames;
  78793. }
  78794. static ma_int16* ma_dr_mp3__full_read_and_close_s16(ma_dr_mp3* pMP3, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount)
  78795. {
  78796. ma_uint64 totalFramesRead = 0;
  78797. ma_uint64 framesCapacity = 0;
  78798. ma_int16* pFrames = NULL;
  78799. ma_int16 temp[4096];
  78800. MA_DR_MP3_ASSERT(pMP3 != NULL);
  78801. for (;;) {
  78802. ma_uint64 framesToReadRightNow = MA_DR_MP3_COUNTOF(temp) / pMP3->channels;
  78803. ma_uint64 framesJustRead = ma_dr_mp3_read_pcm_frames_s16(pMP3, framesToReadRightNow, temp);
  78804. if (framesJustRead == 0) {
  78805. break;
  78806. }
  78807. if (framesCapacity < totalFramesRead + framesJustRead) {
  78808. ma_uint64 newFramesBufferSize;
  78809. ma_uint64 oldFramesBufferSize;
  78810. ma_uint64 newFramesCap;
  78811. ma_int16* pNewFrames;
  78812. newFramesCap = framesCapacity * 2;
  78813. if (newFramesCap < totalFramesRead + framesJustRead) {
  78814. newFramesCap = totalFramesRead + framesJustRead;
  78815. }
  78816. oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(ma_int16);
  78817. newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(ma_int16);
  78818. if (newFramesBufferSize > (ma_uint64)MA_SIZE_MAX) {
  78819. break;
  78820. }
  78821. pNewFrames = (ma_int16*)ma_dr_mp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
  78822. if (pNewFrames == NULL) {
  78823. ma_dr_mp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
  78824. break;
  78825. }
  78826. pFrames = pNewFrames;
  78827. framesCapacity = newFramesCap;
  78828. }
  78829. MA_DR_MP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(ma_int16)));
  78830. totalFramesRead += framesJustRead;
  78831. if (framesJustRead != framesToReadRightNow) {
  78832. break;
  78833. }
  78834. }
  78835. if (pConfig != NULL) {
  78836. pConfig->channels = pMP3->channels;
  78837. pConfig->sampleRate = pMP3->sampleRate;
  78838. }
  78839. ma_dr_mp3_uninit(pMP3);
  78840. if (pTotalFrameCount) {
  78841. *pTotalFrameCount = totalFramesRead;
  78842. }
  78843. return pFrames;
  78844. }
  78845. MA_API float* ma_dr_mp3_open_and_read_pcm_frames_f32(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  78846. {
  78847. ma_dr_mp3 mp3;
  78848. if (!ma_dr_mp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  78849. return NULL;
  78850. }
  78851. return ma_dr_mp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  78852. }
  78853. MA_API ma_int16* ma_dr_mp3_open_and_read_pcm_frames_s16(ma_dr_mp3_read_proc onRead, ma_dr_mp3_seek_proc onSeek, void* pUserData, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  78854. {
  78855. ma_dr_mp3 mp3;
  78856. if (!ma_dr_mp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  78857. return NULL;
  78858. }
  78859. return ma_dr_mp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  78860. }
  78861. MA_API float* ma_dr_mp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  78862. {
  78863. ma_dr_mp3 mp3;
  78864. if (!ma_dr_mp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
  78865. return NULL;
  78866. }
  78867. return ma_dr_mp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  78868. }
  78869. MA_API ma_int16* ma_dr_mp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  78870. {
  78871. ma_dr_mp3 mp3;
  78872. if (!ma_dr_mp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
  78873. return NULL;
  78874. }
  78875. return ma_dr_mp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  78876. }
  78877. #ifndef MA_DR_MP3_NO_STDIO
  78878. MA_API float* ma_dr_mp3_open_file_and_read_pcm_frames_f32(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  78879. {
  78880. ma_dr_mp3 mp3;
  78881. if (!ma_dr_mp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
  78882. return NULL;
  78883. }
  78884. return ma_dr_mp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  78885. }
  78886. MA_API ma_int16* ma_dr_mp3_open_file_and_read_pcm_frames_s16(const char* filePath, ma_dr_mp3_config* pConfig, ma_uint64* pTotalFrameCount, const ma_allocation_callbacks* pAllocationCallbacks)
  78887. {
  78888. ma_dr_mp3 mp3;
  78889. if (!ma_dr_mp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
  78890. return NULL;
  78891. }
  78892. return ma_dr_mp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  78893. }
  78894. #endif
  78895. MA_API void* ma_dr_mp3_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  78896. {
  78897. if (pAllocationCallbacks != NULL) {
  78898. return ma_dr_mp3__malloc_from_callbacks(sz, pAllocationCallbacks);
  78899. } else {
  78900. return ma_dr_mp3__malloc_default(sz, NULL);
  78901. }
  78902. }
  78903. MA_API void ma_dr_mp3_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  78904. {
  78905. if (pAllocationCallbacks != NULL) {
  78906. ma_dr_mp3__free_from_callbacks(p, pAllocationCallbacks);
  78907. } else {
  78908. ma_dr_mp3__free_default(p, NULL);
  78909. }
  78910. }
  78911. #endif
  78912. /* dr_mp3_c end */
  78913. #endif /* MA_DR_MP3_IMPLEMENTATION */
  78914. #endif /* MA_NO_MP3 */
  78915. /* End globally disabled warnings. */
  78916. #if defined(_MSC_VER)
  78917. #pragma warning(pop)
  78918. #endif
  78919. #endif /* miniaudio_c */
  78920. #endif /* MINIAUDIO_IMPLEMENTATION */
  78921. /*
  78922. This software is available as a choice of the following licenses. Choose
  78923. whichever you prefer.
  78924. ===============================================================================
  78925. ALTERNATIVE 1 - Public Domain (www.unlicense.org)
  78926. ===============================================================================
  78927. This is free and unencumbered software released into the public domain.
  78928. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  78929. software, either in source code form or as a compiled binary, for any purpose,
  78930. commercial or non-commercial, and by any means.
  78931. In jurisdictions that recognize copyright laws, the author or authors of this
  78932. software dedicate any and all copyright interest in the software to the public
  78933. domain. We make this dedication for the benefit of the public at large and to
  78934. the detriment of our heirs and successors. We intend this dedication to be an
  78935. overt act of relinquishment in perpetuity of all present and future rights to
  78936. this software under copyright law.
  78937. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  78938. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  78939. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  78940. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  78941. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  78942. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  78943. For more information, please refer to <http://unlicense.org/>
  78944. ===============================================================================
  78945. ALTERNATIVE 2 - MIT No Attribution
  78946. ===============================================================================
  78947. Copyright 2023 David Reid
  78948. Permission is hereby granted, free of charge, to any person obtaining a copy of
  78949. this software and associated documentation files (the "Software"), to deal in
  78950. the Software without restriction, including without limitation the rights to
  78951. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  78952. of the Software, and to permit persons to whom the Software is furnished to do
  78953. so.
  78954. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  78955. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  78956. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  78957. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  78958. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  78959. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  78960. SOFTWARE.
  78961. */